kojiro
kojiro

Reputation: 77059

How to know if a service container is ready for connections?

I frequently run into this issue creating stacks in Docker. Say I have a LAMP stack in docker-compose.yml:

db:
    image: mysql
    environment:
        MYSQL_VARIOUS: things
web:
    build: .
    links:
        - db
    ports:
        - "80"
    entrypoint:
        - setup-and-start

And the setup-and-start script looks like this:

wait_for_mysql && initialize

If the web container has mysql-client installed on it, then I can easily define wait_for_mysql:

wait_for_mysql() {
    local timeout=10
    while sleep 1; do
        mysql [credentials] -e 'select 1;' && return 0
        (( --timeout <= 0 )) && break
    done
    echo 'Failed to initialize mysql within time limit.' >&2
    return 1
}

But many containers won't have the client. Rather than install it into every lightweight container, is there a reasonable way I can check if mysql is up and running before initializing my application? It should work on most Docker containers, but doesn't have to be a perfect validation of mysql; even checking for an expected telnet response would probably be acceptable (except that telnet is also not commonly on docker images).

Upvotes: 2

Views: 1536

Answers (1)

Usman Ismail
Usman Ismail

Reputation: 18649

The question is covered in the Docker Compose FAQ. Short answer there is no good way, and this is by design. Though this use case is very common in testing and small applications for any significant system wait for startup is an anti-pattern.

The problem of waiting for a database to be ready is really just a subset of a much larger problem of distributed systems. In production, your database could become unavailable or move hosts at any time. The application needs to be resilient to these types of failures.

Upvotes: 3

Related Questions