astar
astar

Reputation: 315

Spring Boot Docker - connection to localhost:5432 refused

I am new to Docker. I am trying to dockerize my Spring Boot application but getting the error connection to localhost:5432 refused . The Spring Boot application has a postgresql db connection and uses random port to run on Tomcat. Please find the details below, requesting to please check and help in resolving the issue. Please give a detailed solution as I am new to Docker.

Dockerfile

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/SpringConversionFactor-0.0.1-SNAPSHOT.jar
WORKDIR /opt/app
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","app.jar"]

Docker run

docker run springconversionfactor

Exception

Connection to localost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

Upvotes: 2

Views: 4147

Answers (2)

Mihai Zanfir
Mihai Zanfir

Reputation: 51

I had the same issue and this is how I fixed it. From docker Run the postgres image. A container will be created for this. Run the following command to get the container id of running postgres image:

docker ps -a

This will list the containers.

Copy the id of the postgres container (usually is the first column) (Ex: b5095a58da29):

Run the following command to get its IP:

docker inspect b5095a58da29

It will list a big JSON with some properties. Go and copy the IP from the "IPAddress" property (Ex: 173.18.0.2). As you see, this is in the Networks -> bridge section.

Now, go in the application.properties file of Spring Boot and write the correct IP for the postgresql connection.

# Set here configurations for the database connection
spring.datasource.url=jdbc:postgresql://173.18.0.2:5432/mydb
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.driver-class-name=org.postgresql.Driver

Now rebuild the jar for the spring app, remake the spring app image and run it with docker. For me it worked fine after that. I'll write here the other commands as I used:

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=admin -e POSTGRES_USER=admin -e POSTGRES_DB=mydb -v //C/Work/Docker/PostgreSql:/var/lib/postgresql/data --name=postgres_con postgres

docker build -t spring-app .
docker run -p 8080:8080 spring-app

Upvotes: 0

Bhagyashri Machale
Bhagyashri Machale

Reputation: 219

When you are running any application in docker it gets isolated from your existing environment.Here you are running spring boot application in docker and provided postgresql url as localhost:5432,because of that your spring boot application is finding postgres db inside your spring boot docker container.Please make sure where your postgres db is running.If it is running on your server give url as server_ip:5432 or if it is running in other conatiner then give it as container_name:5432 (here you can do port mapping with your server also).

Upvotes: 4

Related Questions