简体   繁体   中英

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: "admin@admin.com.br"
      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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM