Appearance
Linux 十八般武艺 - 如何在 Linux 平台上添加一个用户服务启动脚本
- 编写启动脚本并将其放置在
/etc/init.d
目录下。
假如脚本名为 my-blog-site
shell
#!/bin/bash
# description: Start my service after reboot
# Your script commands go here
case "$1" in
start)
# Commands to start your service
;;
stop)
# Commands to stop your service
;;
restart)
# Commands to re-start your service
start
;;
status)
# code to check status of app comes here
# example: status program_name
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac
exit 0
- 确保启动脚本具有可执行权限,并且属于 root 用户。
shell
sudo chmod +x /etc/init.d/my-blog-site
sudo chown root:root /etc/init.d/my-blog-site
- 使用
update-rc.d
命令添加启动脚本并设置启动顺序和运行级别。
shell
# 将启用您的脚本在运行级别 **99** 启动,并在运行级别 **99** 停止。
sudo update-rc.d my-blog-site defaults 99
- 重启机器后可以使用
service
命令查看是否生效#
shell
# [ + ] – Services with this sign are currently running.
# [ – ] – Services with this sign are not currently running..
# [ ? ] – Services that do not have a status switch.
sudo service --status-all
备注说明:
Debian and Ubuntu use the service command to control services and update-rc.d for adding and removing services from start up. Using the service command we can start, stop, restart and display all available services. With update-rc.d we can add and remove services and add them to the Ubuntu/ Debian start up scripts. As Linux operating systems have multiple states, or runlevels, you need to make sure you add any new services to the correct runlevels.
Start a service
shell
sudo service my-blog-site start
Stop a service
shell
sudo service my-blog-site stop
Check the status of a service
shell
sudo service my-blog-site status
Remove a service
shell
sudo update-rc.d -f my-blog-site remove
Add a service
Adding a service to Ubuntu or Debian is done with the update-rc.d command. You can specify which runlevels to start and stop the new service or accept the defaults. The init.d file will be added to the relevent rc.d startup folders.
shell
cd /etc/init.d
sudo update-rc.d my-blog-site defaults 99
my-blog-site will be started (as long as it isn’t already) when the system enters RunLevel 2, 3, 4 or 5 with a priority of 99. It will then be asked to stop when the system enters RunLevel 0, 1 or 6 with a priority of 99.
When starting, the lower the number, the earlier it will start. A start priority of 10 will start before a priority of 20. When killing, it’s the opposite. A higher number will be killed before a lower number.