skip to Main Content

When I first time build containers database doesn’t have enough time to initialize itself while web service and nginx is already up and thus I can’t reach the server from a first run, but after second containers run everything works properly. I have tried this command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py runserver 0.0.0.0:8000"] to wait until database got initialized, but it didn’t help me. Help me please to make my services wait until database get initialized. I’ve tried solutions from this post, but nothing was helpful. Help me please to make my services wait until database get initialized. Thanks in advance!

Here is my docker-compose file

version: "3.9"

services:
  db:
    image: postgres:13.3-alpine
    container_name: db
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://localhost:5432" ]
      interval: 30s
      timeout: 10s
      retries: 5
  web:
    build: .
    container_name: web
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    restart: on-failure
    depends_on:
      - db
  nginx:
    build: ./nginx
    container_name: nginx
    ports:
      - "80:80"
    restart: on-failure
    depends_on:
      - web
      - db

2

Answers


  1. Chosen as BEST ANSWER

    Problem solved by adding the short line of script to command.

      web:
        build: .
        container_name: web
        command: bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; python manage.py runserver 0.0.0.0:8000'
        volumes:
          - .:/code
        ports:
          - "8000:8000"
        restart: on-failure
        depends_on:
          - db
    

  2. depends_on only waits until the service has started, not until it is healthy. You should try to additionally define the condition service_healthy to wait until a dependency is healthy:

    depends_on:
      db:
         condition: service_healthy
    

    Here’s a complete docker-compose file for reference:

    version: "3.9"
    
    services:
      db:
        image: postgres:13.3-alpine
        container_name: db
        volumes:
          - ./data/db:/var/lib/postgresql/data
        environment:
          - POSTGRES_DB=postgres
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres
        ports:
          - "5432:5432"
        healthcheck:
          test: ["CMD-SHELL", "pg_isready -U postgres"]
          interval: 1s
          timeout: 5s
          retries: 5
      web:
        image: nginx:latest
        container_name: web
        restart: on-failure
        depends_on:
          db:
            condition: service_healthy
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search