使用Supervisor管理进程

Docker 容器在启动的时候开启单个进程,比如,一个 ssh 或者 apache 的 daemon 服务。但我们经常需要在一个机器上开启多个服务,这可以有很多方法,最简单的就是把多个启动命令放到一个启动脚本里面,启动的时候直接启动这个脚本,另外就是安装进程管理工具。

使用进程管理工具 supervisor 来管理容器中的多个进程。使用 Supervisor 可以更好的控制、管理、重启我们希望运行的进程。

什么是 supervisor

Supervisor (http://supervisord.org) 是一个用 Python 写的进程管理工具,可以很方便的用来启动、重启、关闭进程(不仅仅是 Python 进程)。除了对单个进程的控制,还可以同时启动、关闭多个进程,比如很不幸的服务器出问题导致所有应用程序都被杀死,此时可以用 supervisor 同时启动所有应用程序而不是一个一个地敲命令启动。

安装

yum -y install epel-release
yum -y update
yum -y install supervisor

pip install supervisor

配置文件

Supervisor 相当强大,提供了很丰富的功能,不过我们可能只需要用到其中一小部分。安装完成之后,可以编写配置文件,来满足自己的需求。为了方便,我们把配置分成两部分:supervisord(supervisor 是一个 C/S 模型的程序,这是 server 端,对应的有 client 端:supervisorctl)和应用程序(即我们要管理的程序)。
首先来看 supervisord 的配置文件。安装完 supervisor 之后,可以运行echo_supervisord_conf 命令输出默认的配置项,也可以重定向到一个配置文件里:

echo_supervisord_conf > /etc/supervisord.conf 

去除里面大部分注释和“不相关”的部分,我们可以先看这些配置:
[unix_http_server]
file=/tmp/supervisor.sock ; UNIX socket 文件,supervisorctl 会使用
;chmod=0700 ; socket 文件的 mode,默认是 0700
;chown=nobody:nogroup ; socket 文件的 owner,格式: uid:gid

;[inet_http_server]         ; HTTP 服务器,提供 web 管理界面
;port=127.0.0.1:9001        ; Web 管理后台运行的 IP 和端口,如果开放到公网,需要注意安全性
;username=user              ; 登录管理后台的用户名
;password=123               ; 登录管理后台的密码

[supervisord]
logfile=/tmp/supervisord.log ; 日志文件,默认是 $CWD/supervisord.log
logfile_maxbytes=50MB        ; 日志文件大小,超出会 rotate,默认 50MB
logfile_backups=10           ; 日志文件保留备份数量默认 10
loglevel=info                ; 日志级别,默认 info,其它: debug,warn,trace
pidfile=/tmp/supervisord.pid ; pid 文件
nodaemon=false               ; 是否在前台启动,默认是 false,即以 daemon 的方式启动
minfds=1024                  ; 可以打开的文件描述符的最小值,默认 1024
minprocs=200                 ; 可以打开的进程数的最小值,默认 200

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; 通过 UNIX socket 连接 supervisord,路径与 unix_http_server 部分的 file 一致
;serverurl=http://127.0.0.1:9001 ; 通过 HTTP 的方式连接 supervisord

; 包含其他的配置文件
[include]
files = relative/directory/*.ini    ; 可以是 *.conf 或 *.ini

我们把上面这部分配置保存到 /etc/supervisord.conf(或其他任意有权限访问的文件),然后启动 supervisord(通过 -c 选项指定配置文件路径,如果不指定会按照这个顺序查找配置文件:

$CWD/supervisord.conf, $CWD/etc/supervisord.conf, /etc/supervisord.conf):
supervisord -c /etc/supervisord.conf

查看 supervisord 是否在运行:

ps aux | grep supervisord  

program 配置

上面我们已经把 supervisrod 运行起来了,现在可以添加我们要管理的进程的配置文件。可以把所有配置项都写到 supervisord.conf 文件里,但并不推荐这样做,而是通过 include 的方式把不同的程序(组)写到不同的配置文件里。
为了举例,我们新建一个目录 /etc/supervisor/ 用于存放这些配置文件,相应的,把 /etc/supervisord.conf 里 include 部分的的配置修改一下:

[include]
files = /etc/supervisor/*.conf

假设有个用 Python 和 Flask 框架编写的用户中心系统,取名 usercenter,用 gunicorn (http://gunicorn.org/) 做 web 服务器。项目代码位于 /home/leon/projects/usercenter,gunicorn 配置文件为 gunicorn.py,WSGI callable 是 wsgi.py 里的 app 属性。所以直接在命令行启动的方式可能是这样的:

cd /home/leon/projects/usercenter
gunicorn -c gunicorn.py wsgi:app

现在编写一份配置文件来管理这个进程(需要注意:用 supervisord 管理时,gunicorn 的 daemon 选项需要设置为 False):

[program:usercenter]
directory = /home/leon/projects/usercenter ; 程序的启动目录
command = gunicorn -c gunicorn.py wsgi:app  ; 启动命令,可以看出与手动在命令行启动的命令是一样的
autostart = true     ; 在 supervisord 启动的时候也自动启动
startsecs = 5        ; 启动 5 秒后没有异常退出,就当作已经正常启动了
autorestart = true   ; 程序异常退出后自动重启
startretries = 3     ; 启动失败自动重试次数,默认是 3
user = leon          ; 用哪个用户启动
redirect_stderr = true  ; 把 stderr 重定向到 stdout,默认 false
stdout_logfile_maxbytes = 20MB  ; stdout 日志文件大小,默认 50MB
stdout_logfile_backups = 20     ; stdout 日志文件备份数

; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile = /data/logs/usercenter_stdout.log

; 可以通过 environment 来添加需要的环境变量,一种常见的用法是修改 PYTHONPATH
; environment=PYTHONPATH=$PYTHONPATH:/path/to/somewhere

一份配置文件至少需要一个 [program:x] 部分的配置,来告诉 supervisord 需要管理那个进程。[program:x] 语法中的 x 表示 program name,会在客户端(supervisorctl 或 web 界面)显示,在 supervisorctl 中通过这个值来对程序进行 start、restart、stop 等操作。
使用 supervisorctl
Supervisorctl 是 supervisord 的一个命令行客户端工具,启动时需要指定与 supervisord 使用同一份配置文件,否则与 supervisord 一样按照顺序查找配置文件。

supervisorctl -c /etc/supervisord.conf

上面这个命令会进入 supervisorctl 的 shell 界面,然后可以执行不同的命令了:

> status    # 查看程序状态
> stop usercenter   # 关闭 usercenter 程序
> start usercenter  # 启动 usercenter 程序
> restart usercenter    # 重启 usercenter 程序
> reread    # 读取有更新(增加)的配置文件,不会启动新添加的程序
> update    # 重启配置文件修改过的程序

上面这些命令都有相应的输出,除了进入 supervisorctl 的 shell 界面,也可以直接在 bash 终端运行:
$ supervisorctl status
$ supervisorctl stop usercenter
$ supervisorctl start usercenter
$ supervisorctl restart usercenter
$ supervisorctl reread
$ supervisorctl update

Dockerfile 配置

FROM centos
LABEL maintainer "awen Email: <[email protected]>"
WORKDIR /opt/

COPY CentOS7-Base-163.repo /etc/yum.repos.d/CentOS-Base.repo

ENV NGINX_V=1.13.5 \
    OPENSSL_V=1.0.2l \
    PCRE_V=8.41 \
    ZLIB_V=1.2.11 

RUN yum -y install openssh-server openssl gcc gcc-c++ pcre-devel openssl-devel zlib-devel wget  epel-release python-setuptools rsync make perl tar net-tools  \
    && yum -y update  \
    &&  yum -y install supervisor \
    &&  wget -c -4 https://nginx.org/download/nginx-$NGINX_V.tar.gz \
    &&  wget -c -4 https://www.openssl.org/source/openssl-$OPENSSL_V.tar.gz \
    &&  wget -c -4 ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-$PCRE_V.tar.gz \
    &&  wget -c -4 http://zlib.net/zlib-$ZLIB_V.tar.gz \
    &&  groupadd -r www && useradd -r -g www www \
    &&  tar zxvf zlib-$ZLIB_V.tar.gz \
    &&  cd zlib-$ZLIB_V \
    &&  ./configure \
    &&  make \
    &&  make install \
    &&  cd /opt \
    &&  tar  zxvf pcre-$PCRE_V.tar.gz \
    &&  cd pcre-$PCRE_V \
    &&  ./configure \
    &&  make \
    &&  make install \
    &&  cd /opt \
    &&  tar zxvf openssl-$OPENSSL_V.tar.gz \
    &&  tar zxvf nginx-$NGINX_V.tar.gz \
    &&  cd nginx-$NGINX_V \
    &&  ./configure --prefix=/usr/local/nginx --user=www --group=www --with-pcre=/opt/pcre-$PCRE_V --with-http_ssl_module --with-zlib=/opt/zlib-$ZLIB_V --with-openssl=/opt/openssl-$OPENSSL_V --with-http_v2_module --with-http_ssl_module \
    &&  make \
    &&  make install \
    &&  rm -rf /opt/* \
    &&  yum clean all \
    && rm -rf /root/*.cfg

RUN mkdir -p /usr/local/nginx/conf/vhost /var/log/wwwlogs/ /www/ /var/run/sshd  /etc/supervisor/conf.d/ /usr/local/nginx/ssl \
    &&  ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N '' \
    &&  chown -R www:www /var/log/wwwlogs/ \
    &&  ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N '' \
    &&  ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N '' \
    &&  ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N '' \
    &&  sed -i "s/PasswordAuthentication yes/PasswordAuthentication no/g" /etc/ssh/sshd_config \
    &&  sed -i "s/#Port 22/Port 65422/g" /etc/ssh/sshd_config \
    &&  echo "Asia/Shanghai" > /etc/localtime  


COPY ssl/* /usr/local/nginx/ssl/ 
COPY vhost/* /usr/local/nginx/conf/vhost/
COPY nginx.conf /usr/local/nginx/conf/
COPY ssh/* /root/.ssh/
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf


VOLUME ["/www","/var/log/wwwlogs","/usr/local/nginx/ssl","/usr/local/nginx/conf/vhost"]

EXPOSE 65422 80 443

HEALTHCHECK CMD curl -fs http://localhost/ || exit 1
CMD ["/usr/bin/supervisord","-c","/etc/supervisor/conf.d/supervisord.conf"]

配置文件

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

[program:nginx]
command=/usr/local/nginx/sbin/nginx
stopsignal=QUIT 

运行后查看进程

# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS                                                                NAMES
264aecfceac8        500                 "/usr/bin/supervisord"   3 seconds ago       Up 2 seconds (health: starting)   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:65423->65422/tcp   blog

查看 log 信息

# docker logs 264
2017-10-12 05:20:29,984 CRIT Supervisor running as root (no user in config file)
2017-10-12 05:20:29,987 INFO supervisord started with pid 1
2017-10-12 05:20:30,989 INFO spawned: 'nginx' with pid 7
2017-10-12 05:20:30,996 INFO spawned: 'sshd' with pid 8
2017-10-12 05:20:32,009 INFO success: nginx entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
2017-10-12 05:20:32,010 INFO success: sshd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)