To learn Docker I created a small spring boot app that can create/list/update users.
I run a postgresql database on port 5432 and I run my app on port 8081. The problem that when I try to start the container & my app:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
I created a network and start the containers like this:
docker run --name postgres --network demo-network -p 5432:5432 -e POSTGRES_PASSWORD=admin -d postgres
docker run --network demo-network -p 8081:8081 -d myuser/demodocker
My Spring Boot application.properties:
server.port=8081
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=drop-and-create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
javax.persistence.schema-generation.scripts.action=drop-and-create
What to fix to make it work?
2
Answers
In your Spring Boot application.properties file, you have configured the
spring.datasource.url
property to connect to PostgreSQL usinglocalhost:5432
. However, when running your Spring Boot application and PostgreSQL database in separate Docker containers, you cannot uselocalhost
to refer to the database container. Instead, you should use the hostname of the PostgreSQL container or the name of the service (container name) if they are on the same Docker network.Here’s how you can fix it:
application.properties
file:In the
spring.datasource.url
property, changelocalhost
topostgres
. This way, your Spring Boot application will connect to the PostgreSQL container using the container name as the hostname.Make sure both containers are on the same Docker network, as you’ve already done with the
demo-network
.Run your Spring Boot application container with the updated configuration:
Now, your Spring Boot application should be able to connect to the PostgreSQL database running in the "postgres" container using the hostname "postgres." This should resolve the connection issue.
Remember to rebuild and redeploy your Spring Boot application container after making these changes to your
application.properties
file.I think an even easier way would be to simple change your docker file to include –net=host
Once you do that any code inside your container wanting to access postgres is able to use localhost and have it resolve on the host machine, i think that is what you are looking for.