温馨提示×

centos iptables怎么开放端口

小樊
35
2026-07-07 22:41:28
栏目: 智能运维

CentOS 上用 iptables 开放端口,常见做法如下(以 CentOS 6 / 7(未使用 firewalld) 为例)。


一、临时开放端口(重启后失效)

例如开放 TCP 80 端口

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

如果是 UDP 端口(比如 53):

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

二、保存规则(否则重启失效)

CentOS 6

service iptables save

CentOS 7(使用 iptables-services)

iptables-save > /etc/sysconfig/iptables

或直接:

service iptables save

三、重启 iptables 服务

CentOS 6

service iptables restart

CentOS 7

systemctl restart iptables

四、查看当前规则

iptables -L -n

或查看指定链:

iptables -L INPUT -n

五、常见完整示例(推荐)

开放 8080 TCP 端口,并限制只接受 NEW 连接:

iptables -I INPUT -p tcp --dport 8080 -m state --state NEW -j ACCEPT

六、如果系统用的是 firewalld(CentOS 7 默认)

那就 不要用 iptables 直接改,而是用:

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

七、常见问题

1️⃣ 端口开了还是连不上?

  • 检查服务是否监听:
    netstat -tunlp | grep 80
    
  • 是否被云服务器安全组拦截
  • 是否有其他规则 DROP

2️⃣ 规则顺序问题

iptables 从上到下匹配,建议:

iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

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

  • ✅ CentOS 版本
  • ✅ 要开放的端口
  • ✅ TCP 还是 UDP

我可以给你一条完全可用的命令

0