How to set default route with netplan, Ubuntu 18.04 server, 2 NIC

The issue is that networkd will bring up both networks, and both will have a default gateway set, and both will be at the same metric.

Netplan does not currently allow you to skip setting the route on one interface, but you can configure networkd separately to tell it to do this, by basing the config on what netplan has already generated.

I have copied the commands below. Here I am assuming that ens19 is the "secondary" interface for which you do not want a default gateway set -- note that to do this successfully, it also needs to happen before rebooting with the new interface (or you can copy part of the config, omit the MACAddress= line, etc. so that it's generic enough that a new interface will be matched).

sudo cp /run/systemd/network/10-netplan-ens19.network /etc/systemd/network
sudo vi /etc/systemd/network/10-netplan-ens19.network

Then add under [DHCP]:

UseRoutes=false            # if you don't want to apply any routes from DHCP

RouteMetric=200        # any number above 100 if you want the routes applied, but that they are less preferred.

If you don't have the file yet (ie. you have not attached the interface yet) then you could copy the contents of another interface set for DHCP, and remove MACAddress=.

In general, the file should look something like this:

[Match]
Name=interfacename

[Network]
DHCP=ipv4

[DHCP]
UseMTU=true
RouteMetric=200    # or UseRoutes=false, as you prefer.

For static interfaces just skipping gateway4 (or gateway6) config option causes netplan to NOT create default route for that interface. Then, if you need extra routing using routes element (array of dicts)

For DHCP interfaces you can do:

dhcp4-overrides:
    route-metric: 100

Just increase metric for subsequent interfaces and you should be good.

(See: https://netplan.io/examples)


To stop a dhcp interface in netplan from setting a default route, just set use-routes in dhcp4-overrides to false.

eth2:
    dhcp4: true
    dhcp4-overrides:
        use-routes: false

Also it may be better to not edit /etc/netplan/50-cloud-init.yaml directly but instead:

  • Change the source into /etc/cloud/cloud.cfg.d/50-curtin-networking.cfg.
  • Run cloud-init clean -r to reboot. (this propagates the changes in the cloud config to the netplan config)