使用 systemd 部署服务


Author: yifei / Created: June 26, 2017, 9:07 p.m. / Modified: June 27, 2017, 2:40 a.m. / Edit

大多数的 Linux 系统已经选择了 systemd 来作为进程管理器。之前打算使用 supervisord 来部署服务,思考之后发现还不如直接使用 systemd 呢。这篇文章简单介绍下 systemd。

例子

我们从一个例子开始,比如说我们有如下的 go 程序:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8181", nil)
}

编译到 /opt/listen/listen 这里。

首先我们添加一个用户,用来运行我们的服务:

adduser -r -M -s /bin/false www-data

记下这条命令,如果需要添加用户来运行服务,可以使用这条。

Unit 文件

Unit 文件定义了一个 systemd 服务。/usr/lib/systemd/system/ 存放了系统安装的软件的 unit 文件,/etc/systemd/system/ 存放了系统自带的服务的 unit 文件。

我们编辑 /usr/lib/systemd/system/listen.service 文件:

[Unit]
Description=Listen

[Service]
User=www-data
Group=www-data
Restart=on-failure
ExecStart=/opt/listen/listen
WorkingDirectory=/opt/listen

Environment=VAR1=whatever "VAR2=something else"
EnvironmentFile=/path/to/file/with/variables

[Install]
WantedBy=multi-user.target

然后

sudo systemctl enable listen
sudo service listen status
sudo service listen start

其他一些常用的操作还包括:

basic usage

systemctl start/stop/reload/restart/reload-or-restart/enable/disable/cat/list-dependencies app[.service]

systemctl is-enabled/is-active/is-failed app

systemctl list-units/list-unit-files/daemon-reload

依赖管理

In that case add Requires=B and After=B to the [Unit] section of A. If the dependency is optional, add Wants=B and After=B instead. Note that Wants= and Requires= do not imply After=, meaning that if After= is not specified, the two units will be started in parallel.

类型

Type: simple/ forking

if you service depends on another service, use requires= + after= or wants= + after=

systemctl 的使用

systemctl start/stop/restart    
systemctl reload/reload-or-restart  
systemctl enable/disable    
systemctl status    
systemctl is-active 
systemctl is-enabled    
systemctl list-units [--all] [--state=…]    
systemctl list-unit-files   
systemctl cat [unit-name]   
systemctl edit [uni-name]   

评论区