Describes how to forward (that is, port forwarding) the "host name: port number" of one web server to "another host: port number" on Linux. To realize this, use "iptables" that is installed as standard on CentOS and Ubuntu. The content introduced this time can probably be realized with firewalld etc. which is included by default in CentOS 7 or later, but as a result of searching for a method of port forwarding that does not depend on the environment as much as possible, I decided to use iptables. There are some articles that introduce port forwarding methods with iptables, but even if I tried those methods obediently, it did not work, and I was quite addicted to the realization, so I will summarize it again in this article. Only the http (https) protocol has been confirmed to work this time, but if it is TCP communication, it should work with other protocols (ssh, ftp, etc.).
23.45.67.89
, and the port is 80
. 192.168.1.4
http://192.168.1.4:10080
to the transfer source server, the transfer source server port-forwards to the web server and http://23.45.67.89:80
Request to the site.Execute the following command on the transfer source server
--dport
: Destination port number before conversion --to-destination
: Converted "destination IP: port number"$ sudo iptables -t nat -A PREROUTING -p tcp \
--dport 10080 -j DNAT \
--to-destination 23.45.67.89:80
--d
: Translated IP address --dport
: Destination port number after conversion -j MASQUERADE
: Perform IP masquerade$ sudo iptables -t nat -A POSTROUTING -p tcp \
-d 23.45.67.89 --dport 80 \
-j MASQUERADE
A description required to allow the passage of packets sent from the client.
In the case of TCP communication, two-way communication is performed by a method called 3way-handshake, so it is necessary to make settings to allow both communications.
Reference site: Firewall made with Linux [Packet filtering settings]
The command to allow packets to pass to "client → web server" is as follows
$ sudo iptables -A FORWARD -p tcp \
-d 23.45.67.89 --dport 80 \
-j ACCEPT
-s
: source address" and "" --sport``: source port number. Note$ sudo iptables -A FORWARD -p tcp \
! --syn -m state --state ESTABLISHED \
-s 23.45.67.89 --sport 80 \
-j ACCEPT
$ sudo iptables -t nat -A OUTPUT -p tcp \
--dport 10080 -j DNAT \
--to-destination 23.45.67.89:80
Recommended Posts