前言
关于Linux开机自启服务这篇文章一直想写来着,因为确实是非常使用,但由于懒,所以现在才写下来。废话不多说,Linux自启服务有好几种方法可以完成,主要有以下几种:
- 添加开机自启服务
- 添加开机自启脚本
- 自定义服务文件
添加开机自启服务
以Centos7为例,添加开机自启服务非常方便,可直接通过以下命令来进行:
1 | systemctl enable XXX.service #设置XXX服务为自启动服务,XXX为服务名称,可以是系统自带,也可以是自定义服务 |
添加开机自启脚本
添加开机自启脚本有两种方法:一种是通过/etc/rc.d/rc.local写入命令,一种是通过/etc/rc.d/init.d目录来执行
/etc/rc.d/rc.local该文件可以以写入命令或者执行命令脚本的方式来实现开机自启动
1
2
3
4
5# 值得注意的是,在centos7系统中,该文件的权限被降低了,需要手动添加可执行权限
chmod +x /etc/rc.d/rc.local
# 写入命令,在文件末尾添加可执行的命令
vim /etc/rc.d/rc.local/etc/rc.d/init.d将脚本移动至
/etc/rc.d/init.d目录下1
2
3
4
5
6
7
8
9
10# 将脚本移动至`/etc/rc.d/init.d`目录下
mv XXX.sh /etc/rc.d/init.d/
# 增加可执行权限
chmod +x /etc/rc.d/init.d/XXX.sh
# 添加脚本到开机自启服务中
cd /etc/rc.d/init.d
chkconfig --add XXX.sh
chkconfig XXX.sh on
自定义服务文件
自定义服务文件,添加到系统服务,通过systemctl管理,这个可以说是最有效的一种方式(个人最喜欢的)。
1.写服务文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14[Unit] ##服务的说明
Description:描述服务
After:描述服务类别
[Service] ##服务运行参数的设置
Type=forking是后台运行的形式
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:启动、重启、停止命令全部要求使用绝对路径
[Install] ##服务安装的相关设置,可设置为多用户以下为
nginx.service的示例1
2
3
4
5
6
7
8
9
10
11
12[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
[Install]
WantedBy=multi-user.target下面是我自己写的一个frp服务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16[Unit]
Description=SakuraFrp Service
After=network.target
[Service]
Type=idle
User=root
LimitNOFILE=4096
PIDFile=/var/run/sakurafrp/client.pid
ExecStart=/usr/local/bin/frpc -c /etc/frp/byp.ini
Restart=on-failure
RestartSec=60s
StartLimitInterval=600
[Install]
WantedBy=multi-user.target
2.保存目录
通常情况下,我们会将服务文件以754的权限保存在
/usr/lib/systemd/system1
mv nginx.service /usr/lib/systemd/system/
3.设置开机自启动
1
systemctl enable nginx.service
4.服务其他命令
1
2
3
4
5
6
7
8
9
10启动nginx服务
systemctl start nginx.service
设置开机自启动
systemctl enable nginx.service
停止开机自启动
systemctl disable nginx.service
查看服务当前状态
systemctl status nginx.service
重新启动服务
systemctl restart nginx.service
查看所有开机启动的服务
1 | systemctl list-units --type=service |



