Docker-compose with 2 containers. 1st is a Postgres database and 2nd is a Java Spring Boot application. For running, I use further docker-compose config file:
docker-compose.yml
version: "3.7"
services:
db-service:
image: postgres
restart: always
volumes:
- /home/ec2-user/dbdata:/var/lib/postgresql/data
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: 1
POSTGRES_DB: auth
ports:
- 5432:5432
auth-service:
build: .
restart: always
depends_on:
- db-service
links:
- db-service
ports:
- 80:80
I suppose to use /home/ec2-user/dbdata
to containing database data and after all, data is created. successfully. And log of postgres container is:
PostgreSQL init process complete; ready for start
2021-01-07 01:36:16.786 UTC
[1] LOG: starting PostgreSQL 13.1 (Debian 13.1-1.pgdg100+1) on
x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2021-01-07 01:36:16.786 UTC [1] LOG: listening on
IPv4 address "0.0.0.0", port 5432 2021-01-07
01:36:16.786 UTC [1] LOG: listening on IPv6 address "::", port 5432
2021-01-07 01:36:16.790 UTC [1] LOG: listening on
Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2021-01-07 01:36:16.795 UTC [76] LOG: database system was shut down
at 2021-01-07 01:36:16 UTC 2021-01-07 01:36:16.800
UTC [1] LOG: database system is ready to accept connections
But Java app throws an error:
org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432
refused. Check that the hostname and port are correct and that the
postmaster is accepting TCP/IP connections.
But in port mapping is 5432:5432
.
And data source properties into Java app is:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/auth
spring.datasource.username=postgres
spring.datasource.password=1
What is can be the reason for this error?
2
Answers
It’s not working because the java app is pointed to 127.0.0.1 which is local to the java container and postgres is not running in that container.
In your properties file change this line:
to
Using
db-service
as the host comes from the name of the service in your docker-compose.yml file. See the docker compose networking page for more information.Another option, since both containers are linked (as per docker-compose file) is to use
localhost
(instead of127.0.0.1
) as the DB host in the connection string ->spring.datasource.url=jdbc:postgresql://localhost:5432/auth