Starting docker containers in a specific order after a reboot

Context

Almost all of my docker containers are web applications that run on port 80. To allow them to run on the same host, I allow the docker to assign a random unused port and use jwilder/nginx-proxy ( link ) as a reverse proxy. To do this, run jwilder / nginx-proxy before starting the container , which is simple enough in the bash script that I run to start the container after creating it:

 ... ####################### # ensure that we are running the frontend proxy # which allows us to run multiple web containers RESULT=`docker ps | grep jwilder | wc -l` if [ $RESULT -gt 0 ];then echo "found frontend proxy." else echo "Deploying frontend proxy" docker run -d \ -p 80:80 \ -v /var/run/docker.sock:/tmp/docker.sock \ -t jwilder/nginx-proxy fi ####################### # Now start the container. docker run -d \ -e VIRTUAL_HOST=$VIRTUAL_HOST \ -p 80 \ -p 443 \ --name="$PROJECT_NAME" \ $CONTAINER_IMAGE 

Problem

I often have to restart my servers, and I need a solution that will start all my containers automatically and in the correct order.

I can use the docker run paramater --restart=always parameter so that all my running containers start automatically after reboot, however, how can I guarantee that my reverse proxy container starts first first and there is a slight delay before starting any of the others containers (in any order).

Ideally, I would like the solution not to be specific to the distribution, for example, using supervisord , instead of writing upstart or running the systemd script, but I need a way to connect to the launch after the docker daemon finished successfully.

+6
source share
1 answer

If you expose port 80 on all your containers using web applications, you can link to your Nginx container.

Here is a small docker-compose.yml :

 app: build: app/ expose: - "80" api: build: api/ expose: - "80" webserver: image: nginx ports: - "80:80" volumes: - default.conf:/etc/nginx/conf.d/default.conf links: - app - api 

And here is the configuration for Nginx:

 server { listen 80; server_name localhost; location / { proxy_pass http://app; } location /api { proxy_pass http://api; } } upstream app { server app:80; } upstream api { server api:80; } 

When binding the container to another container (in this case, Nginx), Docker modifies the /etc/hosts and adds lines like this:

172.17.0.7 api 165637cfd4ab yourproject_api_1

172.17.0.5 app dedf870dec53 yourproject_app_1

So, Nginx knows about api and app containers.

When the request arrives at "localhost: 80", Nginx will proxy it to http://app:80 . hosts resolves the htt://app request to 172.17.0.7 , and therefore this request is forwarded to the application container.

Launch all containers using $ docker-compose up , and you're done.

+5
source

Source: https://habr.com/ru/post/988986/


All Articles