1. 问题背景与现象分析
最近在帮客户部署新服务器时遇到了一个典型问题:通过源码编译安装Nginx后,执行systemctl start nginx命令时系统提示"Unit nginx.service not found"。这种情况在从源码构建服务的场景中相当常见,尤其当运维人员习惯了用包管理器(如yum/apt)安装软件后初次尝试编译安装时。
这个报错的本质是systemd系统未能识别Nginx作为一个服务单元存在。与直接使用apt install nginx不同,源码安装不会自动:
- 生成.service服务文件
- 设置服务自启动
- 注册到systemd服务管理器
2. 解决方案全流程
2.1 创建systemd服务文件
在/etc/systemd/system/目录下新建nginx.service文件:
bash复制sudo vim /etc/systemd/system/nginx.service
文件内容模板(需根据实际路径调整):
ini复制[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
关键参数说明:
PIDFile:必须与nginx.conf中pid路径一致ExecStartPre:启动前测试配置文件语法Type=forking:声明服务以daemon方式运行
