How to Make Your Linux Server a Router

Created On: 2016-09-11

To make your linux server a router, you need to have at least two Ethernet cards that are connected to two networks. Let's suppose eth0 connects to the Internet and have a dynamic IP address, eth1 connects to a private network and have a fixed IP of 192.168.2.1/24. In order to make it a router for the private network 192.168.2.0/24, You need to do two things:

  1. enable ipv4 forwarding
    sudo sysctl -w net.ipv4.ip_forward=1
    

    You can add net.ipv4.ip_forward=1 to /etc/sysctl.conf for persist configuration across reboots.

  2. add SNAT rule
    sudo iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j SNAT --to-source 192.168.2.1
    

    In order to make that persist across reboots, you can add the command to /etc/rc.local.

To verify the config is working, you can set default gateway on 192.168.2.0/24 to 192.168.2.1, then run mtr 223.5.5.5 on a client in 192.168.2.0/24. You should notice the first host is 192.168.2.1 and there should be no packet loss.

Is this post helpful?