In a project there are three services in the docker compose yml:
A VPN.
A container (named first
) connected to that VPN using network_mode.
A container (named second
) not connected to that VPN.
From first
I can get second
's IP using the container name (second), but the oposite does not work.
"first" and "second" are simple python scripts sending data to each other using socket.
I can send data from "second" to "first" if I use the IP address instead of the container name, but that is not a solution I can use in the project.
This is the .yml I'm using:
version: '3.9'
services:
vpn:
build: ./vpn
container_name: vpn
env_file:
- ss.env
cap_add:
- NET_ADMIN
- NET_RAW
devices:
- /dev/net/tun:/dev/net/tun
dns:
- 1.1.1.1
first:
build: ./first
container_name: first
depends_on:
- vpn
network_mode: service:vpn
second:
build: ./second
container_name: second
depends_on:
- vpn
The relevant part of the python scripts:
#first.py
client.sendto(bytes('message from second',encoding='utf8'), ('second', 37021))
#second.py
client.sendto(bytes('message from second',encoding='utf8'), ('first', 37020))
Also, the vpn log:
vpn | 2021-10-20 00:44:21 TUN/TAP device tun0 opened
vpn | 2021-10-20 00:44:21 /sbin/ip link set dev tun0 up mtu 1500
vpn | 2021-10-20 00:44:21 /sbin/ip link set dev tun0 up
vpn | 2021-10-20 00:44:21 /sbin/ip addr add dev tun0 10.8.8.2/24
vpn | 2021-10-20 00:44:21 /sbin/ip route add 104.111.100.109/32 via 192.168.144.1
vpn | 2021-10-20 00:44:21 /sbin/ip route add 0.0.0.0/1 via 10.8.8.1
vpn | 2021-10-20 00:44:21 /sbin/ip route add 128.0.0.0/1 via 10.8.8.1
CodePudding user response:
Your problems come from a misconfiguration of the networks.
First of all, when you're starting services with docker-compose up -d
you're creating a default network with the name of the folder where that Compose file is located. You can check that with docker network ls
.
Well, all your services will connect by default to that network, except if you define a different default or you change the network mode, as it's your case for first
.
Basically, let's suppose you have your Compose file under a directory called myapp
.
- When you start your containers, Docker Compose is creating a network with the name
myapp-default
. - Your services
vpn
andsecond
will join that network, butfirst
will work with the network stack fromvpn
. - Since
first
is using the same network namespace ofvpn
, it can discoversecond
without any problem using the service name. - Since
first
isn't in thedefault
network,second
cannot discover it.
If you want first
to be discoverable by second
you shouldn't use the same network stack of vpn
but just let it join the default
network created by Compose (or create another network by yourself and make the three of them to join that network).