Start service on system boot with systemd
systemd
systemd
counld be used for running program on system boot/reboot.
常用的格式和字段:
Unit
- Description
- Before
- After
Service
- EnvironmentFile
- ExecStart
- ExecStop
- ExecReload
- ExecStartPre
- ExecStartPos
- ExecStopPost
- Type
- Restart
Install
- WantsBy
Examples
Create redis.service
Here we will write a redis.service
to start redis-server on system boot:
1 | [Unit] |
Then:
1, Copy this file to path /lib/systemd/system/
2, Start service with systemctl start redis
. Make sure your redis config file set the daemonize
to no
, if you set to yes
, in the later run systemctl start
step, it will fail. Now your redis-server should be running, you could check its running status with systemctl status redis
.
3, To stop it, run systemctl stop redis
If you changed the service file content, you need to reload it:
1 | systemctl daemon-reload |
To make it run on system boot, you need:
1 | systemctl enable redis |
This will create a symbol link to your file under /etc/systemd/system/multi-user.target.wants/
folder, and after your system reboot, it will auto start this redis service.
Other examples
In this /etc/systemd/system/multi-user.target.wants
folder, there are some other service files we can learn as example:
ufw.service
1 | [Unit] |
cron.service
1 | [Unit] |
supervisor.service
1 | [Unit] |
Compare to supervisor
supervisor
is a good tool to run program too. So I think if the service is the basic infra applications, like redis, mysql, mongodb, you could set it under systemd
, b/c supervisor doesn’t have a good “dependency” running order supported. Then in the application layer, you could just use supervisor
which have more flexible settings for applications.