Something very common when managing servers is redirecting traffic.
Suppose we have a server with certain services running, but for whatever reason we change one of those services (I don't know, for example pop3 which is port 110) to another server. The normal and most frequent thing would be to simply change the IP in the DNS record, however if someone was using the IP instead of the subdomain it will be affected.
What to do? ... simple, redirect the traffic that server receives through that port to another server with the same port.
How do we start redirecting traffic?
The first thing is that we must have enabled the forwarding on the server, for this we will put the following:
echo "1" > /proc/sys/net/ipv4/ip_forward
You can also use this other command, in case the previous one doesn't work for you (it happened to me like this on a CentOS):
Then we will restart the network:
service networking restart
In RPM distros like CentOS and others, it would be:
service nertwork restart
Now we will move on to the important thing, tell the server through iptables what to redirect:
iptables -t nat -A PREROUTING -p tcp --dport <puerto receptor> -j DNAT --to-destination <ip final>:<puerto de ip final>
That is, and following the example I mentioned, suppose we want to redirect all the traffic that our server receives through port 110 to another server (not: 10.10.0.2), which will still receive that traffic through 110 (it is the same service):
iptables -t nat -A PREROUTING -p tcp --dport 110 -j DNAT --to-destination 10.10.0.2:110
The 10.10.0.2 server will see that all the packets or requests come from the client's IP, in case they want to swim the requests, that is, that the 2nd server sees that the requests arrive with the IP of the 1st server (and in the which we apply the redirection), it would also be to put this second line:
iptables -t nat -A POSTROUTING -j MASQUERADE
Some questions and answers
In the example I used the same port both times (110), however they can redirect traffic from one port to another without problems. For example, suppose I want to redirect traffic from port 80 to 443 on another server, for this it would be:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.10.0.2:443
This is iptables, they can use all the other parameters that we know, for example, if we only want to redirect traffic from a specific IP, it would be by adding -s … For example I will redirect only the traffic that comes from 10.10.0.51:
iptables -t nat -A PREROUTING -p tcp -s 10.10.0.51 --dport 80 -j DNAT --to-destination 10.10.0.2:443
Or an entire network (/ 24):
iptables -t nat -A PREROUTING -p tcp -s 10.10.0.0/24 --dport 80 -j DNAT --to-destination 10.10.0.2:443
We can also specify the network interface with -i :
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 80 -j DNAT --to-destination 10.10.0.2:443
This as I said already, is iptables, you can apply what is already known so that the server does exactly what you want it to do 😉