Published in 19:35 of 07/03/2015 by Bruno Rocha
Bruno Rocha There is more to life than increasing its speed!

Published in 19:35 of 07/03/2015


Dealing with linked containers dependency in docker-compose

In docker-compose a common problem is starting services and daemons in containers that depends on services running on linked containers, in example: your app depends on elasticsearch but it is not ready when the app container is started. Solution is to use a wait script.

I knew that docker-compose team is working on adding a WAIT parameter, but while it is not ready we can use a wait script to load our services.

The process is simple, your container will execute a shell script that will try to execute a HEALTH CHECK many times you want before starting the main command. The health check, the command, the sleep and how many loops to try will be defined in environment variables

This is a program that needs to access an elasticsearch server located in 'elastic' host (that will be mapped by compose

from datetime import datetime 
from elasticsearch import Elasticsearch
es = Elasticsearch('elastic')
es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp":})
print es.get(index="my-index", doc_type="test-type", id=42)


    image: elasticsearch
    command: elasticsearch"YourNodeName"
       - "9200:9200"

    image: ubuntu:14.04
    command: wait_to_start
    working_dir: /src
        - elastic:elastic
        - .:/src
        - WAIT_COMMAND=[ $(curl --write-out %{http_code} --silent --output /dev/null http://elastic:9200/_cat/health?h=st) = 200 ]
        - WAIT_START_CMD=python
        - WAIT_SLEEP=2
        - WAIT_LOOPS=10

wait_to_start script



is_ready() {
    eval "$WAIT_COMMAND"

# wait until is ready
while ! is_ready; do
    i=`expr $i + 1`
    if [ $i -ge $WAIT_LOOPS ]; then
        echo "$(date) - still not ready, giving up"
        exit 1
    echo "$(date) - waiting to be ready"
    sleep $WAIT_SLEEP

#start the script

Now when you start your environment with docker-compose up the app container will start and execute wait_to_start script, which will perform the test defined in WAIT_COMMAND environment variable and will retry until the test succeeds, so it will end executing the program defined in WAIT_START_CMD

Full code on gist:

This code was made with StackOverflow help

  • from dynaconf import settings in python · 14:38 of 04/12/2019
  • Hacktoberfest 2018 in Home · 14:35 of 10/01/2018
  • Announcing the first Flask Conference in Brazil - August 2018 in flask · 19:07 of 06/28/2018

  • comments powered by Disqus Go Top