How to make Ubuntu as router for external traffic

Due to limitations in public IPs you cant give all your hosts the publicly route-able IPs. but on otherside you want to install packages etc on those private host . One way is to enable a Public IP with a Host (we called it as gateway host) which has two network card , One network card has public ip and other with private one.

Now you want to route all hosts in private network to route their public traffic via that (gateway) host .

On Gateway host do this:

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

## eth1 in above where you have public ip can be any interface

iptables -A FORWARD -i eth2 -j ACCEPT

## eth2 in above where you have private ip can be any interface

On Private hosts:

route del default gw

## is our gateway’s private ip you can check with yours what is the private ip you have on gateway

## by running ifconfig eth2 ## replace eth2 with interface you have private ip on gateway