Search code examples
dockerdocker-composetraefik

Traefik as a proxy for Docker container with host machines network


I would like to set up the following scenario:

  • One physical machine with Docker containers
  • traefik in a container with network backend
  • another container which is using the host machines network (network_mode: host)

Traefik successfully finds the container and adds it with the IP address 127.0.0.1 which obviously not accessible from the traefik container (different network/bridge).

docker-compose.yml:

version: '3'
services:
    traefik:
        image: traefik
        ports:
            - "80:80"
            - "443:443"
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
            - ./traefik.toml:/etc/traefik/traefik.toml
        networks:
            - backend
     app:
         image: my_app
         labels:
             - "traefik.enable=true"
             - "traefik.frontend.rule=Host:myapp.example"
             - "traefik.port=8080"
         network_mode: host
networks:
    backend:
        driver: bridge

The app container is added with

Server      URL                     Weight 
server-app  http://127.0.0.1:8080   0
Load Balancer: wrr

Of course I can access app with http://127.0.0.1:8080 on the host machine or with http://$HOST_IP:8080 from the traefik container.

Can I somehow convince traefik to use another IP for the container?

Thanks!


Solution

  • Without a common docker network, traefik won't be able to route to your container. Since you're using host networking, you could access it directly. Or if you need to only access it through the proxy, then place it on the backend network. If you need some ports published on the host and others proxied through traefik, then place it on the backend network and publish the ports you need to publish, rather than using the host network directly.

    With recent versions of traefik and docker, it is possible to have the proxy connect back to the docker host for ports. You need to define the host.docker.internal hostname on Linux using (this should be provided automatically on Docker Desktop environments):

        traefik:
            image: traefik
            ports:
                - "80:80"
                - "443:443"
            volumes:
                - /var/run/docker.sock:/var/run/docker.sock
                - ./traefik.toml:/etc/traefik/traefik.toml
            networks:
                - backend
            extra_hosts:
                - "host.docker.internal:host-gateway"