Baptiste
Baptiste

Reputation: 133

Docker expose ports between containers

I would like to have a python flask application that runs with a postgresql database (psycopg2). So I made this docker-compose file:

version: "3"
services:
  web:
    depends_on:
      - database
    container_name: web
    build:
      context: "."
      dockerfile: "docker/Dockerfile.web"
    ports:
      - 5000:5000
    volumes:
      - database:/var/run/postgresql
  database:
    container_name: database
    environment:
      POSTGRES_PASSWORD: "password"
      POSTGRES_USER: "user"
      POSTGRES_DB: "products"
    image: postgres
    expose:
    - 5432
    volumes:
    - database:/var/run/postgresql
volumes:
  database:

In my app.py I try to connect to postgres like this:

conn = psycopg2.connect(database="products", user="user", password="password", host="database", port="5432")

When I run docker-compose up I get the following error:
"Is the server running on host "database" (172.21.0.2) and accepting TCP/IP connections on port 5432?"

I don't know where I have mistaken here.

Any ideas ?

Thanks for replies and have a nice day.

Upvotes: 2

Views: 324

Answers (1)

Nguyen Lam Phuc
Nguyen Lam Phuc

Reputation: 1421

I think what happened is that even though you have the flag depends_on set to database, that only means that the web container will start after database container starts. However, for the first time, the database will generally take quite some time to set up and when your web server is up, the database is still not ready to accept the connection.

2 ways to work around the problem here:

  1. Easy way with no change in code: run docker-compose up -d (detach mode) and wait for the database to finish initializing. Then run docker-compose up -d again and your web container will now be able to connect to the database.
  2. Second way is to update the web container with restart: always so docker-compose will keep trying to restart your web container until it runs successfully (until the database is ready to accept connection)
version: "3"
services:
  web:
    depends_on:
      - database
    ...
    restart: always
    ...

Upvotes: 2

Related Questions