In this post we see how to add a static route in Ubuntu using ip route and netplan.
The ip route command is useful for adding a temporary route. To keep the route configured persistently in Ubuntu 18.04, 20.04, 22.04 and 24.04, we will use netplan.
Temporary route with ip route
To add a temporary route to a specific network through an interface:
sudo ip route add 192.168.12.0/24 dev ens18
With this command we indicate that traffic to the 192.168.12.0/24 network must leave through the ens18 interface.
If the remote network is behind a specific gateway:
sudo ip route add 192.168.12.0/24 via 192.168.1.1
We can also specify both gateway and interface:
sudo ip route add 192.168.12.0/24 via 192.168.1.1 dev ens18
To review the routing table:
ip route show
To check which route the system would use to reach a specific IP address:
ip route get 192.168.12.10
Persistent route with netplan
Netplan stores network configuration in YAML files inside /etc/netplan/. First, check which file exists:
ls -l /etc/netplan/
Example with DHCP on the ens18 interface and a static route to 192.168.12.0/24 using the 192.168.1.1 gateway:
network:
version: 2
renderer: networkd
ethernets:
ens18:
dhcp4: true
routes:
- to: 192.168.12.0/24
via: 192.168.1.1
If we need to define a metric:
network:
version: 2
renderer: networkd
ethernets:
ens18:
dhcp4: true
routes:
- to: 192.168.12.0/24
via: 192.168.1.1
metric: 100
Then validate the configuration:
sudo netplan generate
If there are no errors, test the change with automatic rollback:
sudo netplan try
If everything works, apply it permanently:
sudo netplan apply
Change the default route
To change the default route with netplan, use to: default:
network:
version: 2
renderer: networkd
ethernets:
ens18:
addresses:
- 192.168.1.20/24
routes:
- to: default
via: 192.168.1.1
nameservers:
addresses:
- 1.1.1.1
- 8.8.8.8
On remote servers, it is best to always use netplan try before netplan apply. An incorrect gateway can leave the machine without SSH access.
Quick summary
ip route add: adds temporary routes, useful for testing.netplan: common persistent configuration in Ubuntu 18.04, 20.04, 22.04 and 24.04.netplan generate: validates/generates the configuration.netplan try: tests the change with rollback.netplan apply: applies the change permanently.
