linux注册自启动服务
方法一:使用Service管理开启自启动
在/etc/init.d/
中增加配置文件,使用chkconfig
命令就可以注册到Service
服务自启动
创建配置注册并管理Service管理
服务
-
在
/etc/init.d/
创建配置文件test
touch /etc/init.d/test
-
配置内容如下
# 数字意义: 2345表示系统运行级别是2,3,4或者5时都启动此服务,80:启动优先级,90停止优先级,数字越大越后执行 # chkconfig 2345 80 90 # description: 启动redis服务 # 这里后面都写要执行脚本命令 touch /home/test/test.txt
-
给配置脚本增加权限
chmod a+x /etc/init.d/test
-
添加到
chkconfig
服务chkconfig --add test
-
然后可以使用
service
命令管理服务
service test start
# 还有其他命令 stop restart status
chkconfig
命令详解
chkconfig --list
#列出所有的系统服务chkconfig --add redisTest
#增加redisTest服务chkconfig --del redisTest
#删除redisTest服务chkconfig --level redisTest2345 on/off
#设置redisTest在运行级别为2、3、4、5的情况下都是on(开启)/off(关闭)的状态chkconfig --list redisTest
#列出redisTest服务设置情况
方法二:使用systemctl管理开启自启动
Linux系统最新的初始化系统是systemd
,可以提高系统的启动速度,尽可能启动较少的进程,尽可能多进程并发启动,对应的进程管理命令是systemctl
,
注册systemctl
管理的服务
在这里,我们用docker
注册自启动服务的配置文件作为案例进行介绍
-
/usr/lib/systemd/system
目录下新增docker.service
文件,并建立软连接touch /usr/lib/systemd/system/docker.service ln -s '/usr/lib/systemd/system/docker.service' '/etc/systemd/system/docker.service'
-
docker.service
文件内容如下[Unit] Description=Docker Application Container Engine #当前配置文件的描述信息 Documentation=https://docs.docker.com After=network-online.target firewalld.service #表示当前服务是在那个服务后面启动,一般定义为网络服务启动后启动 Wants=network-online.target [Service] Type=notify #定义启动类型 ExecStart=/usr/bin/dockerd #定义启动进程时执行的命令。 ExecReload=/bin/kill -s HUP $MAINPID #重启服务时执行的命令 LimitNOFILE=infinity LimitNPROC=infinity TimeoutStartSec=0 Delegate=yes KillMode=process Restart=on-failure StartLimitBurst=3 StartLimitInterval=60s [Install] WantedBy=multi-user.target #表示多用户命令行状态
-
给
docker.service
添加权限chmod a+x /etc/systemd/system/docker.service
-
重新加载配置文件
systemctl daemon-reload
-
启动/重启/查看状态
systemctl start/stop/restart/status docker
-
设置开机启动
systemctl enable docker.service
原理:会在
/etc/systemd/system/multi-user.target.wants/
这个linux系统自启动目录下新建一个/usr/lib/systemd/system/docker.service
文件的链接
systemctl
命令详解的链接地址
linux的.service文件配置详解
方法三:使用/etc/rc.d/rc.local
开启自启动
linux系统在开启后,会执行/etc/rc.d/rc.local
里的脚本,只需要创建脚本,然后再/etc/rc.d/rc.local
中调用就可以了,但是推荐使用上面两种
-
创建脚本
touch /home/test/test.sh
-
赋予权限
chmod a+x /home/test/test.sh
-
命令追加到
/etc/rc.d/rc.local
# 这里必须是绝对路径 /home/test/test.sh