Adding persistant static routes in linux

Let’s say that you have a box that lives on subnet 172.16.16.0 /24. Your default route is set in /etc/sysconfig/network as 172.16.16.1, as shown below:

NETWORKING=yes
HOSTNAME=testbox.domain.com
GATEWAY=172.16.16.1

Now you need to get to network 1.2.3.0 /24 using gateway 172.16.16.250 and network 45.67.89.0 /24 using gateway 172.16.16.254. One option is to add those routes manually with the following commands:

SYNTAX
# route add [-net|-host] netmask gw dev X

EXAMPLES
route add -net 1.2.3.0 netmask 255.255.255.0 gw 172.16.16.250
route add -net 45.67.89.0 netmask 255.255.255.0 gw 172.16.16.254

This will work in the short term, and can be doublechecked using the ‘route’ command – sample output shown below:

Destination Gateway Genmask Flags Metric Ref Use Iface
172.16.16.0 * 255.255.255.0 U 0 0 0 eth0
1.2.3.0 172.16.16.250 255.255.255.0 UG 0 0 0 eth0
45.67.89.0 172.16.16.254 255.255.255.0 UG 0 0 0 eth0
default 172.16.16.1 0.0.0.0 UG 0 0 0 eth0

NOTE: once the machine is rebooted, those statis routes will disappear, as they are stored in memory and are not recreated on startup.

To add a persistent static route in Redhat Enterprise Linux or CentOS, create a file called route-X in the /etc/sysconfig/network-scripts/ directory where is the interface number and X is the interface number. As you would expect, these are specified in separate files for each of the available interfaces.

In this particular case, we will be creating a file called ‘route-eth0’ in /etc/sysconfig/network-scripts in order to make those routes persistent through reboot, and populating it with the information shown below

vi /etc/sysconfig/network-scripts/route-eth0
1.2.3.0/24 via 172.16.16.250
45.67.89.0/24 via 172.16.16.254

Once that file has been modified, run the following command to restart the network:

service network restart

After that, run the route command and make sure that your routes are in place.

Leave a Reply

Your email address will not be published. Required fields are marked *