Linux 上设置 Nginx 开机自启
本教程将介绍如何通过 systemd 在 Linux 系统上配置 Nginx 开机自启,涵盖服务文件创建、配置项解析、服务管理与日志排查。
1. 创建服务文件
使用 vim 编辑 systemd 服务文件,路径为/etc/systemd/system/nginx.service:
vim/etc/systemd/system/nginx.service2. 配置文件详解
[Unit] Description=Nginx Web Server After=network.target- Description:服务描述,
systemctl status时显示。 - After:指定在网络服务就绪后再启动 Nginx,避免启动时网络不可用。
[Service] Type=forking PIDFile=/app/nginx/logs/nginx.pid ExecStartPre=/app/nginx/sbin/nginx -t -c /app/nginx/conf/nginx.conf ExecStart=/app/nginx/sbin/nginx -c /app/nginx/conf/nginx.conf ExecReload=/app/nginx/sbin/nginx -s reload ExecStop=/bin/kill -s QUIT $MAINPID LimitNOFILE=65535 Restart=on-failure RestartSec=5- Type=forking:表示 Nginx 启动后会派生子进程,主进程退出,systemd 通过 PIDFile 跟踪实际进程。
- PIDFile:指定 PID 文件路径,systemd 据此管理服务。
- ExecStartPre:启动前执行配置测试,确保配置文件语法正确,失败则不会启动。
- ExecStart:启动 Nginx 主程序,指定配置文件路径。
- ExecReload:执行平滑重载配置,不中断服务。
- ExecStop:向主进程发送 QUIT 信号,优雅停止。
- LimitNOFILE:设置文件描述符上限为 65535,应对高并发连接。
- Restart=on-failure:非正常退出时自动重启服务。
- RestartSec:重启前等待 5 秒,防止频繁重启。
[Install] WantedBy=multi-user.target- WantedBy:定义服务在多用户运行级别下启用,配合
systemctl enable实现开机自启。
3. 加载并启用服务
保存文件后,重新加载 systemd 配置:
systemctl daemon-reload设置开机自启:
systemctlenablenginx启动 Nginx:
systemctl start nginx查看运行状态:
systemctl status nginx4. 日常管理命令
- 启动:
systemctl start nginx - 停止:
systemctl stop nginx - 重启:
systemctl restart nginx - 重载配置(不中断服务):
systemctl reload nginx - 关闭开机自启:
systemctl disable nginx - 查看开机自启状态:
systemctl is-enabled nginx
5. 日志排查
若启动失败,查看实时日志:
journalctl-unginx-f