阅读量:4
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释放端口,或把 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 start 或 invalid 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.conf、ExecReload=/usr/local/nginx/sbin/nginx -s reload、Type=forking、PIDFile=/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”)对照上述修复项逐项处理。
以上就是关于“怎样解决Ubuntu Nginx启动失败”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm