Search code examples
postgresqldockernetwork-programminglocalhostdocker-compose

How to connect from docker-compose to Host PostgreSQL?


I have a server with installed PostgreSQL. All my services work in containers (docker-compose). I want to use my Host PostgreSQL from containers. Buy I have the error:

  Unable to obtain Jdbc connection from DataSource (jdbc:postgresql://localhost:5432/shop-bd) for user 'shop-bd-user': Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  SQL State  : 08001
  Error Code : 0
  Message    : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

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

My docker-compose is using host network_mode, like this:

version: '3'
services:
  shop:  
    container_name: shop
    build: ./shop
    hostname: shop
    restart: always   
    ports:
      - 8084:8084
    network_mode: "host"

My database connection URL is: jdbc:postgresql://localhost:5432/shop-bd


Solution

  • According to the documentation, from version 18.03 onwards, using host.docker.internal as DNS works for me, without specifying neither --net=host or network_mode: "host"