Binding a port to a specific network in Docker Compose

1.1k views Asked by At

I run pihole on my RPi behind nginx reverse proxy, along with several other proxied containers. I want to:

  • map the port 80 of the pihole container to an internal-only network (that nginx proxies to public port 80)
  • map the port 53 (DNS) to the default network (so that it's publicly available).

By default all ports are published on all networks the container is part of, which I'm trying to avoid. In essence I'd like to do this:

version: '3'

services:
  pihole:
    container_name: pihole
    hostname: pihole
    image: pihole/pihole:latest
    networks:
      - default
      - intraonly
    ports:
      - default:53:53/tcp
      - default:53:53/udp
      - intraonly:80/tcp
      - intraonly:443/tcp

[...nginx & other services definitions follow...]

networks:
  intraonly:
    driver: bridge
    internal: true

The above obviously fails, because the documentation says clearly it expects an IP address only in the port definition:

Specify the host IP address to bind to AND both ports (the default is 0.0.0.0, meaning all interfaces): (IPADDR:HOSTPORT:CONTAINERPORT).

That seems crazy however, as the IP address changes every time I rebuild the container. In other places the documentation suggests to avoid addressing other containers by IP address and chose the symbolic service names (published by DNS) instead.

What am I missing? What is the right/robust way to expose a port on a specific interface without hardcoding IP address? (I'm aware I could achieve internal-only ports by using expose syntax), but the question of binding ports to specific custom networks still stands.)

0

There are 0 answers