How can I forward the external packet to the different port of the other host with iptable?

Hello. I am a total newbie to iptables and configuring a firewall host to protect my Redis storage. What I want is hiding the actual Redis storage behind the firewall which provides a proxy mapping between one of its ports and the Redis port, 6397.

Each of firewall host and Redis host has two network devices, eth0 for the public network and eth1 for the private network, and can communicate with each other via the private network (i.e., eth1). In short, what I want is:

(external client) <—[eth0]—> (firewall host:4515) <—[eth1]—> (Redis host:6397)

I succeeded to configure following settings, which maps the same port between the firewall and the Redis storage, with the commands from this guide. But since this setting infers that the Redis storage is behind the firewall, I have to make some changes.

(external client) <—[eth0]—> (firewall host:6397) <—[eth1]—> (Redis host:6397)

This is the command I used:

sudo iptables -A FORWARD -i eth0 -o eth1 -p tcp --syn --dport 6379 -m conntrack --ctstate NEW -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o eth1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A FORWARD -i eth1 -o eth0 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 6379 -j DNAT --to-destination {redis-storage-private-ip}
sudo iptables -t nat -A POSTROUTING -o eth1 -p tcp --dport 6379 -d {redis-storage-private-ip} -j SNAT --to-source {firewall-private-ip}

So: How can I modify above commands to map the different ports between the firewall and the Redis storage?

Thanks in advance. Any answers are appreciated.


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Looking at the examples here, it looks like using the --toport flag should be added to map to receiving port to something other than the 6397 that Redis is using behind your firewall.