Rafa Acioly
Rafa Acioly

Reputation: 636

How to connect to a Postgres on Docker using java.sql package?

How do I connect to a PostgreSQL database (inside a Docker container) using java.sql. module?

I'm already running Postgres and accessing it using pgadmin with this config:

version: '3'

services:
  teste-postgres-compose:
    image: postgres
    environment:
      POSTGRES_PASSWORD: "Postgres2019!"
    ports:
      - "15432:5432"
    volumes:
      - /home/renatogroffe/Desenvolvimento/Docker-Compose/PostgreSQL:/var/lib/postgresql/data 
    networks:
      - postgres-compose-network

  teste-pgadmin-compose:
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: "[email protected]"
      PGADMIN_DEFAULT_PASSWORD: "PgAdmin2019!"
    ports:
      - "16543:80"
    depends_on:
      - teste-postgres-compose
    networks:
      - postgres-compose-network

networks: 
  postgres-compose-network:
    driver: bridge

But if I try to connect through my Java app I get the error:

org.postgresql.util.PSQLException: The connection attempt failed.

This is the connection that I'm trying to call:

try{
    Class.forName("org.postgresql.Driver");            
    connection = DriverManager.getConnection("jdbc:postgresql://teste-postgres-compose:15432/postgres", "postgres", "Postgres2019!");
} catch(ClassNotFoundException erro1){
    throw new RuntimeException(erro1);
} catch (SQLException erro2) {
    throw new RuntimeException(erro2);
}

return connection;

Upvotes: 2

Views: 6080

Answers (1)

MartenCatcher
MartenCatcher

Reputation: 2887

Found 2 mistypes in your configuration

services:
  teste-postgres-compose:
    image: postgres
    environment:
      POSTGRES_PASSWORD: "Postgres2019!"
    ports:
      - "15432:5432"
connection = DriverManager.getConnection("jdbc:postgresql://test-postgres-compose:5432/postgres", "postgres", "Postgres2019!");
  1. Your service has name teste-postgres-compose but you connect to test-postgres-compose
  2. - "15432:5432" you've exposed port 15432 but connect to 5432

Update:

Sorry, my mistake. Of course the second container is pgadmin, not your application.

The containers' names like teste-postgres-compose are available just in postgres-compose-network network and may be used just other by other containers in same network. Applications are launched locally (I guess you launched java code from your IDE) may use just exposed ports with localhost. Services' names are not available outside the network.

For example your postgres has to be available by address:

localhost:15432

Because you've exposed this port in the compose file. Also you may try loopback 127.0.0.1 or your host ip address.

Upvotes: 3

Related Questions