沐光

记录在前端之路的点点滴滴

iptables 端口转发配置

前言

先前转载了一篇 iptables 的使用和配置的文章,但是凡事都得自己动手学习一下才能深入了解,因此本篇用来记录动手操作了一番后的一些配置心得。当然建议大家了解的时候读一读参考文章,特别是 iptables 入门指南iptables 详解,能让你对 iptables 有更深入的理解。

查看本地规则

root 用户下

1
iptables -nL -t nat --line-number

显示结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@/]# iptables -nL -t nat
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 redir ports 8020

Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- 0.0.0.0/0 127.0.0.1 tcp dpt:80 redir ports 8020
REDIRECT tcp -- 0.0.0.0/0 <本机IP> tcp dpt:80 redir ports 8020

Chain POSTROUTING (policy ACCEPT)
target prot opt source destination

其中 Chain PREROUTING (policy ACCEPT) 指的是有外部访问本机的 80 端口时,其会转发到 8020 端口;Chain OUTPUT (policy ACCEPT) 指的是内部机器地址输出时,当监测到目标地址为 127.0.0.1 / <本机IP> 时,其默认的 80 端口会转发到 8020 端口,从而实现 80 -> 8020 端口的转发。

添加转发规则

外部访问端口转发

iptables 转发端口时,其使用的并非默认的 filter,因此需要 -t 制定为 nat,此外上面有说到,外部访问时会经由 PREROUTING,因此需要对此规则做配置,指令如下:

1
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8020
  • -t: 指定表为 nat 表(默认为 filter 表)
  • -A: 指定 nat 表中的三项规则中的哪一项,分别为: OUTPUTPREROUTINGPOSTEROUTING
  • -p: 指定使用的协议
  • --dport: 指定目标端口
  • -j: 指定针对本机做重定向操作(DROP、ACCEPT、REDIRECT 等)
  • --to-port: 重定向的端口

补充,不同表的操作链

INPUT FORWARD OUTPUT PREROUTING POSTEROUTING
Filter true true true false false
Nat false false true true true
Mangle true true true true true

内部访问端口转发

仅外部转发其实是不够的,对于内部地址访问时仍需要进行一次转发才能满足内外一致的情况,与上指令类似:

1
iptables -t nat -A OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-port 8020
  • -d: 指定目的地址地址(与之相反的 -s 为指定源地址)

删除转发规则

删除指令如下:

1
iptables - t nat -D OUTPUT <number>

验证规则生效

telnet ip port: 查看某一个机器上的某一个端口是否可以访问,如:

1
telnet 127.0.0.1 8020

配置开机启动

结合 iptables-saveiptables-reload 使用

1
iptables-save > /root/iptables.bk

配置启动脚本

1
2
3
4
5
6
7
8
9
10
11
12
# 配置启动脚本
vim /root/iptables-preload

#### 将如下内容贴入其中并保存
#!/bin/bash
/sbin/iptables-restore < /root/iptables.up.rules
####

chmod +x /root/iptables-preload

#### 编辑 /etc/rc.local,添加如下内容
/root/iptables-preload

参考文章