subnet 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:

Linux (bridge network)

  1. Create a custom bridge network

You can also use the default bridge network.

  1. Make the docker container use the custom network

See network configuration in the docker compose example below.

  1. On the host make the service listen to the hosts IP address on the custom network

For example, change listen_addresses in postgresql.conf for PostgreSQL.

Example docker-compose.yml:

version: "3.8"
      - mynetwork
    env_file: ./mycontainer.env
        - subnet:

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

Make sure the service is listening to the host’s IP address on the network which should be

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


Host networking is not supported by MacOS. You can use an IP address alias instead or one of the host’s IP addresses.

Option 1: Using an IP address alias

We can use an IP address that does not resolve inside the container to access the host. Unresolved IP addresses are routed to the host for resolving.

First, create an alias:

sudo ifconfig lo0

Make Postgres listen to the address in postgresql.conf:

listen_addresses = 'localhost,'

Allow connections in pg_hba.conf:

host    all             all               trust

Restart PostgreSQL.

Option 2: Using an existing host IP address

Same as above except you don’t have to create an alias as the IP address already exists.

Run ifconfig -a on the host to list all IP addresses. Select one and see the instructions above.

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

# Linux: use the Docker IP or the hosts external IP, see:
  • 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.