ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Linux 上设置 Nginx 开机自启

2026/8/27 12:41:29 拓冰建站 浏览量
Linux 上设置 Nginx 开机自启 Linux 上设置 Nginx 开机自启本教程将介绍如何通过 systemd 在 Linux 系统上配置 Nginx 开机自启涵盖服务文件创建、配置项解析、服务管理与日志排查。1. 创建服务文件使用 vim 编辑 systemd 服务文件路径为/etc/systemd/system/nginx.servicevim/etc/systemd/system/nginx.service2. 配置文件详解[Unit] DescriptionNginx Web Server Afternetwork.targetDescription服务描述systemctl status时显示。After指定在网络服务就绪后再启动 Nginx避免启动时网络不可用。[Service] Typeforking 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 LimitNOFILE65535 Restarton-failure RestartSec5Typeforking表示 Nginx 启动后会派生子进程主进程退出systemd 通过 PIDFile 跟踪实际进程。PIDFile指定 PID 文件路径systemd 据此管理服务。ExecStartPre启动前执行配置测试确保配置文件语法正确失败则不会启动。ExecStart启动 Nginx 主程序指定配置文件路径。ExecReload执行平滑重载配置不中断服务。ExecStop向主进程发送 QUIT 信号优雅停止。LimitNOFILE设置文件描述符上限为 65535应对高并发连接。Restarton-failure非正常退出时自动重启服务。RestartSec重启前等待 5 秒防止频繁重启。[Install] WantedBymulti-user.targetWantedBy定义服务在多用户运行级别下启用配合systemctl enable实现开机自启。3. 加载并启用服务保存文件后重新加载 systemd 配置systemctl daemon-reload设置开机自启systemctlenablenginx启动 Nginxsystemctl start nginx查看运行状态systemctl status nginx4. 日常管理命令启动systemctl start nginx停止systemctl stop nginx重启systemctl restart nginx重载配置不中断服务systemctl reload nginx关闭开机自启systemctl disable nginx查看开机自启状态systemctl is-enabled nginx5. 日志排查若启动失败查看实时日志journalctl-unginx-f​