All Articles

Wait for MongoDB, Postgres or MySql to start on Docker

Quick tip here.

I was struggling to get this thing working so I need to share with you guys.

Assuming that you have an app depending on a MongoDB container:

version: "3.3"
services:
  web:
    build: .
    volumes:
      - "./app:/src/app"
    ports:
      - "3030:3000"
    links:
      - mongo
    depends_on:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
volumes:
  mongo_data:

In my case it’s a NodeJS app.

The MongoDB is quite slow to get up, so when the app starts, the linked container is ready but not the database itself.

To solve this problem you can use a script to explicitly wait for MongoDB service to be up.

Add this to your Dockerfile

FROM node:latest

RUN mkdir /src


WORKDIR /src
ADD app/package.json /src/package.json
RUN npm install

EXPOSE 3000

## THE LIFE SAVER
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait /wait
RUN chmod +x /wait

## Launch the wait tool and then your application
CMD /wait && npm start

And now change your docker-compose.yml file and adds a WAIT_HOSTS section

version: "3.3"
services:
  web:
    build: .
    volumes:
      - "./app:/src/app"
    ports:
      - "3030:3000"
    links:
      - mongo
    depends_on:
      - mongo
    environment:
      WAIT_HOSTS: mongo:27017
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
volumes:
  mongo_data:

And that’s it.

You can use it for any other service such as Postgres, MySQL, etc …

To do this you just need to use commas:

version: "3"

services:

  mongo:
    image: mongo:3.4
    hostname: mongo
    ports:
      - "27017:27017"
  
  postgres:
    image: "postgres:9.4"
    hostname: postgres
    ports:
      - "5432:5432"

  mysql:
    image: "mysql:5.7"
    hostname: mysql
    ports:
      - "3306:3306"
      
  mySuperApp:
    image: "mySuperApp:latest"
    hostname: mySuperApp
    environment:
      WAIT_HOSTS: postgres:5432, mysql:3306, mongo:27017

Hope it helps