connection refused postgres docker

2020-04-17 04:27发布

问题:

I made a small application with spring-boot, spring jpa data, that connects to a dockerized postgres instace and it works pretty fine, even if I try to connect via 'psql' to the dockerized postgres instace it works well. The porblem is when I try to dockerize an image's instance of my spring-boot application and I try to link it with the dockerized postegres instance. The docker command I use is this

docker run -it --link mypgcontainerwithpwd:postgres --name postgresclient1 sprinbootjpa

As a I already mentioned the container mypgcontainerwithpwd is running and reachable either with a local application either via psql

psql -p 5555 postgres postgres

in the jar I'm going to execute the application.properties file looks like this

spring.datasource.url=jdbc:postgresql://localhost:5555/postgres
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.generate-ddl=true

During the starting phase an exception is raised up that prints: connection refused localhost-> 5555

The dockerfile that builds the instace looks like this

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD ./SpringJPA-PostgreSQ-0.0.1.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

I'm new to docker and I didn't find anything to fix the issue, I'm running docker on windows 10 with unix containers.

Thanks to all.

回答1:

In your property file you are stating that postgres is running in the same container as your Spring Boot application (localhost) which is not true as it is running in a different container.

Replace you property by this:

spring.datasource.url=jdbc:postgresql://postgres:5555/postgres

You could also point to the docker bridge ip which usually is 172.17.0.1.



回答2:

Change -

spring.datasource.url=jdbc:postgresql://localhost:5555/postgres

TO

spring.datasource.url=jdbc:postgresql://postgres:5555/postgres

Since you started the client container with link --link mypgcontainerwithpwd:postgres which means your client will be able to reach your mypgcontainerwithpwd container using alias postgres. localhost means your client container itself & not mypgcontainerwithpwd.



回答3:

This works, but I just want to emphasize Vivek's point that "postgres" comes from the container name and not the userID or the database type. I am using Docker Compose, so this name comes from my docker-compose.yml file.