Home > Software engineering >  Unable to connect to postgresql setup on a docker container from Java code
Unable to connect to postgresql setup on a docker container from Java code

Time:10-15

I have installed a postgres image on a docker container -

I also installed pgadmin and connected the postgres and pgadmin by adding them to a docker network. I am able to connect to the db via pgadmin

I now want to access this local-postgres instance from within my java code, but I get an error that the connection attempt failed.

What am I missing here?


docker run --name pgadmin -e "[email protected]" -e "PGADMIN_DEFAULT_PASSWORD=admin" -p 5050:80 -d dpage/pgadmin4 

docker network create --driver bridge pgnetwork

docker network connect pgnetwork local-postgres

docker network connect pgnetwork pgadmin 

below are the application.properties file settings


spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.show-sql=true

spring.datasource.url=jdbc:postgresql://local-postgres:5432/db-java-docker

CodePudding user response:

Are you running your java application via Docker inside of pgnetwork? If not, the local-postgres hostname will not resolve. If you don't want to run the java application via docker, you'll have to give the postgres port a mapped host port that will let you resolve it via localhost. Here's an example:

# Maps the postgres port to port 5051 on your localhost
$ docker run \
  --name local-postgres \
  -e POSTGRES_USER=postgres \
  -e POSTGRES_PASSWORD=password \
  -e POSTGRES_DB=db-java-docker \
  -p 5051:5432 \
  postgres:14
spring.datasource.url=jdbc:postgresql://postgres:password@localhost:5051/db-java-docker

CodePudding user response:

I suppose that you forgot to add to your config file login and password for db:

spring.datasource.username: DB_USERNAME

spring.datasource.password: DB_PASSWORD

where DB_USERNAME and DB_PASSWORD so that you created docker postgres container

  • Related