This question has been asked many times here, here and here but these solutions are not working for me.
I have created a Postgres and a AppServer container with this docker-compose.yml file
version: "3.7"
services:
db:
image: postgres:alpine
container_name: db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydb
POSTGRES_INITDB_ARGS: '-A md5'
volumes:
- ./pgdata:/var/lib/postgressql/data
ports:
- "5432:5432"
api:
build: api
container_name: api
volumes:
- ./database/migrations:/migrations
ports:
- "8080:8080"
links:
- db
depends_on:
- db
After running this, I can successfully do
docker exec -it db psql -U user mydb
and I connect to Postgres successfully. I can also successfully login into terminals of both containers with
docker exec -it api bash
docker exec -it db bash
from inside of bash of api I can ping db without any problem
However from my api container, I cannot establish a JDBC connection to the Postgres database.
api | Flyway Community Edition 7.3.2 by Redgate
api | ERROR:
api | Unable to obtain connection from database (jdbc:postgresql://db:5432/mydb) for user 'user': Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
api | SQL State : 08001
api | Error Code : 0
api | Message : Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api |
api | Caused by: org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | Caused by: java.net.ConnectException: Connection refused (Connection refused)
Why am I getting connection refused when I can connect via psql? This is my flyway conf
flyway.url=jdbc:postgresql://db:5432/mydb
flyway.user=user
flyway.password=password
flyway.locations=filesystem:/migrations
Edit:: So if I wait and then execute flyway migrate after some time from docker exec -it api bash everything works fine. I think what is happening above is that my flyway migrate command is running even before the database is ready.
Why is this happening? because I have specified dependency so my API container should start only when the database has fully started. but it seems that is not the case.