详解Docker容器运行多条命令(supervisor)

一, 简介

Dockerfile 运行只支持一条命令,当在Docker里要运行多条命令,用supervisor来管理就比较合适了。

Supervisor是一个 Python 开发的 client/server 系统,可以管理和监控类 UNIX 操作系统上面的进程。它可以同时启动,关闭多个进程,使用起来特别的方便。

组成部分

supervisor 主要由两部分组成:

supervisord(server 部分):主要负责管理子进程,响应客户端命令以及日志的输出等;

supervisorctl(client 部分):命令行客户端,用户可以通过它与不同的 supervisord 进程联系,获取子进程的状态等。

二,存在的问题——日志不输出

但是使用supervisor,Django运行的日志就不会在Docker里输出了,默认的输出如下:

2018-03-28 06:48:20,292 CRIT Supervisor running as root (no user in config file)

2018-03-28 06:48:20,308 INFO supervisord started with pid 1

2018-03-28 06:48:21,310 INFO spawned: 'celery_beat' with pid 7

2018-03-28 06:48:21,312 INFO spawned: 'celery_worker' with pid 8

2018-03-28 06:48:21,313 INFO spawned: 'django' with pid 9

2018-03-28 06:48:22,315 INFO success: celery_beat entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

2018-03-28 06:48:22,315 INFO success: celery_worker entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

2018-03-28 06:48:22,315 INFO success: django entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

上面的Docker中supervisor配置如下:

[supervisord]

nodaemon=true

[program:django]

command=python manage.py runserver 0.0.0.0:8080

[program:celery_worker]

command=python manage.py celery worker -c 4 -l info

[program:celery_beat]

command=python manage.py celery beat

这样的配置在容器中是同时运行Django,celery。

三,解决方案

1,改进后的配置方案

[inet_http_server]

port=9001

username=abc

password=123456

[supervisord]

nodaemon=true

logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)

pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)

childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP)

[program:django]

command=python manage.py runserver 0.0.0.0:8080

#stdout_logfile = /var/log/supervisord/django_stdout.log

loglevel=info

redirect_stderr=true

[program:celery_worker]

command=python manage.py celery worker -c 4 -l info

loglevel=info

redirect_stderr=true

[program:celery_beat]

command=python manage.py celery beat

loglevel=info

redirect_stderr=true

实测发现Django的日志输出会写到stderr.log文件中,所以在配置文件中将错误日志重定向到标准日志里;

redirect_stderr=true

容器中的生成的日志文件如下:

root@a16bc77e96bc:/var/log/supervisor# ls

celery_beat-stderr---supervisor-rSPQ7E.log django-stderr---supervisor-9LS_KA.log

celery_beat-stdout---supervisor-t5Q4UI.log django-stdout---supervisor-cTSBmq.log

celery_worker-stderr---supervisor-TRFzc7.log supervisord.log

celery_worker-stdout---supervisor-xNgeBU.log

2,查看日志

运行容器时,将9001端口映射出去,通过ip:9001访问:

点击 Tail -f 查看各个进程的日志。

以上是 详解Docker容器运行多条命令(supervisor) 的全部内容, 来源链接: utcz.com/z/319207.html

回到顶部