'network_mode: service:<serviceName> not working correctly

I am trying to configure a docker-compose stack with a container that connects to a VPN, and another container that exposes an HTTP service which is reachable only through that VPN connection. I searched online and found that network_mode: service:<serviceName> setting in docker-compose.yml should do the trick, but it is not working in my environment.

If I start the two containers separately with docker run and --network=container:<containerName> setting, everything works and I can correctly connect to the remote HTTP service with curl localhost:8080

Here is the working configuration with two separate commands:

docker run --rm --name vpn --privileged --hostname vpn --publish 127.0.0.1:8080:80 --device /dev/net/tun --cap-add NET_ADMIN registry.internal.com/vpnclient

docker run --rm --name proxy --network=container:vpn registry.internal.com/proxy

And here is docker-compose.yml that is not working:

version: '3'

services:
  vpn:
    container_name: vpn
    image:  registry.internal.com/vpnclient
    privileged: true
    ports:
      - 8080:80
    devices:
      - /dev/net/tun
    cap_add:
      - NET_ADMIN
    sysctls:
      - net.ipv6.conf.all.disable_ipv6=1
    restart: unless-stopped


  proxy:
    container_name: proxy
    image: registry.internal.com/proxy
    depends_on:
      - vpn
    network_mode: service:vpn
    restart: unless-stopped


Solution 1:[1]

The two versions differ slightly.

In the 'docker run' version you use --name ... and that corresponds to the container_name: ... of the 'docker compose' version.

However, you did also use --hostname ... and that is laking in the docker compose version.

Could it be the case that this 'hostname' is somehow required in the 'proxy' container? (update: I should add that I'm not saying here that making what's running in the container depend on this "hostname" is good practice. In fact, I even feel like it can be a problem in some environments, but I could be wrong too.)

Because not configuring it changes the /etc/hosts file and the response of the hostname command.

Adding a hostname: vpn beneath the container_name: vpn should answer that question.

(There is also the sysctls thing?)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1