有时候我们需要Linux在开机的时候自动加载某些脚本或系统服务,一般情况下,服务器是不会重新启动的,但是在某些特定的情境下,我们需要重新启动服务器,例如断电、宕机或者做一些系统配置又或安装一些硬件驱动。

总之非常多的情况,但重启会遇到一个问题,即使我们在服务器上部署的一些软件也会随之挂掉,还要手动启动,这样非常浪费时间并且有可能遗漏一些应该开启的软件和服务。

此时,我们需要把部署在服务器上的服务程序自定义为系统服务,并设置开机自启。

将软件设置为系统服务

我们只需要在该目录下创建脚本文件,就可以使用systemctl命令管理。

系统服务管理的命令为systemctl,其脚本存放在/etc/systemd/system目录下。

文件名格式为“serviceName.service”,文件内容如下:

[Unit]            服务的说明
Description       描述服务
Documentation     服务文档
After             描述服务类别

[Service]             服务运行参数的设置
Type=forking          是后台运行的形式
PIDFile               存放PID文件的位置
ExecStartPre          设置在执行 ExecStart= 之前/后执行的命令行
ExecStart             为服务的具体运行命令启动该服务的命令
ExecStop              为停止命令
ExecReload            为重启命令
PrivateTmp=True       表示给服务分配独立的临时空间

[Install]
WantedBy=multi-user.target 服务安装的相关设置,可设置为多用户,这玩意默认就这样写就行

注意:启动、重启、停止命令全部要求-使用绝对路径因为需要找到该服务对应的启动重启停止脚本

以nginx为例演示

使用vim /etc/systemd/system/nginx.service创建并编辑服务文件,内容如下:

[Unit]
Description=nginx web service
Documentation=http://nginx.org/en/docs/
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=default.target

添加nginx.service服务后需要重新加载 systemd

如果权限有问题需要进行权限设置,操作如下:

chmod 755 /etc/systemd/system/nginx.service

重新加载 systemd

systemctl daemon-reload

启动nginx服务

systemctl start nginx.service

设置为开机自启动

systemctl enable nginx.service

取消开机启动

systemctl disable nginx.service

查看服务状态

systemctl status nginx.service

重新启动服务

systemctl restart nginx.service

重新加载nginx配置文件

systemctl reload nginx

查看正在运行的服务

systemctl list-units --type=service