当前位置:首页>Linux>Linux 上设置 Nginx 开机自启

Linux 上设置 Nginx 开机自启

  • 2026-10-11 06:56:13
Linux 上设置 Nginx 开机自启

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
    :启动 Nginx 主程序,指定配置文件路径。
  • ExecReload
    :执行平滑重载配置,不中断服务。
  • ExecStop
    :向主进程发送 QUIT 信号,优雅停止。
  • User/Group
    :以 nginx 用户和组运行,提升安全性。
  • LimitNOFILE
    :设置文件描述符上限为 65535,应对高并发连接。
  • Restart=on-failure
    :非正常退出时自动重启服务。
  • RestartSec
    :重启前等待 5 秒,防止频繁重启。
[Install]WantedBy=multi-user.target
  • WantedBy
    :定义服务在多用户运行级别下启用,配合 systemctl enable 实现开机自启。

3. 加载并启用服务

保存文件后,重新加载 systemd 配置:

systemctl daemon-reload

设置开机自启:

systemctl enable nginx

启动 Nginx:

systemctl start nginx

查看运行状态:

systemctl status nginx

4. 日常管理命令

  • 启动:systemctl start nginx
  • 停止:systemctl stop nginx
  • 重启:systemctl restart nginx
  • 重载配置(不中断服务):systemctl reload nginx
  • 关闭开机自启:systemctl disable nginx
  • 查看开机自启状态:systemctl is-enabled nginx

5. 日志排查

若启动失败,查看实时日志:

journalctl -u nginx -f

最新文章

随机文章