How initialize sequentially two containers in docker composer

Published Dec 15, 2017


Sometimes we have more than one images that we want to initialize sequentially, that means start the second one until the first one was started, this can be needed in case one container depends on the other, for example, lets thing in a database image and a service that will use it, the proper way is to wait until the database is started to start the service that will use it.

Step by Step guide (A working example)

  1. For this purpose we will use a bash script named that can be found in this github link: This script is a pure bash script that will wait on the availability of a host and TCP port. It is useful for synchronizing the spin-up of interdependent services.

  2. In our docker-compse.yml file, we will tell the second service to wait until the first service is available, for this example until de dabatase is started.

  3. So in this example we will use the mongoDB image available in docker-hub.
    a. In order to create an local image of the mongoDB image we will run the following command:
    1. docker pull mongo.
    b. We will use ubuntu image as a client service for our database container, just run the following command to make ubuntu image available.
    1. docker pull ubuntu
    c. Then we need to create a Dockerfile to create our own image based in the busybox.
    1. Create a folder named waitforit: mkdir waitforit
    2. create the following file in the folder named waitforit just created.
    3. The Dockerfile should looks as follow (See the attached Dockerfile for more info): Dockerfile
    4. FROM ubuntu
    MAINTAINER Rodrigo Ruiz,
    WORKDIR /usr/local/src/
    COPY /usr/local/src/
    RUN chmod +x /usr/local/src/

     5. Copy the file to waitforit folder just created
     6. In a terminal go the folder just created: cd waitforit
     7. Run the following command to create our own image based in busybox that will contains the wait for it script:
     	1. docker build -t waitforit .

    d. Then we need to create our docker-compose.yml
    1. Create a file named docker-compose.yml inside the waitforit folder that we just create. See the attached docker-compose.yml and take it as example.
    2. Then we only need to run the following command:
    1. docker-compose up


FROM ubuntuMAINTAINER Rodrigo Ruiz, /usr/local/src/COPY /usr/local/src/RUN chmod +x /usr/local/src/

--Dont just copy-`paste the following code, use space to indent the file (dont tab).

version: '3'
image: mongo
- "27017:27017"
- /tmp/datadir:/data/db #Change the /usr/local/datadir for any otherdirectory or just create this one.
image: waitforit
- "db"
command: >
bash -c "/usr/local/src/ --timeout=0 db:27017"

Discover and read more posts from Rodrigo Ruiz
get started