Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Windows Postgres from Debian Docker container

I am running Postgres on a Windows 10 computer, and I want to connect to it from a Docker container. I've followed instructions from many sources and things should be working, but they're not.

Command line used to create Docker container:

docker run --rm -d --network=host --name mycontainer myimage

In postgresql.conf:

listen_addresses = '*'  

In pg_hba.conf:

host    all             all             172.17.0.0/16           trust

In the bash shell of my container, I run:

psql -h 127.0.0.1

and I get the error:

psql: could not connect to server: Connection refused

Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

Needless to say, Postgres is definitely running on my computer and I am able to query it from local applications. What am I missing?

like image 883
Shaul Behr Avatar asked Oct 11 '18 16:10

Shaul Behr


People also ask

How do I connect to a PostgreSQL container?

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

THIS WON'T WORK FOR DOCKER v18.03 AND ONWARDS
The answer is already there - From inside of a Docker container, how do I connect to the localhost of the machine?

This question is related to a mysql setup, but it should work for your case too.

FOR DOCKER v18.03 ONWARDS

Use host.docker.internal to refer to the host machine.

https://docs.docker.com/docker-for-windows/networking/#i-cannot-ping-my-containers

like image 190
Mahesh H Viraktamath Avatar answered Sep 29 '22 18:09

Mahesh H Viraktamath


As you've discovered, --network-host doesn't work with Docker for Windows or Docker for Mac. It only works on Linux hosts.

One option for this scenario might be to host PostgreSql in a container, also. If you deploy them with a docker-compose file, you should be able to have two separate Docker containers (one for the database and one for your service) that are networked together. By default, docker-compose will expose containers to others in the same compose file using the container name as its DNS name.

You could also consider including the database in the same container as your service, but I think the docker-compose solution is better for several reasons:

  1. It adheres to the best practice of each container having only a single process and single responsibility.
  2. It means that you can easily change and re-deploy your service without having to recreate the database container.
like image 26
MJRousos Avatar answered Sep 29 '22 19:09

MJRousos