rtfm snippets

How to access a service running on the host from a docker container

Tagged container, docker, host, ip, docker-compose, subnet, ufw, rtfm  Languages bash

How to access a service running on the host from a docker container? Easy…

First, RTFM:



Things you can try:

  1. Create a custom network (bridge)
  2. Make the docker container use the network
  3. On the host make the service listen to the hosts IP address on the custom network
version: "3.8"
    image: registry.gitlab.com/xxx/mycontainer:v1
      - mynetwork
    env_file: ./mycontainer.env
        - subnet:

The docker container will be assigned an IP from the subnet.

Now, just make sure the service is listening to the host’s IP address on the network which should be

Lastly, remember to allow the traffic in the firewall. See UFW example below:

# Check where the connection is coming from:
sudo dmesg
# Unblock the connections by source IP
sudo ufw allow in from "" to port 5432
# Or, unblock the connections by network name
sudo ufw allow in on <name of network> to port 5432

Bad ideas

There are many other ways of achieving this, which are more or less bad ideas…

  • Option 1: docker hostnames

This option is mostly useful in development environments:

# Mac
ping docker.for.mac.localhost

# Windows
ping docker.for.win.localhost

# Linux: use the Docker IP or the hosts external IP, see:
# https://github.com/docker/for-linux/issues/264#issuecomment-385698947
  • Option 2: host networking

This option is not a good idea if you plan on hosting many projects on the same server.

Note that it’s not possible to use host networking on Mac or Windows, only Linux:

The host networking driver only works on Linux hosts, and is not supported on Docker Desktop for Mac, Docker Desktop for Windows, or Docker EE for Windows Server.