温馨提示×

怎样解决Ubuntu Nginx启动失败

小樊
35
2025-12-13 03:12:20
栏目: 智能运维

Ubuntu 上 Nginx 启动失败的排查与修复指南

一 快速定位

  • 检查配置语法与包含的目录片段是否无误:sudo nginx -t。若提示行号或文件错误,先修正后再启动。
  • 查看服务状态与最近日志:sudo systemctl status nginx -l,并实时跟踪错误日志:sudo tail -f /var/log/nginx/error.log
  • 若服务单元不存在:sudo systemctl status nginx 显示 Unit nginx.service not found,说明未通过包管理器安装或未正确注册服务,需要安装或创建 systemd 单元。
  • 若服务卡在启动阶段并超时,常见为 PID 文件路径不一致 或进程未能按预期转入后台,需核对 service 文件与实际 PID 文件位置。

二 常见原因与对应修复

  • 端口被占用:日志出现 bind() to 0.0.0.0:80 failed (98: Address already in use)。处理:sudo ss -tulnp | grep :80 查进程 PID,sudo kill -9 <PID> 释放端口,或把 Nginx 改为监听 8080/8443 等可用端口。
  • 配置文件语法或包含错误:sudo nginx -t 直接报行号;修复后再次测试。
  • 权限或目录不可达:日志出现 Permission denied。处理:确保网站根目录与日志目录对 www-data(或配置中指定的用户)可读/可写,例如 sudo chown -R www-data:www-data /var/www/html && sudo chmod -R 755 /var/www/html
  • PID 文件与 systemd 不一致:状态提示 Can’t open PID file /run/nginx.pid (yet?) after startinvalid PID number “”。处理:在 /lib/systemd/system/nginx.service[Service] 中设置 PIDFile=/run/nginx.pid,并确保 ExecStart 启动的进程会写入该路径;随后执行 sudo systemctl daemon-reload && sudo systemctl restart nginx
  • 服务单元未安装:提示 Unit nginx.service not found。处理:通过包管理器安装 sudo apt-get install nginx;若是源码安装,创建 /etc/systemd/system/nginx.service,示例关键项:ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.confExecReload=/usr/local/nginx/sbin/nginx -s reloadType=forkingPIDFile=/usr/local/nginx/logs/nginx.pid,然后 sudo systemctl daemon-reload && sudo systemctl enable --now nginx
  • 资源或系统限制:磁盘满导致写入失败,执行 df -lh 清理空间;文件句柄不足,调整 ulimit -n、在 /etc/security/limits.conf 设置 soft/hard nofile 65535,并在 nginx.conf 加入 worker_rlimit_nofile 65535;
  • 防火墙/安全策略阻断访问:Ubuntu 使用 ufw 放行端口:sudo ufw allow 80/tcp,443/tcp;如使用 SELinux(非 Ubuntu 默认),需调整策略或临时 setenforce 0 验证。

三 最小可用 systemd 单元示例

  • 适用于源码安装到 /usr/local/nginx 的场景,保存为 /etc/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • 生效与验证:sudo systemctl daemon-reload && sudo systemctl enable --now nginx && sudo systemctl status nginx

四 一键排查命令清单

# 1) 配置语法
sudo nginx -t

# 2) 服务状态与实时错误
sudo systemctl status nginx -l
sudo tail -f /var/log/nginx/error.log

# 3) 端口占用
sudo ss -tulnp | grep ':80\|:443'

# 4) 资源与句柄
df -lh
ulimit -n

# 5) 重新加载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx
sudo systemctl status nginx
  • 若仍失败,优先根据 error.log 的具体报错行号与关键词(如 “bind()”, “Permission denied”, “PID file”)对照上述修复项逐项处理。

0