Debian/Ubuntu: Multi network/gateway ip routing setup

If you would like to connect your Debian or Ubuntu system to more than one network (e.g. with more than one physical or virtual network device) you could use the following ip routing setup to use a specific gateway for each network.

Create a configuration file in /etc/network/if-up.d/ (like /etc/network/if-up.d/routing) and add one section for each network card (eth0, eth1, …), like:

#!/bin/bash
 
IP=/sbin/ip
 
case "$IFACE" in
  eth0)
    $IP route flush table 10
    $IP route add table 10 to [NETWORK-1]/[MASK-BITS-1] dev eth0
    $IP route add table 10 to default via [GATEWAY-1] dev eth0
    $IP rule add from [NETWORK-1]/[MASK-BITS-1] table 10 priority 10
    $IP route flush cache
    ;;
  eth1)
    $IP route flush table 20
    $IP route add table 20 to [NETWORK-2]/[MASK-BITS-2] dev eth1
    $IP route add table 20 to default via [GATEWAY-2] dev eth1
    $IP rule add from [NETWORK-2]/[MASK-BITS-2] table 20 priority 20
    $IP route flush cache
   ;;
  [...]
esac

After restarting the network service the configuration should be active. If you do not know what mask bits to use, take a look at the ip subnet calculator.

Leave a comment

Your email address will not be published. Required fields are marked *

*