三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

liunx 开机自启脚本(nginx)

liunx 开机自启脚本(nginx)

🧩 Nginx 开机自启动 · 完整配置指南

记录于 2026-08-10 · 适用于 Linux 系统(systemd / init.d)

📌 场景说明

在 CentOS / Ubuntu 等 Linux 发行版中,通过源码编译安装的 Nginx 默认不会创建 systemd 服务文件,因此无法直接使用 systemctl enable nginx 实现开机自启。本文档提供两种主流方案,并附上手动创建 nginx.service 的详细步骤。

✅ 方案一:使用 systemd(推荐)

适用于 Ubuntu 16.04+ / CentOS 7+ / Debian 8+ 等现代发行版。

1. 确认 Nginx 安装路径

查找 Nginx 可执行文件与配置文件位置:

which nginx
# 或
find / -name "nginx" -type f 2>/dev/null

假设得到路径为 /usr/local/nginx/sbin/nginx,配置文件在 /usr/local/nginx/conf/nginx.conf

2. 手动创建 /etc/systemd/system/nginx.service

sudo vim /etc/systemd/system/nginx.service

将以下内容粘贴(根据实际路径修改):

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
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
Restart=on-failure
RestartSec=5[Install]
WantedBy=multi-user.target

3. 启用并启动服务

sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
✅ 成功标志: status 输出显示 active (running),且 enabled 状态为 enabled

🔄 方案二:使用 init.d / chkconfig(旧版系统)

适用于 CentOS 6 或更早版本(无 systemd)。

chkconfig --add nginx
chkconfig --level 2345 nginx on
service nginx start

但前提是已有 /etc/init.d/nginx 脚本,若没有可参考 systemd 单元自行编写。

⚠️ 故障排查

  • 配置文件语法错误:运行 sudo /usr/local/nginx/sbin/nginx -t 检查。
  • 错误日志:查看 /var/log/nginx/error.log/usr/local/nginx/logs/error.log
  • systemd 日志sudo journalctl -u nginx -n 20 --no-pager
  • 权限问题:确保 PID 文件目录(如 /usr/local/nginx/logs)可写。
⚠️ 常见错误: 如果执行 systemctl enable nginx 报错 No such file or directory,通常就是因为缺少 nginx.service 文件,按上述步骤创建即可解决。

📁 补充:将 Nginx 设为开机自启后,如何管理?

  • 启动:sudo systemctl start nginx
  • 停止:sudo systemctl stop nginx
  • 重启:sudo systemctl restart nginx
  • 重载配置(不中断服务):sudo systemctl reload nginx
  • 取消开机自启:sudo systemctl disable nginx

📝 结语

通过以上步骤,无论 Nginx 是 yum/apt 安装还是源码编译,都能完美实现开机自启动。将服务纳入 systemd 管理,是 Linux 运维的标准实践,也便于统一监控和日志管理。

若你遇到其他异常,欢迎查阅官方文档或检查系统日志,耐心定位总能找到根因。

 
← 返回列表