Had to setup some simple policy-based routing on CentOS again recently, and had forgotten the exact steps. So here's the simplest recipe for CentOS that seems to work. This assumes you have two upstream gateways (gw1 and gw2), and that your default route is gw1, so all you're trying to do is have packets that come in on gw2 go back out gw2.
1) Define an extra routing table e.g.
$ cat /etc/iproute2/rt_tables # # reserved values # 255 local 254 main 253 default 0 unspec # # local tables # 102 gw2 #
2) Add a default route via gw2 (here 172.16.2.254) to table gw2 on the
appropriate interface (here
$ cat /etc/sysconfig/network-scripts/route-eth1 default table gw2 via 172.16.2.254
3) Add an
ifup-local script to add a rule to use table gw2 for
eth1 packets e.g.
$ cat /etc/sysconfig/network-scripts/ifup-local #!/bin/bash # # Script to add/delete routing rules for gw2 devices # GW2_DEVICE=eth1 GW2_LOCAL_ADDR=172.16.2.1 if [ $(basename $0) = ifdown-local ]; then OP=del else OP=add fi if [ "$1" = "$GW2_DEVICE" ]; then ip rule $OP from $GW2_LOCAL_ADDR table gw2 fi
4) Use the
ifup-local script also as
ifdown-local, to remove that rule
$ cd /etc/sysconfig/network-scripts $ ln -s ifup-local ifdown-local
5) Restart networking, and you're done!
# service network restart
For more, see: