How does Docker start multiple services at the same time

  • 2020-05-17 07:07:14
  • OfStack

In the previous Docker articles, you only started one backend service when you started the container. Today, how can you start multiple services through supervisor

1. First create a directory and create an Dockerfile in the directory. The contents of the file are as follows


FROM centos:centos6

MAINTAINER Fanbin Kong "kongxx@hotmail.com"

RUN rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
RUN yum install -y openssh-server sudo mysql-server mysql supervisor
RUN sed -i 's/UsePAM yes/UsePAM no/g' /etc/ssh/sshd_config 
 
RUN useradd admin
RUN echo "admin:admin" | chpasswd
RUN echo "admin ALL=(ALL)  ALL" >> /etc/sudoers
 
RUN ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN mkdir /var/run/sshd

RUN /etc/init.d/mysqld start &&\
 mysql -e "grant all privileges on *.* to 'root'@'%' identified by 'letmein';"&&\
 mysql -e "grant all privileges on *.* to 'root'@'localhost' identified by 'letmein';"&&\
 mysql -u root -pletmein -e "show databases;"

RUN mkdir -p /var/log/supervisor
COPY supervisord.conf /etc/supervisord.conf

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

2. Create the supervisord.conf file in the directory where Dockerfile is located, as follows:


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


3. Run the build command in the Dockerfile directory to generate the image file, using mysql_server as the image file name

sudo docker build -t myserver .

Start the container

4.1 start the container with the following command

sudo docker run --name=myserver -d -P myserver

4.2 after starting the container, you can view it using "sudo docker ps", at which point you can see column PORTS as
"0.0.0.0:49171 - > 22/tcp, 0.0.0.0:49172- > 3306 / tcp"
Ports 22 and 3306 of the container are mapped to ports 49171 and 49172 of the host machine.

4.3 at this point you can access the ssh and mysql services with the following command

ssh admin@ < The host machine > -p < Host machine port >
mysql -h < The host machine > -u root -pletmein -P 49172

4.4 of course, you can also view the container IP address using "sudo docker inspect myserver | grep IPAddress" and then access the ssh and mysql services through the following commands

ssh admin@ < Container machine IP >
mysql -h < Container machine IP > -u root -pletmein


Related articles: