温馨提示×

linux防火墙怎么优化

小樊
51
2026-10-28 00:17:43
栏目: 智能运维

Linux 防火墙的“优化”一般可以从 性能、安全性、可维护性 三个方面来做。下面以最常见的 iptables / nftables / firewalld 为例说明。


一、先确认你用的是哪种防火墙

# 查看是否使用 firewalld
systemctl status firewalld

# 查看 nftables
systemctl status nftables

# 查看 iptables
iptables -L -n

✅ 推荐优先级(新系统): nftables > firewalld(基于 nftables)> iptables


二、性能优化(高并发场景)

1. 使用 nftables 替代 iptables

iptables 规则多时会变慢,nftables 性能更好。

systemctl enable --now nftables

示例(仅允许 22、80、443):

table inet filter {
    chain input {
        type filter hook input priority 0;
        ct state established,related accept
        tcp dport {22,80,443} accept
        drop
    }
}

2. 减少规则数量(合并端口)

❌ 不推荐:

iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

✅ 推荐:

iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT

3. 启用连接追踪优化

避免对已有连接反复匹配:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

nftables:

ct state established,related accept

4. 限制恶意流量(防扫描)

# 限制 SSH 暴力破解
iptables -A INPUT -p tcp --dport 22 -m limit --limit 3/min -j ACCEPT

或用 fail2ban(强烈推荐)


三、安全性优化(生产必做)

1. 默认 DROP(最小化暴露)

iptables -P INPUT DROP
iptables -P FORWARD DROP

nftables:

policy drop;

2. 只允许可信来源(如管理端口)

iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT

3. 防止常见攻击

# 防 SYN Flood
sysctl -w net.ipv4.tcp_syncookies=1

# 防 IP 欺骗
sysctl -w net.ipv4.conf.all.rp_filter=1

四、可维护性优化(别让自己崩溃)

1. 使用 firewalld(适合新手/服务器)

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

✅ 优点:

  • 规则自动持久化
  • 支持 zone(内网 / 公网)
  • 不易写错

2. 规则持久化

# iptables
iptables-save > /etc/iptables/rules.v4

# nftables
nft list ruleset > /etc/nftables.conf

五、常见错误(一定要避免)

❌ 规则顺序写反
❌ 忘记放行回环接口

iptables -A INPUT -i lo -j ACCEPT

❌ 远程服务器没测试就 DROP ALL(容易断连)


六、推荐生产方案(总结)

✅ 新手 / 云服务器:firewalld ✅ 高性能 / 自定义:nftables ✅ 必须配合:fail2ban + SSH 密钥 + 端口限制


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

  • 系统版本(CentOS / Ubuntu / Debian)
  • 用途(Web / 数据库 / 内网 / 公网)
  • 是否高并发

我可以给你一套可直接用的防火墙配置。

0 踩