Docker5

docker container startup method of multiple service

This project is maintained by wangfakang

关于docker启动容器的时候如何同时执行多个任务:
   从docker的官方文档来看CMD和ENTRYPOINT好像多一次只可以执行一条命令,但是可以给多个参数.
那现在有个需求就是我要在启动容器的时候启动多个任务该如何做恩:

     方案1.使用shell脚本,把自己要启动的多个任务写在脚本中,然后ENTRYPOINT ["/docker-entrypoint.sh"]    
     方案2.使用 supervisor,他是linux下的一个进程管理工具.使用方法如下:     

下面方法摘自docker神书教程

配置

首先创建一个 Dockerfile,内容和各部分的解释如下。 

FROM ubuntu:13.04
MAINTAINER examples@docker.com
RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list
RUN apt-get update
RUN apt-get upgrade -y

安装 ssh、apache 和 supervisor

RUN apt-get install -y --force-yes  perl-base=5.14.2-6ubuntu2
RUN apt-get install -y apache2.2-common
RUN apt-get install -y openssh-server apache2 supervisor
RUN mkdir -p /var/run/sshd
RUN mkdir -p /var/log/supervisor

这里安装 3 个软件,还创建了 2 个 ssh 和 supervisor 服务正常运行所需要的目录。

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

添加 supervisord 的配置文件,并复制配置文件到对应目录下面。

EXPOSE 22 80
CMD ["/usr/bin/supervisord"]

这里我们映射了 22 和 80 端口,使用 supervisord 的可执行路径启动服务。

supervisor配置文件内容

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

[program:apache2]
command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"

配置文件包含目录和进程,第一段 supervsord 配置软件本身,使用 nodaemon 参数来运行。第二段包含要控制的 2 个服务。 每一段包含一个服务的目录和启动这个服务的命令。

使用方法

创建镜像。

$ sudo docker build -t test/supervisord .

启动 supervisor 容器。

$ sudo docker run -p 22 -p 80 -t -i test/supervisord

2013-11-25 18:53:22,312 CRIT Supervisor running as root (no user in config file)
2013-11-25 18:53:22,312 WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
2013-11-25 18:53:22,342 INFO supervisord started with pid 1
2013-11-25 18:53:23,346 INFO spawned: 'sshd' with pid 6
2013-11-25 18:53:23,349 INFO spawned: 'apache2' with pid 7

使用 docker run 来启动我们创建的容器。使用多个 -p 来映射多个端口,这样我们就能同时访问 ssh 和 apache 服务了。

可以使用这个方法创建一个只有 ssh 服务的基础镜像,之后创建镜像可以使用这个镜像为基础来创建

欢迎一起交流学习

在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流

Thx

Author