Failed to start nginx.service: Unit nginx.service not found.

分享一篇nginx安装后,出现:Failed to start nginx.service: Unit nginx.service not found. 我们需要如何解决这个问题

在使用 Nginx 1.26.3 时遇到了 nginx.service找不到的问题。这是因为通过源码编译安装 Nginx 后,systemd 没有对应的服务单元文件。别担心,我们可以手动创建一个

1.创建服务文件

使用vi编辑器在 systemd 的系统目录中创建服务文件。通常建议放在 /etc/systemd/system/目录下

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

2.编写服务配置

将以下内容复制到文件中。​请务必将路径 /usr/local/nginx/全部替换为您实际的 Nginx 安装路径 /usr/local/nginx-1.26.3/

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx-1.26.3/logs/nginx.pid
ExecStartPre=/usr/local/nginx-1.26.3/sbin/nginx -t
ExecStart=/usr/local/nginx-1.26.3/sbin/nginx
ExecReload=/usr/local/nginx-1.26.3/sbin/nginx -s reload
ExecStop=/usr/local/nginx-1.26.3/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target

关键提示​:请仔细核对并确保 PIDFileExecStartPreExecStartExecReloadExecStop的路径都正确指向您的 Nginx 安装路径 /usr/local/nginx-1.26.3

ExecStartPre参数用于在启动前测试配置文件语法,能帮助提前发现配置错误

3.重新加载systemd配置

创建文件后,必须让 systemd 重新加载配置,以识别这个新服务

sudo systemctl daemon-reload

4.启动并验证Nginx服务

sudo systemctl start nginx

检查服务状态

sudo systemctl status nginx

Snipaste_2025-10-23_14-23-22

5.设置开机自启动

sudo systemctl enable nginx

Snipaste_2025-10-23_17-00-43

检查确认开机自启是否已成功启用

sudo systemctl is-enabled nginx

Snipaste_2025-10-23_14-25-03

posted @ 2025-10-23 14:26  子墨老师  阅读(24)  评论(0)    收藏  举报