Ask Your Question
1

How can Docker be made to wait until postgresql is running?

asked 2022-02-09 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-12-30 13:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-09 11:00:00 +0000

Seen: 12 times

Last updated: Dec 30 '22