Waiting for dependant container services post

This feeling when your application container fails because of not ready MySQL service yet.

More details

When the main application's container needs an external services like MySQL/PostgreSQL/Redis but the dependant service requires more time to launch, then the main container will fail.

But there is a simple and great solution thanks to jwilder effort.

Solution

# ./docker/
FROM php:7.3-cli-alpine

RUN apk add --no-cache openssl

ENV DOCKERIZE_VERSION v0.6.1
RUN wget https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz \
    && tar -C /usr/local/bin -xzvf dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz \
    && rm dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz
COPY entrypoint.sh /entrypoint.sh    
#!/bin/sh
# entrypoint.sh

dockerize \
    -wait tcp://mysql:3306 \
    -wait tcp://mongo:27017 \
    -timeout 60s

php [email protected]
version: '3.2'
services:
  app:
    build: docker/
  mysql:
    image: mysql:latest
  mongo:
    image: mongo:latest

Second way

What if you don't want to change the image? Then you can use an extra docker-compose service:

# docker-compose.yaml
version: '3.2'
services:
  app:
    image: php:7.3-cli-alpine
  mysql:
    image: mysql:latest
  mongo:
    image: mongo:latest
  waiting-for:
    image: jwilder/dockerize
    container_name: waiting-for
    command: |
      -wait tcp://mysql:3306
      -wait tcp://mongo:27017
      -timeout 60s

And then run the app with the following order:

docker-compose up -d mongo mysql
docker-compose run --rm waiting-for
docker-compose up app

Enjoy!

Links: * jwilder/dockerize * docker-compose

Categories: devops

Tags: docker, docker-compose