I have several gateways and would like to route some traffic out of different gateways based on its destination. I'm guessing I'd need to use a combination of iproute2 and iptables rules, but am not sure where to start.
Can someone provide an example?
You can probably do what you want with
ip route add 126.96.36.199 via 10.0.0.1 dev enp3s8 ip route add 10.0.0.0/24 dev eth0
ip route add shows a single IP address, sent out a given ethernet interface (ep3s8) to the next hop router, 10.0.0.1
The second route is for a whole network, 10.x.y.z, sent out a given ethernet card, eth0. That's the "local network", which doesn't have a next hop router, it's all on the same logical wire.
You want to read
man ip-route before doing anything, though. Also, be prepared to have to reboot, and do not do this remotely. You can very easily create incorrect routes that terminate your remote access. I am the voice of experience in this last recommendation.
What you are asking about is
policy-based routing or
source-based routing. There is an excellent introduction by David Schwartz on this very same site.
I would like to point out that there is also a neat little program, which can be found here, that allows you to bind specific applications to a given interface. This is of course easy with apps like openssh which have options to bind to the desired listening address. But this library allows you to bind even applications without such options (like Firefox) to a given IP address.
In this way, you can choose whether you wish to provide separate routing tables for all applications, or override those same specifications on a per-application basis.
A good place to read about source base routing is Linux Advanced Routing & Traffic Control.
You can also read manuals from the command line:
man ip rule man ip route
Note: on some systems, you may need to do
man ip-rule and
Or you can read them online: rule and route.
Warning: the online versions might not be identical
to the versions on your system.
In general, you should add a rule. I specified an interface in my example (eth1). This is optional and can be omitted.
# ip rule add dev eth1 to 188.8.131.52 table 2 priority 20000
dev eth1– device that will be used to send packets
to 184.108.40.206– the destination
table 2– table where you should add your routes
priority 20000– priority of rule
You can see your rule by running this command:
# ip ru sh 0: from all lookup local 20000: from all to 220.127.116.11 iif eth1 lookup 2 32766: from all lookup main 32767: from all lookup default
Next, you should add routes, specifying the table in which they will be added. In this case it would be table 2.
# ip route add table 2 via 18.104.22.168 default
In order to see your routes, you should run:
# ip route show ta 2