Search code examples
dockerdocker-composedocker-network

Docker-compose "ports": listen on multiple IP addresses / IP range


Instead of listening to a single IP address like e.g. localhost:

ports:
- "127.0.0.1:80:80"

I want the container to only listen to a local network, i.e. e.g.:

ports:
- "10.0.0.0/16:80:80"

ERROR: The Compose file './docker-compose.yml' is invalid because:
services.SERVICE.ports contains an invalid type, it should be a number, or an object

Is this possible?

I don't want to use things like swarm mode etc., yet.


If IP range is not supported, maybe at least multiple IP addresses like 10.0.0.2 and 10.0.0.3?

ERROR: for CONTAINER  Cannot start service SERVICE: driver failed programming external connectivity on endpoint CONTAINER (...): Error starting userland proxy: listen tcp 10.0.0.3:80: bind: cannot assign requested address

ERROR: for SERVICE  Cannot start service SERVICE: driver failed programming external connectivity on endpoint CONTAINER (...): Error starting userland proxy: listen tcp 10.0.0.3:80: bind: cannot assign requested address

Or is it not even supported to listen to 10.0.0.3 ?

The host machine is connected to 10.0.0.0/16:

> ifconfig
ens10: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1450
        inet 10.0.0.2  netmask 255.255.255.255  broadcast 10.0.0.2
        inet6 f**0::8**0:ff:f**9:b**7  prefixlen 64  scopeid 0x20<link>
        ether **:00:00:**:**:**  txqueuelen 1000  (Ethernet)

Solution

  • Listening to a single IP address seems not correct. The service is listening at an IP address.

    Let's say your VM has two network interfaces (ethernet cards):

    Network 1 → subnet: 10.0.0.0/24 and IP 10.0.0.100
    Network 2 → subnet: 10.0.1.0/24 and IP 10.0.1.200

    • If you set 127.0.0.1:80:80 that means that your service listening at 127.0.0.1's (localhost) port 80.
    • If you want to access service from 10.0.0.0/24 subnet you should set 10.0.0.100:80:80 and use http://10.0.0.100:80 address to be able connect your container from external hosts

    If you want to access service from multiple networks simultaneously you can bind the container port to multiple ports, where the IP is the connection source IP):

    ports:
      - 10.0.0.100:80:80
      - 10.0.1.200:80:80
      - 127.0.0.1:80:80
    

    And don't forget to open 80 port at VM's firewall, if a firewall exists and restricts that network