Docker: Accessing Host

Accessing the host machine from inside a docker container

Problem

I often come across a need to have a service running inside docker to communicate with a service running on the host machine (outside docker). This isn't always very easy to do.

Solution

One approach to solving this is to tell #docker to create a new host entry to point at the host machine.

When the host.docker.internal domain is used inside the container it will resolve to the host machine.

Docker

--add-host=host.docker.internal:host-gateway

Docker Compose

services:
  app:
    ...
    extra_hosts:
      - host.docker.internal:host-gateway

This approach may only work on docker versions v20.10 and above.

Details

This allows software running inside a docker container to access web services running on the host machine. For example, I used this to allow a prometheus instance running in a docker container to connect to a node exporter instance running on the host.

The extra_host or --add-host options are used to add extra entries in the container's /etc/hosts file. This can be used for various purposes, one of which is to add a domain to resolve to the host machine.

The host-gateway string is a special placeholder that docker replaces with the host's IP on the docker network.

Once this has been set up, services in the docker container can connect to the host machine by using the host.docker.internal URL.

Related