Search code examples
dockerdocker-composedocker-networkms-yarp

How can I access (forward) the public HTTP request IP address inside a docker compose network?


With the following setup:

enter image description here

only the YARP container has published ports. It correctly sets the X-Forward* headers for other containers to use. But unfortunately it's the docker compose gateway address.

When I want to log the (public) client's IP address, I get ::ffff:172.18.0.1 which is the docker compose gateway IP address. Somehow I need to tell docker to put the public IP address in the X-Forward-For header which then will be used by my reverse proxy.

My containers run inside their own network:

services:
  yarp:
    ...
    networks:
      - mynet

I can see the created network:

$ docker network ls
NETWORK ID     NAME                                      DRIVER    SCOPE
2bf19f507987   dockercompose1502733..._mynet             bridge    local

and to see the details:

$ docker network inspect 2bf
[
  {
    "Name": "dockercompose1502733..._mynet",
    "Id": "2bf...",
    "Created": "...",
    "Scope": "local",
    "Driver": "bridge",
    "EnableIPv6": false,
    "IPAM": {
      "Driver": "default",
      "Options": null,
      "Config": [
        {
          "Subnet": "172.18.0.0/16",
          "Gateway": "172.18.0.1" // this is the address I get for public requests
        }
      ]
    },
    "Internal": false,
    "Attachable": true,
    "Ingress": false,
    "ConfigFrom": {
      "Network": ""
    },
    "ConfigOnly": false,
    "Containers": {
      "b82645911...": {
        "Name": "YARP",
        "EndpointID": "fb1b...",
        "MacAddress": "02:42:ac:...",
        "IPv4Address": "172.18.0.10/16",
        "IPv6Address": ""
      },
      ...
    },
    "Options": {},
    "Labels": {
      "com.docker.compose.network": "mynet",
      "com.docker.compose.project": "dockercompose1502733...",
      "com.docker.compose.version": "1.29.2"
    }
  }
]

Solution

  • You could do network_mode: host for the reverse proxy service: https://docs.docker.com/compose/compose-file/#network_mode

    Be mindful though, because:

    host: which gives the container raw access to host’s network interface

    It looks like this is your only solution: https://github.com/docker/roadmap/issues/157

    I assume this is a production workload, you might be better off migrating to kubernetes where you certainly will face other set of problems :) but this one is not a problem at least with ingress-nginx I was able to configure it.