Set routing on HOST after running docker-compose

My problem

I have set of docker containers, that are started with docker-compose - there is even a definition of a private subnet in docker-compose.yml.

However, some containers here are used as an actual routers - they have a wireguard, which is used for connecting remote devices, and their directly-connected subnets, into the host machine, and it’s own directly-connected networks.

version: '3'

services:

...

  vpn-gw:
    image: sdr-li-vpn-gw:latest
    container_name: vpn-gw
    restart: always
    environment:
      - <REDACTED>
    volumes:
      - <REDACTED>
    cap_add:
      - NET_ADMIN
    networks:
      net_0:
        ipv4_address: 10.123.9.18

...

networks:
  net_0:
    enable_ipv6: false
    ipam:
      driver: default
      config:
        - subnet: 10.123.9.16/28
    driver_opts:
      com.docker.network.bridge.name: br_infranet

So after running docker-compose up, one has to call for example ip route add 10.21.37.0/24 via 10.123.9.18. In this example, where 10.123.9.18 is wireguard server’s container’s IP within docker network, and 10.21.37.0/24 is remote network, directly connected to one of the wireguard server’s peers.

Docker doesn’t have an ability to create a custom route on HOST after creating some network/running docker-compose up. I can’t run ip route add ... at the boot, since there is no docker networks alive at such early stage…

So what? Use dirty scripts along the “docker-compose up”?

Solution

Create a file in /etc/systemd/network/, for example called /etc/systemd/network/1-br-infranet.network. There can be defined the network, that is also defined inside docker-compose.yml file, along with the required routes (more entries can be defined!). By that, routes can be defined EVEN, when docker haven’t created a network yet.

[Match]
Name=br_infranet

[Network]
Address=10.123.9.17/28

[Route]
Destination=10.21.37.0/24
Gateway=10.123.9.18

Isn’t there solution by Docker

Nope. I asked ChatGPT, then Chatbot from Docker Reference. And in my case, I can’t use Kubernetes or other heavy solutions, since I run the infra on low-specs VPS. Inb4, no - using better VPS is not a solution since I want to have a small and compact solutions, instead of using a cannon to kill a fly.