docker-compose snippets

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

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

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

  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"
      - 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

# 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.


How to set the environment variables in a cron script (Docker)

Tagged cron, docker, env, crontab, environment, docker-compose  Languages bash

To give your cron script access to the same environment variables as the Docker container, you can read and export the environment variables for the PID 1 process in your script:

crontab -l
* * * * * /app/


#!/usr/bin/env bash
# Read the environment variables for the main process (PID 1) running in the Docker container:
export $(xargs -0 -a "/proc/1/environ")

python3 -m $1