Home > Enterprise >  automatic dns resolution does not work on containers running on host network
automatic dns resolution does not work on containers running on host network

Time:09-14

I have two containers running on the same host using docker, however one container uses the host network while the other uses a custom bridge network as follows:

version: '3.8'

services:
  app1:
    container_name: app1
    hostname: app1
    image: app1/app1
    restart: always
    networks:
      local:
        ipv4_address: 10.0.0.8
    ports:
      - "9000:9000/tcp"
    volumes:
      - /host:/container

  app2:
    container_name: app2
    hostname: app2
    image: app2/app2
    restart: always
    network_mode: host
    volumes:
      - /host:/container

networks:
  local:
    ipam:
      driver: bridge
      config:
        - subnet: "10.0.0.0/24"

i have normal ip communication between the two containers however when i want to use the hostname of the containers to communicate it fails. is there a way to make this feature work on host networks?

CodePudding user response:

No, you can't do this. You probably could turn off host networking though.

Host networking pretty much completely disables Docker's networking layer. In the same way that a process outside a container can't directly communicate with a container except via its published ports:, a container that uses host networking would have to talk to localhost and the other container's published port. If the host has multiple interfaces it's up to the process to figure out which one(s) to listen on, and you can't do things like remap ports.

You almost never need host networking in practice. It's appropriate in three cases: if a service listens on a truly large number of ports (thousands); if the service's port is unpredictable; or for a management tool that's consciously trying to escape the container. You do not need host networking to make outbound network calls, and it's not a good solution to work around an incorrect hard-coded host name.

For a typical application, I would remove network_mode: host. If app2 needs to be reached from outside the container, add ports: to it. You also do not need any of the manual networking configuration you show, since Compose creates a default network for you and Docker automatically assigns IP addresses on its own.

A functioning docker-compose.yml file that omits the unnecessary options and also does not use host networking could look like:

version: '3.8'
services:
  app1:
    image: app1/app1
    restart: always
    ports: # optional if it does not need to be directly reached
      - "9000:9000/tcp"
    # no container_name:, hostname:, networks:, manual IP configuration
    # volumes: may not be necessary in routine use
  app2:
    image: app2/app2
    restart: always
    # add to make the container accessible
    ports:
      - "3000:3000"
    # configure communication with the first service
    environment:
      APP1_URL: 'http://app1:9000'
  • Related