Changing default route in a Docker container

I use typically macvlan-based network driver for my containers in order to have an experience close to VM on my home network, and rely on docker-compose for their instanciation.

In that particular case I was doing the following configuration in my docker-compose.yml:

networks:
  backend:
  physical:
     external: true

The network ‘physical’ is defining my layer 2 ethernet home network, while ‘backend’ defines a classical docker bridge without any special consideration for the supporting database, appcode etc.

However, at the instanciation, the backend network is inheritating the default route of the docker bridge (i.e. ‘172.20.21.124’), leading to some network confusion when an external host was consulting a resource through the nginx proxy I have instanciated between the macvlan and the backend networks.

The workaround (without giving more network admin rights within the container) is to change the routing from the host itself. This could be done with the following snippet from this stackoverflow answer:

pid=$(sudo docker inspect -f '{{.State.Pid}}' mycontainername)
sudo mkdir -p /var/run/netns
sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid
sudo ip netns exec $pid ip route del default 
sudo ip netns exec $pid ip route add default via 192.168.1.1

The original author is linking it to a docker event change through an awk pipe, however I did not find anything about docker events hooking in docker-compose YAML, except similar ideas already pushed on their Github repo.