Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few ways to make Docker wait until PostgreSQL is running:

  1. HEALTHCHECK command: You can use the HEALTHCHECK command in your Dockerfile to check if PostgreSQL is running. For example:

    HEALTHCHECK CMD pg_isready -U postgres -h localhost || exit 1
    

    This command checks for the availability of the postgres database user on the host localhost. If the PostgreSQL server is not running or not accepting connections, the command will exit with a non-zero status code, which will indicate that the container is unhealthy.

  2. Entry point script: You can create an entry point script that checks if PostgreSQL is running before starting your application. For example:

    #!/bin/sh
    set -e
    
    # Wait for PostgreSQL to be ready
    until pg_isready -U postgres -h localhost
    do
     echo "Waiting for PostgreSQL to be ready..."
     sleep 1
    done
    
    # Start your application
    exec your-app-command
    

    This script will wait for PostgreSQL to be ready by calling pg_isready in a loop until it succeeds. Once PostgreSQL is ready, it will start your application.

  3. Docker Compose: If you are using Docker Compose to manage multiple containers, you can define a depends_on directive in your docker-compose.yml file. For example:

    version: '3'
    services:
     postgres:
       image: postgres
       restart: always
       environment:
         POSTGRES_PASSWORD: mysecretpassword
     myapp:
       build: .
       depends_on:
         - postgres
    

    This configuration tells Docker Compose to start the postgres container first, and then start the myapp container after the postgres container is running.