How to add static route with netplan on Ubuntu 20.04 Focal Fossa Linux

In this tutorial you will learn how to permanently add a static route on Ubuntu 20.04 Focal Fossa Linux using netplan.

In this tutorial you will learn:

  • How to add permanent static route
  • How to apply new netplan configuration
  • How to check static routes from command line

How to add static route with netplan on Ubuntu 20.04 Focal Fossa Linux

How to add static route with netplan on Ubuntu 20.04 Focal Fossa Linux

Software Requirements and Conventions Used

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Installed Ubuntu 20.04 or upgraded Ubuntu 20.04 Focal Fossa
Software N/A
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

How to add static route with netplan on Ubuntu 20.04 step by step instructions

  1. First step is to open the main netplan configuration file using administrative privileges:
    $ sudoedit /etc/netplan/50-cloud-init.yaml
    


  2. Find the configuration stanza related to the network interface to which you wish to add the static route. In this example we will add the the static route to the destination network subnet 172.16.0.0/24 via the network gateway 192.168.1.100 on the interface enp0s3.Example:
    # This file is generated from information provided by
    # the datasource.  Changes to it will not persist across an instance.
    # To disable cloud-init's network configuration capabilities, write a file
    # /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
    # network: {config: disabled}
    network:
        ethernets:
            enp0s3:
                dhcp4: false
                addresses: [192.168.1.202/24]
                gateway4: 192.168.1.1
                nameservers:
                  addresses: [8.8.8.8,8.8.4.4,192.168.1.1]
                routes:
                - to: 172.16.0.0/24
                  via: 192.168.1.100
        version: 2
    
  3. Once you made all required changes to add the static route all the new netplan configuration using the bellow command:
    $ sudo netplan apply
    
  4. Check all static routes available on your Ubuntu system:
    $ ip route s
    default via 192.168.1.1 dev enp0s3 proto static 
    172.16.0.0/24 via 192.168.1.100 dev enp0s3 proto static 
    192.168.1.0/24 dev enp0s3 proto kernel scope link src 192.168.1.202