用途:有两台机器,需要用其中的一台机器做跳板,转发另一台机器一个特定的端口,机器列表如下

机器 IP
iptables机器 10.0.0.41
web服务器 10.0.0.42:8000

开启内核转发功能

1
sudo sysctl -w net.ipv4.ip_forward=1

或者

1
echo "1" > /proc/sys/net/ipv4/ip_forward
1
2
3
4
5
6
7
sudo vim /etc/sysctl.conf

# 保证是这个配置
net.ipv4.ip_forward=1

# 立即生效
sudo sysctl -p

本地端口转发到本地端口

1
2
# 访问本地的2222端口,转发到本地的22端口
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j REDIRECT --to-port 22

转发请求到目标主机

这是通过本主机做一个跳转,比如访问A的80端口转发到B的8000端口

1
2
3
4
iptables -t nat -A PREROUTING -4 -p tcp -d 10.0.0.41 --dport 80 -j DNAT --to-destination 10.0.0.42:8000

# 转发数据包回路
iptables -t nat -A POSTROUTING -4 -p tcp -d 10.0.0.42 --dport 8000 -j MASQUERADE

其他操作

操作 命令
查看nat表 sudo iptables -t nat -L
清空nat表配置 sudo iptables -t nat -F
查看filter表 sudo iptables -L
清空filter表 sudo iptables -F

iptables持久化

请看iptables进行持久化配置,重启不丢失