Reputation: 133
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.
/var/run/postgresql
directory on "web" container.Any ideas ?
Thanks for replies and have a nice day.
Upvotes: 2
Views: 324
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:
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.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