Search code examples
pythonpostgresqldockerdocker-composestartup-probe

flask app service can't connect to postgres service within docker-compose


I am trying to run flask, postgres and nginx services with following docker-compose:

version: '3.6'


services:

  postgres:
    image: postgres:10.5
    container_name: postgres
    hostname: postgres
    user: postgres  
    ports:
      - "5432:5432"
    networks:
      - db-tier
    environment:
      CUSTOM_CONFIG: /etc/postgres/postgresql.conf
    volumes:
      - ./postgres/sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql
      - ./postgres/postgresql.conf:/etc/postgres/postgresql.conf
    command: postgres -c config_file=/etc/postgres/postgresql.conf
    restart: always

  app:
    image: python/app:0.0.1
    container_name: app
    hostname: app
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
     - postgres
    networks:
      - app-tier
      - db-tier
    stdin_open: true

  nginx:
    image: nginx:1.22
    container_name: nginx-reverse-proxy-flask
    ports:
      - "8080:80"
    depends_on:
      - app
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    networks:
      - app-tier


networks:
  app-tier:
    driver: bridge
  db-tier:
    driver: bridge

This is what app.config["SQLALCHEMY_DATABASE_URI"] equals to postgresql://denis:1234Five@postgres:5432/app

The error after docker-compose up is:

app         | psycopg2.OperationalError: could not connect to server: Connection refused
app         |   Is the server running on host "postgres" (192.168.32.2) and accepting
app         |   TCP/IP connections on port 5432?

What could cause this type of error? I double checked the container name of postgres service, and it running with this name postgres why flask app doesn't "see" it?


Solution

  • This issue was resolved with postgres pg_isready adding following lines to postgres service:

    healthcheck:
      test: ["CMD-SHELL", "sh -c 'pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}'"]
      interval: 10s
      timeout: 3s
      retries: 3
    

    Took as solution from here Safe ways to specify postgres parameters for healthchecks in docker compose