Add IP Routes and Rules at Startup

20,945

Solution 1

You can do this using /etc/network/interfaces file only.

You just have to put your add route command under the desired interface and put post-up or pre-down keywords before that command.

post-up keyword will add that route in the routing table after you will have brought up that interface and pre-down keyword will remove it before you will have brought down that interface.

For example:
To add static route on eth0 interface, /etc/network/interfaces file should be

auto eth0
iface eth0 inet static
    ...
    ...
    post-up ip route replace default via 192.168.0.1
    pre-down ip route delete default via 192.168.0.1 || true

Solution 2

Put your commands in a shell script e.g. /usr/local/sbin/myrouting and make it executable.

You could use cron and an @reboot target in /etc/crontab or the root crontab e.g. /etc/crontab

@reboot root /usr/local/sbin/myrouting

or root crontab

@reboot /usr/local/sbin/myrouting 

You could also do it using systemd.

Create a systemd unit file /etc/systemd/system/myrouting.service

[Unit]
after=network

[Service]
ExecStart=/usr/local/sbin/myrouting

[Install]
WantedBy=default.target

Then enable it

systemctl enable myrouying.service
Created symlink /etc/systemd/system/default.target.wants/myrouting.service → /etc/systemd/system/myrouting.service.
Share:
20,945
Zaden
Author by

Zaden

Updated on September 18, 2022

Comments

  • Zaden
    Zaden over 1 year

    I’m currently routing some marked packets via eth0. However, I have to apply the routing rules every time the system reboots. The two commands I always have to re enter are

    ip rule add fwmark 3 table 3
    ip route add default via 192.168.0.1 table 3
    

    The gateway for eth0 being 192.168.0.1 I’ve tried placing those commands in both /etc/rc.local and /etc/network/interfaces, and in both cases I have still had to run them manually. Does anyone have a suggestion as to where/how to run these commands on every startup?

  • Zaden
    Zaden over 6 years
    Turned out that OpenVPN was messing with commands I placed in there, so I kept the marking rule in the interfaces file, but moved the route adding to a file that runs on OpenVPN start up. Marking this as correct, since if it weren't for OpenVPN it would've worked.