把 Sanic 部署到 Docker 中并用 Supervisor 来守护

最近开发 Python 一直在用 Sanic,感觉还不错;看看如何将 Sanic 部署到 Docker 中并用 Supervisor 来守护

Dockerfile

这里利用 Python 3.9 来构建基础镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
FROM python:3.9-alpine

RUN sed -i 's/dl-cdn.alpinelinux.org/repo.huaweicloud.com/g' /etc/apk/repositories

RUN apk update \
&& apk add --no-cache build-base \
&& apk add --no-cache libffi-dev

RUN mkdir /usr/src/app

COPY . /usr/src/app/

COPY ./supervisor/supervisord.conf /etc/supervisord.conf

WORKDIR /usr/src/app
ENV PYTHONPATH /usr/src/app

RUN pip3 install supervisor \
&& pip3 install -r requirements.txt --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple

CMD ["supervisord", "-c", "/etc/supervisord.conf"]

这里利用华为的 alpine 源和 pypi

Supervisor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[unix_http_server]
file=/var/run/supervisor.sock

[supervisord]
logfile=/var/log/supervisord.log
logfile_maxbytes=50MB
logfile_backups=10
loglevel=info
pidfile=/var/run/supervisord.pid
nodaemon=true
silent=false
minfds=1024
minprocs=200

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor.sock

[program:sanic]
user = root
directory=/usr/src/app
command=sanic server.app --host=0.0.0.0 --port=8888 --workers=4
stdout_logfile_backups=20
stdout_logfile_maxbytes=50MB
stdout_logfile = /var/log/sanic.log
stderr_logfile = /var/log/sanic.err
autostart=true

Supervisor 配置参考


题外话:

容器运行 Supervisor 记得设置 nodaemon=true,或则会出现 Unlinking stale socket /var/run/supervisor.sock

因为 Supervisor 默认是 deamon 模式,启动命令结束后 Supervisor 会在后台运行,而容器运行启动命令返回 0 后自己关闭了,导致一直出现无法运行的现象