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