温馨提示×

centos iptables怎么允许端口

小樊
100
2026-07-07 22:37:25
栏目: 智能运维

在 CentOS 系统中,使用 iptables 允许(开放)某个端口,常见做法如下(以 CentOS 7 为例,并假设还在使用 iptables,而不是 firewalld)。


一、基础:允许单个端口(如 8080)

iptables -I INPUT -p tcp --dport 8080 -j ACCEPT
  • -I INPUT:插入到 INPUT 链(默认最前面)
  • -p tcp:TCP 协议(UDP 用 -p udp
  • --dport 8080:目标端口
  • -j ACCEPT:允许

UDP 示例:

iptables -I INPUT -p udp --dport 53 -j ACCEPT

二、允许指定 IP 访问端口(更安全)

只允许 192.168.1.100 访问 3306:

iptables -I INPUT -p tcp -s 192.168.1.100 --dport 3306 -j ACCEPT

三、允许端口范围

允许 8000–9000:

iptables -I INPUT -p tcp --dport 8000:9000 -j ACCEPT

四、保存 iptables 规则(非常重要)

CentOS 7 默认不会自动保存,重启后会丢失规则。

1️⃣ 安装保存工具(如果没有)

yum install -y iptables-services

2️⃣ 保存规则

service iptables save

iptables-save > /etc/sysconfig/iptables

3️⃣ 设置开机启动

systemctl enable iptables
systemctl start iptables

五、查看当前规则

iptables -L -n

或只看 INPUT:

iptables -L INPUT -n

六、删除某条规则

先查看规则编号

iptables -L INPUT --line-numbers

删除第 N 条

iptables -D INPUT 3

七、CentOS 7 建议说明(重要)

CentOS 7 默认使用 firewalld,如果你在用 firewalld,不建议混合使用 iptables

查看是否启用 firewalld

systemctl status firewalld

如果用 firewalld,推荐方式:

firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload

八、常见端口示例

服务 端口
SSH 22
HTTP 80
HTTPS 443
MySQL 3306
Redis 6379

示例:

iptables -I INPUT -p tcp --dport 22 -j ACCEPT

如果你愿意,可以告诉我:

  • ✅ CentOS 版本(6 / 7 / 8)
  • ✅ 是否启用了 firewalld
  • ✅ 想开放哪个端口、是否限制 IP

我可以给你最合适的一套完整命令

0