一、问题描述
在排除代码问题,一边去查看 Nginx 的错误日志。Nginx 是 root 用户安装的,查看日志必须加 sudo
,忽然发现日志一直在输出错误:
2018/09/20 16:14:38 [emerg] 23817#0: bind() to 0.0.0.0:8800 failed (98: Address already in use)
2018/09/20 16:14:38 [emerg] 23817#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/09/20 16:14:38 [emerg] 23817#0: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/09/20 16:14:38 [emerg] 23817#0: bind() to 0.0.0.0:8800 failed (98: Address already in use)
2018/09/20 16:14:38 [emerg] 23817#0: still could not bind()
二、原因查找
首先在 Nginx 中文文档 中找到 Nginx 主模块,找到 daemon
命令,官方给出的解释是:
语法: daemon on | off缺省值: on
Do not use the "daemon" and "master_process" directives in a production mode, these options are mainly used for development only. You can use
daemon off
大意:在生产环境中 daemon
和 master_process
配置均不可使用,仅用于开发测试。
为了方便开发测试 Nginx 的 daemon 参数默认值为 on。
然后找到 Nginx 的配置文件 /usr/local/nginx/conf/nginx.conf
,检索 daemon
参数。然后是意料之中 Pattern not found: daemon。
三、异常处理
方法1:直接在 nginx.conf 配置文件中增加 daemon off;
参数。
方法2:在启动 Nginx 时追加命令,命令为:
/usr/local/nginx/sbin/nginx -g 'daemon off;'
由于线上环境 Nginx 配置文件由 Supervisor 守护,所以直接修改 supervisord.conf:
[program:nginx]
command=/usr/local/nginx/sbin/nginx -g 'daemon off;'
directory=/usr/local/nginx
autostart=true
autorestart=true
redirect_stderr=true
priority=10
stdout_logfile=/data/logs/supervisord/nginx.log
四、重新加载
修改后记得更新 Supervisor 以及重启 Nginx 进程,命令:
supervisorctl reread # 重新读取配置
supervisorctl update # 更新配置
supervisorctl restart nginx # 重启 nginx
killall nginx # 杀掉所有的 nginx 进程