How to share localhost between two different Docker containers?

The right way: don’t use localhost. Instead use docker’s built in DNS networking and reference the containers by their service name. You shouldn’t even be setting the container name since that breaks scaling.


The bad way: if you don’t want to use the docker networking feature, then you can switch to host networking, but that turns off a very key feature and other docker capabilities like the option to connect containers together in their own isolated networks will no longer work. With that disclaimer, the result would look like:

version: "2"

services:

  service_a:
    container_name: service_a.dev
    image: service_a.dev
    network_mode: "host"
    depends_on:
      - postgres
    volumes:
      - ../configs/service_a/var/conf:/opt/services/service_a/var/conf

  postgres:
    container_name: postgres.dev
    image: postgres:9.6
    network_mode: "host"
    volumes:
      - ../configs/postgres/scripts:/docker-entrypoint-initdb.d/

Note that I removed port publishing from the container to the host, since you’re no longer in a container network. And I removed the hostname setting since you shouldn’t change the hostname of the host itself from a docker container.

The linked forum posts you reference show how when this is a VM, the host cannot communicate with the containers as localhost. This is an expected limitation, but the containers themselves will be able to talk to each other as localhost. If you use a VirtualBox based install with docker-toolbox, you should be able to talk to the containers by the virtualbox IP.


The really wrong way: abuse the container network mode. The mode is available for debugging container networking issues and specialized use cases and really shouldn’t be used to avoid reconfiguring an application to use DNS. And when you stop the database, you’ll break your other container since it will lose its network namespace.

For this, you’ll likely need to run two separate docker-compose.yml files because docker-compose will check for the existence of the network before taking any action. Start with the postgres container:

version: "2"
services:
  postgres:
    container_name: postgres.dev
    image: postgres:9.6
    ports:
      - "5432:5432"
    volumes:
      - ../configs/postgres/scripts:/docker-entrypoint-initdb.d/

Then you can make a second service in that same network namespace:

version: "2"
services:
  service_a:
    container_name: service_a.dev
    image: service_a.dev
    network_mode: "container:postgres.dev"
    ports:
      - "6473:6473"
      - "6474:6474"
      - "1812:1812"
    volumes:
      - ../configs/service_a/var/conf:/opt/services/service_a/var/conf

Leave a Comment