Linux 设置开机启动项的几种方法
Linux 设置开机启动项的几种方法
方法一:编辑rc.loacl脚本
Ubuntu开机之后会执行/etc/rc.local文件中的脚本。
所以我们可以直接在/etc/rc.local中添加启动脚本。
vim /etc/rc.local#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
/etc/init.d/mysqld start #mysql开机启动
/etc/init.d/nginx start #nginx开机启动
/etc/init.d/php-fpm start #php-fpm开机启动
/etc/init.d/memcached start #memcache开机启动
#在文件末尾(exit 0之前)加上你开机需要启动的程序或执行的命令即可(执行的程序需要写绝对路径,添加到系统环境变量的除外),如:
/usr/local/thttpd/sbin/thttpd -C /usr/local/thttpd/etc/thttpd.conf
方法二:添加一个开机启动服务。
将你的启动脚本复制到 /etc/init.d目录下,并设置脚本权限, 假设脚本为test
mv test /etc/init.d/test
sudo chmod 755 /etc/init.d/test
将该脚本放倒启动列表中去
cd .etc/init.d
sudo update-rc.d test defaults 95
注:其中数字95是脚本启动的顺序号,按照自己的需要相应修改即可。在你有多个启动脚本,而它们之间又有先后启动的依赖关系时你就知道这个数字的具体作用了。
将该脚本从启动列表中剔除
cd /etc/init.d
sudo update-rc.d -f test remove
方法三:自己写一个shell脚本
将写好的脚本(.sh文件)放到目录 /etc/profile.d/ 下,系统启动后就会自动执行该目录下的所有shell脚本。
方法四:通过chkconfig命令设置
将启动文件cp到 /etc/init.d/或者/etc/rc.d/init.d/(前者是后者的软连接)下
vim 启动文件,文件前面务必添加如下三行代码,否侧会提示chkconfig不支持
#!/bin/sh 告诉系统使用的shell,所以的shell脚本都是这样
#chkconfig: 35 20 80 分别代表运行级别,启动优先权,关闭优先权,此行代码必须
#description: http server(自己随便发挥)//两行都注释掉!!!,此行代码必须
chkconfig --add 脚本文件名 操作后就已经添加了
五、注册服务实例配置文件目录
systemctl脚本目录:/usr/lib/systemd/
系统服务目录:/usr/lib/systemd/system/
用户服务目录:/usr/lib/systemd/user/
在/usr/lib/systemd/system目录下新建service-name.service文件:
[UNIT]
#服务描述
Description=Media wanager Service
#指定了在systemd在执行完那些target之后再启动该服务
After=network.target
[Service]
#定义Service的运行类型,一般是forking(后台运行)
Type=forking
#定义systemctl start|stop|reload *.service 的执行方法(具体命令需要写绝对路径)
#注:ExecStartPre为启动前执行的命令
ExecStartPre=/usr/bin/test "x${NETWORKMANAGER}" = xyes
ExecStart=/home/mobileoa/apps/shMediaManager.sh -start
ExecReload=
ExecStop=/home/mobileoa/apps/shMediaManager.sh -stop
#创建私有的内存临时空间
PrivateTmp=True
[Install]
#多用户
WantedBy=multi-user.target
重载系统服务:systemctl daemon-reload
设置开机启动:systemctl enable *.service
启动服务:systemctl start *.service
停止服务:systemctl stop *.service
重启服务:systemctl reload *.service