温馨提示×

怎么配置CentOS防火墙

小樊
36
2026-08-18 14:48:47
栏目: 智能运维

CentOS 中,防火墙工具随版本不同而变化:

  • CentOS 7 及以后:默认使用 firewalld
  • CentOS 6 及更早:使用 iptables

下面分别说明。


一、CentOS 7 / 8 / Stream(firewalld)

1️⃣ 查看防火墙状态

systemctl status firewalld

启动 / 停止 / 重启:

systemctl start firewalld
systemctl stop firewalld
systemctl restart firewalld

设置开机启动:

systemctl enable firewalld

2️⃣ 查看当前规则

firewall-cmd --list-all

查看所有开放端口:

firewall-cmd --list-ports

3️⃣ 开放端口(常用)

临时生效(重启失效)

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

永久生效

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

示例:

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

4️⃣ 开放服务(如 http、https)

firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent
firewall-cmd --reload

5️⃣ 删除端口或服务

firewall-cmd --remove-port=80/tcp --permanent
firewall-cmd --remove-service=http --permanent
firewall-cmd --reload

6️⃣ 指定 IP 白名单(允许某 IP 访问)

firewall-cmd --permanent --add-source=192.168.1.100
firewall-cmd --reload

二、CentOS 6 或手动使用 iptables

1️⃣ 查看规则

iptables -L -n

2️⃣ 开放端口(如 80)

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

3️⃣ 保存规则(否则重启失效)

service iptables save

或:

/etc/init.d/iptables save

4️⃣ 启动 / 停止 iptables

service iptables start
service iptables stop
chkconfig iptables on

三、常见场景示例

✅ 开放 MySQL(3306)

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

✅ 禁止 ping(ICMP)

firewall-cmd --permanent --add-icmp-block=echo-request
firewall-cmd --reload

四、快速判断你该用哪个?

systemctl status firewalld
  • ✅ running → 用 firewalld
  • ❌ not found / inactive → 用 iptables

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

  • ✅ CentOS 具体版本
  • ✅ 想开放 / 限制哪些端口或 IP

我可以给你精确命令

0