Reputation: 4307
I have the following definition of docker-compose file with postgres image that I want to run and connect to it from hosting machine of my PC, but I'm getting Connection Refused localhost:5432
all the time. I realize that container has to be run on host network driver, but network mode doesn't solve this problem. What I'm doing wrong?
I run this with docker-compose -f [file] up
on Windows 10 with Docker for Desktop
version: '3.7'
services:
database:
image: postgres:10.6
restart: always
ports:
- "5432:5432"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=p0stgr@s
- POSTGRES_DB=eagle_eye_local
network_mode: host
When I run the same container with the following command it works:
docker container run --name postgres10.6 -e POSTGRES_PASSWORD=p0stgr@s -e POSTGRES_USER=postgres -e POSTGRES_DB=eagle_eye_local -p 5432:5432 postgres:10.6
Upvotes: 1
Views: 4419
Reputation: 12240
I'm assuming you are not running natively on linux but use some Docker for Desktop. Then the short answer is: Remove the network_mode: host
and the compose setup will work the same way your docker run command works.
version: '3.7'
services:
database:
image: postgres:10.6
restart: always
ports:
- "5432:5432"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=p0stgr@s
- POSTGRES_DB=eagle_eye_local
The two examples you provided are not really equal even though they can lead to some similar results when run on a real linux host (similar in a way that on a linux host you will be able to access the postgres instance via localhost:5432
on the host machine).
If you run the given compose file on Docker for Desktop (Mac or Windows) you must keep in mind that in this case there is a VM running your containers and all commands are passed into that VM. If you don't use network_mode: host
Docker will (1) expose the port correctly on the VM and (2) have some proxy process in place on your host machine (mac/windows) to forward the traffic into the VM. This basically doesn't work when you start the container with network_mode: host
.
You can verify the established mapping when running docker ps
under the Ports
column. This will be empty if you run with network_mode: host
.
For some more details see the discussions in the docker forum.
Upvotes: 1