Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 961
Max Avatar asked Jan 19 '18 23:01

Max


People also ask

Can I run postgres in docker?

Developers can perform Data Processing Operations using any Database Management System (DBMS) like PostgreSQL by pulling in their respective Docker Image files from the Docker Hub.

How do I access docker in PostgreSQL?

Connecting to the PSQL server via CLI : Run the below command to enter into the container (with the ID from step-1). docker exec -it <PSQL-Container-ID> bash. Authenticate to start using as postgres user. psql -h localhost -p 5432 -U postgres -W.


2 Answers

Updated Apri, 2018

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

like image 116
Satjapong Meeklai Avatar answered Oct 17 '22 00:10

Satjapong Meeklai


This would have worked if you were on linux OS. But this won't work on Mac or Windows. The thing is that when you use --net=host, you still are not on host network. That is the limitation of how docker for windows work

Instead of localhost you need to use docker.for.win.localhost as the host. This is a special DNS name which is available on Docker for Windows when you want to refer to the host localhost

like image 45
Tarun Lalwani Avatar answered Oct 17 '22 00:10

Tarun Lalwani