跳转至

日常运维工作

创建于:2025-08-24 最后更新:2025-09-16


简介说明

本节记录的实践内容为:部署好 Nginx 服务之后,需要进行的日常维护工作。

前置条件

  • 系统要求:Debian 12 (bookworm)
  • 相关工具:toppsdudffreeiostatvmstatsarss

安装与配置

技巧

因为 top 工具更适合交互使用,所以不放入脚本中执行。你可以在执行脚本前使用 top 命令先后按下 PM ,排序观察系统 CPU、内存资源;然后按下 L 快速锁定 Nginx 相关进程,速览服务器当前进程状况。

下方提供的脚本通过 eval 将字符串传递给 shell 解析执行。对于每个单独的命令,格式化其输出,实现了简单的系统信息状态收集功能:

#!/usr/bin/env sh
# Script Name: nginx_maintenance.sh
# Author: Aina
# Data Created: 2025-08-25 | Data Modified: 2025-09-08

# Exit immediately if a command exits with a non-zero status
# Treat unset variables as an error and exit immediately
set -eu

# Check the permission
if [ $(id -u) -ne 0 ]; then
    echo 'This script must be run with `sudo`.'
    exit 1
fi

# Define variables
log_dir="/var/log/nginx"
current_date="$(date -I)"
report_dir="${HOME}/maintenance_reports"
report_file="${report_dir}/log_${current_date}.log"
website_dir="/var/www/html"

mkdir -p "${report_dir}"

print_head() {
    head_text="Outputs of the command \`${1}':"
    echo "${head_text}"
    printf "%0.s-" $(seq 1 $(expr length "${head_text}"))
    echo "\n\n\`\`\` sh"
}

command_exist() {
    command -v "${1}" > /dev/null 2>&1
    echo "${1} processing ..."
}

check_status() {
    if command_exist ${1}; then
        print_head "${1}" >> "${report_file}"
        eval "${1}" >> "${report_file}"
        echo "\`\`\`\n" >> "${report_file}"
    else
        echo "Command \`${1}' not found." >> "${report_file}"
    fi
}

# Check system resources and disk usage
check_status 'uptime'
check_status 'free -h'
check_status 'dmesg | tail -n 20'
check_status 'vmstat 1 4'
check_status 'df -h'
check_status 'du -h -d 1 "${website_dir}" | sort -rh | head -n 10'

# Check process status
check_status 'ps aux | grep [n]ginx'
check_status 'ps aux --sort=%cpu | head -n 10'
check_status 'ps aux --sort=%mem | head -n 10'

# Check network status
check_status 'ss -s'
check_status 'ss -tunlp'

# Performance monitoring commands
# check_status 'iostat -x 1 3'
# check_status 'sar -u 1 3'
# check_status 'sar -r 1 3'

故障排查

1. 某些字段无法正常显示

  • 问题描述:

    在收集到的日志中,某些字段无法正常显示。如 ss -tunlpprocess 字段为空。

  • 原因分析:

    通常是权限不足或系统限制导致。

  • 解决方案:

    优先通过 sudo 提升权限解决,如果无效,再排查 AppArmor / SELinux


附录:参考与链接