Systemd

Linux 启动时会执行进程, 我们可以自定义.

Ubuntu15.04 之前用的是 Upstart, 之后用 Systemd

let’s talk about systemd

我们以开机启动 Gunicorn 为例来说明

service file location

Systemd 是创建$job.service文件
系统范围的服务单元文件:/lib/systemd/system/
用户范围的服务单元文件:/etc/systemd/system/

we can locate file to the /etc/systemd/system. but user need sudo permission to start the service.

if current user have not sudo permission, we can use systemctl --user, and the service file should be located in ~/.config/systemd/user/

service file content

[Unit]
Description=Rhinoauth service
After=network.target

[Service]
Type=simple
ExecStart=/home/apollo/rhinoauth/systemd/rhinoauth.sh start
ExecStop=/home/apollo/rhinoauth/systemd/rhinoauth.sh stop
RemainAfterExit=yes

[Install]
WantedBy=default.target

Grammar description:
Service.Type could be oneshot or simple, Their differences can be found here: https://stackoverflow.com/questions/39032100/what-is-the-difference-between-systemds-oneshot-and-simple-service-types, Let’s give an example:

...
[Service]
Type=simple
Restart=always
ExecStart=nohup gunicorn app:create_app &
ExecStop=pkill gunicorn
...

we can see the ExecStart, The nohup command allows the Gunicorn command to execute after the shell session is over. The postfix & symbols can allow the entire command to execute in background, so after the entire command is executed, it exits. so the service status turn to inactive.
but the type is simple, and restart is always, so this service will be restart looply. how to fix it? two ways:

  1. remove & symbol
  2. set RemainAfterExit=yes in the [Service] section

enable and start

# active servie file
systemctl daemon-reload
# config start when boot
systemctl enable $job
# start immediately
systemctl start $job

or use systemctl --user

log

systemctl status $job
# or
journalctl -u $job