最近在通过Linux系统学一些技术,但是在启动Nginx时,总是需要执行其安装路径下的脚本文件,要么我们需要先进入其安装路径,要么我们每次执行命令直接拼上Nginx的完整目录,如启动时命令为/usr/local/nginx/sbin/nginx。
可以看到这样在进行Nginx操作时稍比较繁琐,还需记住Nginx的安装路径,但是我了解到通过systemctl命令可以对系统服务进行管理,那是否可以将Nginx配置一下,使用systemctl命令启动呢?
答案是,当然可以!
在 Linux 系统中,一些服务可能已经集成了 systemd 单元(units),因此可以直接通过 systemctl 命令来管理,包括启动、停止、重启等操作。而另一些服务可能还未提供 systemd 单元,此时可能需要通过执行脚本来启动、停止服务。
对于 Nginx 这样的常见服务,通常都可以通过 systemctl 来管理。如果你的系统没有提供 Nginx 的 systemd 单元,你可以手动创建一个 systemd 单元文件来实现通过 systemctl 来管理 Nginx 服务。
以下是具体步骤:
1、sudo su提权,确保当前用户有权限编辑文件
2、进入配置文件目录,创建一个新的 systemd 单元文件,如/usr/lib/systemd/system/nginx.service
3、编辑nginx.service
[Unit]
Description=Nginx Web Server
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
KillMode=process
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
4、创建完成后,重新加载 systemd 配置:
systemctl daemon-reload
5、以上步骤完成后就可以使用systemctl命令对nginx服务进行相关操作了
- 启动 Nginx 服务:
systemctl start nginx
- 查看 Nginx 服务状态:
systemctl status nginx
- 停止 Nginx 服务:
systemctl stop nginx
- 重启服务:
systemctl restart nginx