-1

I want to access service1 from inside of service2 container by using localhost:5432. How can do so?

This is what my docker compose currently looks like:

services:
  service1:
    image: postgres:12
    ports:
      - '172.10.1.1:5432:5432'
    expose:
      - '5432'
    environment:
      - POSTGRES_USER=project
      - POSTGRES_PASSWORD=pass
    volumes:
      - db_data:/var/lib/postgresql/data
  service2:
        build: .
        ports:
          - '172.10.1.1:1234:1234'

Please note I know i can access it by using service1:5432 or just service1. But I would like to use localhost if possible.

Raman
  • 216
  • 3
  • 15
  • 2
    Check this - https://stackoverflow.com/questions/43547795/how-to-share-localhost-between-two-different-docker-containers You can do it in a hacky way but this sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you want to use localhost? – Shashank V Jan 26 '21 at 06:41

2 Answers2

0

It is not possible, because each container has a own ip.

But there is a workaround: Set network to host. So the ports are open on hostmaschine and are accessible via 127.0.0.1. Not working on windows.

But I don't know any good reason why you like to use localhost for postgres? Are you trying to authenticate via localhost? Don't do that - use a password instead.

akop
  • 5,981
  • 6
  • 24
  • 51
-1

Using host network maybe a solution you are finding https://docs.docker.com/network/host/

services:
  service1:
    image: postgres:12
    network_mode: host
    expose:
      - '5432'
    environment:
      - POSTGRES_USER=project
      - POSTGRES_PASSWORD=pass
    volumes:
      - db_data:/var/lib/postgresql/data
  service2:
    build: .
    network_mode: host
phapli
  • 627
  • 6
  • 16