Why Change the Default Gateway?
The default gateway is the IP address of the router that your Linux system sends packets to when it doesn’t explicitly know the route to the destination (like when accessing the internet). If you install a new core router, change ISPs, or add a secondary VPN connection, you may need to manually update your server’s routing table to ensure traffic exits through the correct interface.
Step 1: View the Current Routing Table
Before making any changes, you should inspect the current routing configuration. Open your terminal and run the modern ip route command (which replaces the deprecated route and netstat -r commands):
ip route show
Look for the line that begins with the word default. It will look something like this:
default via 192.168.1.1 dev eth0 proto static metric 100
In this example, 192.168.1.1 is the current default gateway.
Step 2: Delete the Existing Default Route
To avoid routing conflicts or creating multiple default routes with the same metric, it is best practice to delete the old route before adding the new one. Run the following command with root privileges:
sudo ip route del default
If you run ip route show again, the “default via” line will be completely gone, and your server will immediately lose internet access.
Step 3: Add the New Default Gateway
Now, add the new default gateway. Let’s assume your new router’s IP address is 192.168.1.254, and it is physically connected to the eth0 interface. Use the add flag:
sudo ip route add default via 192.168.1.254 dev eth0
Test the new route by pinging a public IP address (like Google’s DNS):
ping 8.8.8.8 -c 4
Step 4: Make the Change Persistent (Ubuntu/Debian)
The ip route command modifies the kernel’s routing table in RAM. If you reboot the server, these changes will be lost. You must update your network configuration files.
On modern Ubuntu systems using Netplan, open the YAML file located in /etc/netplan/ (e.g., 01-netcfg.yaml):
sudo nano /etc/netplan/01-netcfg.yaml
Update the gateway4 directive (or routes: - to: default via: 192.168.1.254 in newer Netplan versions). Save the file and apply it:
sudo netplan apply
Step 5: Make the Change Persistent (RHEL/CentOS)
On Red Hat-based systems using NetworkManager, it is easiest to use the nmcli tool to update the connection profile permanently:
sudo nmcli connection modify "System eth0" ipv4.gateway 192.168.1.254
Bring the interface down and back up to apply the permanent configuration:
sudo nmcli connection up "System eth0"
Your Linux server will now permanently route unknown traffic through the new gateway.