Ubuntu 20.04 manage routing of multiple gateways and interfaces from a single VM
With the advent of netplan it is possible to manage the routing for each network interface in a simple way.
For example, if we have a VM connected to two separate LANs with two network cards and obviously two gateways we have to manage the routing of packets, because Linux is known to route everything to the default gateway.
To overcome this problem, it is sufficient to modify the netplan configuration.
Let’s see how to do it with a few simple steps:
- have iproute2 installed
1 |
apt install iproute2 |
2. modify the “sudo nano / etc / iproute2 / rt_tables” file by inserting the last two lines with numbers that define the priorities
1 |
sudo nano /etc/iproute2/rt_tables |
insert as last two lines:
1 2 |
800 800 801 801 |
3) modify the conf. of netplan for interfaces:
1 |
nano /etc/netplan/<your netplan con file>.yaml |
Each interface has a settings block in this file. At the end of this block, we will add policy settings and routing rules for the interface.
We configure the first network interface which has the following parameters (let’s say it is connected with lan1):
- name: enp0s5
- ip address: 10.10.0.20
- network: 10.10.0.0/24
- gateway: 10.10.0.1
- macaddress: 54: 45: 42: 51: 12: 09
Configuriamo la seconda interfaccia di rete che ha i seguenti parametri (diciamo che è connessa con la lan2):
- nome: enp1s6
- ip address: 192.168.10.30
- network: 192.168.10.0/24
- gateway: 192.168.10.1
- macaddress: 56:55:46:51:12:09
( per ottenere il mac address delle interfacce è sufficiente eseguire “ifconfig -a” )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
network: version: 2 ethernets: enp0s5: addresses: - 10.10.0.20/24 match: macaddress: 54:45:42:51:12:09 mtu: 1500 nameservers: addresses: - 8.8.8.8 - 1.1.1.1 - 8.8.4.4 search: [] set-name: enp0s5 routes: - to: 0.0.0.0/0 via: 10.10.0.1 table: 801 routing-policy: - from: 10.10.0.20 table: 801 priority: 200 enp1s6: addresses: - 192.168.10.30/24 gateway4: 192.168.10.1 match: macaddress: 56:55:46:51:12:09 mtu: 1500 nameservers: addresses: - 8.8.8.8 - 1.1.1.1 - 8.8.4.4 search: [] set-name: enp1s6 routes: - to: 0.0.0.0/0 via: 192.168.10.1 table: 800 routing-policy: - from: 10.10.0.20 table: 800 priority: 300 version 2 |
The same operation must be performed for all interfaces connected to the various LANs of your infrastructure. Obviously if you have more than two you will need to add more lines to the rt_tables file.