热升级与排错
约 762 字大约 3 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 运维与安全(在新窗口打开) › 热升级与排错
热升级(不停机更新 Nginx 二进制)
# 1. 备份旧二进制
cp /usr/sbin/nginx /usr/sbin/nginx.old
# 2. 安装新版本
# 使用包管理器或编译安装
# 3. 发送 USR2 信号启动新 Master
kill -USR2 $(cat /var/run/nginx.pid)
# 4. 通知旧 Worker 优雅退出
kill -WINCH $(cat /var/run/nginx.pid)
# 5. 验证新版本
nginx -v
# nginx version: nginx/1.26.0
# 6. 如果需要回滚
# 恢复旧二进制,发送 HUP 信号
cp /usr/sbin/nginx.old /usr/sbin/nginx
kill -HUP $(cat /var/run/nginx.pid)配置语法检查
# 标准检查
sudo nginx -t
# nginx: the configuration file syntax is ok
# nginx: configuration file test is successful
# 打印完整的有效配置
sudo nginx -T
# 指定配置文件检查
sudo nginx -t -c /etc/nginx/nginx.conf常见错误排查
Permission Denied
# 检查日志文件权限
ls -la /var/log/nginx/
# 应属于 nginx 用户或 www-data
# 修复
sudo chown -R nginx:nginx /var/log/nginx/
# 检查 socket 绑定权限
# Linux 上 1024 以下端口需要 root 权限
# 使用 authbind 或 setcap 让普通用户绑定低端口
sudo setcap cap_net_bind_service=+ep /usr/sbin/nginx端口冲突
# 检查端口占用
sudo lsof -i :80
sudo netstat -tlnp | grep :80
# 修改配置换端口
# listen 8080;502 Bad Gateway
# 后端服务未启动
systemctl status backend
# 重启后端服务
# 防火墙阻止连接
# 检查后端端口防火墙规则
# 网络不通
# 检查 upstream 地址是否正确配置重载失败
# 检查语法
sudo nginx -t
# 查看错误日志
tail -f /var/log/nginx/error.log
# 常见原因
# - 文件权限错误(SSL 证书不可读)
# - 端口冲突
# - include 的文件不存在调试模式
# 临时开启调试日志(修改配置后 reload)
error_log /var/log/nginx/error.log debug;
# 查看调试日志
tail -f /var/log/nginx/error.log常用调试命令
# 查看 Nginx 进程
ps -ef | grep nginx
# 查看 Nginx 版本和编译参数
nginx -V
# 检查 SSL 证书
openssl x509 -in /etc/ssl/certs/example.crt -text -noout
# curl 调试
curl -v http://example.com # 查看请求/响应头
curl -I https://example.com # 仅查看响应头
curl -k https://example.com # 忽略 SSL 证书错误
# DNS 排查
dig example.com
nslookup example.com
# 跟踪请求路径
curl -H "Host: example.com" http://127.0.0.1配置回滚
# 方法 1:用版本管理
cd /etc/nginx
git init
git add .
git commit -m "初始配置"
# 修改前提交
git commit -am "修改前备份"
# 回滚
git checkout <previous-commit> -- nginx.conf性能诊断
# 查看状态页
curl http://127.0.0.1/nginx_status
# 分析慢请求
awk '{print $NF, $0}' /var/log/nginx/access.log | sort -rn | head -20
# 监控连接数
watch -n 1 'curl -s http://127.0.0.1/nginx_status'
# 查看 worker 进程数
ps -ef | grep "nginx: worker" | wc -l小结
- 热升级:
kill -USR2启动新 Master,kill -WINCH优雅退出旧 Worker。 nginx -t检查配置语法,nginx -T输出完整展开配置。- 常见问题:权限(日志/端口)、端口冲突(
lsof -i :80)、后端不通(502)。 - 调试日志
error_log ... debug获取详细信息。 - 配置回滚用 Git 管理最简单。
stub_status+ 日志分析命令组合监控性能。
上一节:安全加固
