Jason Strimpel
Jason Strimpel

Reputation: 15506

Accessing Docker Services from Host

I have a simple web app with a docker-compose.yml configuration like this:

version: "3"
services:
  web:
    build: .
    ports:
      - "8000:8000"
  db:
    image: postgres
    ports:
      - "5432:5432"

I can access the database service within the web app container with postgres://db:5432 because both containers share networking.

I'd like to access the database service from my host machine using postgres://db:5432. How do I map the db:5432 host from the container to db:5432 on my local host machine? I've tried adding 127.0.0.1:5432 db:5432 to my /etc/hosts file which does not seem to work.

Upvotes: 4

Views: 54

Answers (1)

Subesh Bhandari
Subesh Bhandari

Reputation: 1122

The /etc/hosts file is simply a way to statically resolve names when no DNS server is present or resolved. It can't map port addresses. Ref: https://serverfault.com/questions/54357/can-i-specify-a-port-in-an-entry-in-my-etc-hosts-on-os-x

It will work if you do,

127.0.0.1       db

Remove the port and it will work.

Also, you can directly access Postgres with localhost: 5432 from host machine.

Upvotes: 3

Related Questions