In the routine operation of cloud servers, migrating data from an old server to a new one is an inevitable part of system administration. During the migration process, as domain name resolution takes time to become effective, it's common for some traffic to still be directed to the old server, leading to data continuity issues. iptables is a widely used traffic control software on Linux operating systems. By utilizing iptables on the old server, we can forward the traffic to the new server, effectively addressing the data discrepancies caused by the migration.
This article uses a CentOS 6 server as an example to illustrate how to use iptables for traffic forwarding. The following method supports both 32-bit and 64-bit versions of CentOS. Before proceeding, ensure that iptables is successfully installed. If iptables is not installed, use the following command to install it.
yum install iptables -y
To enable traffic forwarding on a CentOS system, a Linux kernel parameter needs to be modified. Edit the /etc/sysctl.conf file and set the following parameter to 1.
net.ipv4.ip_forward = 1
After saving, execute the following command to reload the kernel parameters.
sysctl -p
Create forwarding rules:
iptables -A FORWARD -d 2.2.2.2 -i venet0 -p tcp -m tcp --dport 80:90 -j ACCEPT
Note: Replace 2.2.2.2 with the new server's IP, replace venet0 with the network interface name, and replace 80:90 with the desired port range to forward. If only one port needs to be forwarded, use the port number directly. To forward UDP traffic, replace tcp with udp.
Create routing rules (destination address):
iptables -t nat -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 80:90 -j DNAT --to-destination 2.2.2.2
Note: The parameters to be replaced are the same as in the previous command.
Create routing rules (source address):
iptables -t nat -A POSTROUTING -o venet0 -j MASQUERADE
Note: Replace venet0 with the network interface name.
Save and load iptables:
service iptables save
service iptables reload
With these steps, we have successfully set up traffic forwarding from an old server to a new server in a Linux cloud server environment using iptables.
23-02-2024 02:02:07
22-02-2024 03:19:32
22-02-2024 03:16:03
22-02-2024 03:14:03
22-02-2024 03:11:58