How to add a static route on Ubuntu 18.04 CLI

This is a quick reference guide on how to add a persistent static route on on Ubuntu 18.04

1. Edit yaml file in /etc/netplan

At this point you should already have a netplan yaml file created either for dhcp or a statically assigned interface IP address.

root@VPS2:~# cd /etc/netplan/
root@VPS2:/etc/netplan# ls
network_config.yaml
root@VPS2:/etc/netplan# nano network_config.yaml

2. Define routes in yaml file.

IMPORTANT: It is extremely important to place all the configuration in the correct columns otherwise the configuration will not take. You should be able to copy, edit and paste the configuration example below and this will place the configuration correctly into your file.

The example below shows me pointing all traffic destined for 10.1.1.0/24 to go via 192.168.1.2.

network:
    version: 2
    renderer: networkd
    ethernets:
        eth0:
            addresses:
                - 192.168.1.100/24
            gateway4: 192.168.1.1
            nameservers:
                addresses:
                - 8.8.8.8
                search:
                - mydomain.net
            routes:
                    - to: 10.1.1.0/24
                      via: 192.168.1.2

3. Apply Netplan

root@VPS2:/etc/netplan# netplan apply

3. Check that the route is in the routing table using “route -n”

root@VPS2:/etc/netplan# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

If you are new to the world of Linux, an avid Linux enthusiast or a student why not try our 0.99p per month Linux VPS.

Simply click on the screen shot below to find out more or navigate to https://piggybank.cloud

Thank you for reading and please feel free to leave any feedback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s