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;