温馨提示×

如何用Debian配置防火墙

小樊
46
2026-10-11 05:45:52
栏目: 智能运维

在 Debian 中配置防火墙,常见做法有 iptables(传统) 和 nftables / ufw(推荐、易用)。下面按从易到难给你一套实用方案。


一、推荐方式:使用 UFW(最简单)

UFW 是 iptables 的前端,适合大多数服务器。

1. 安装 UFW

sudo apt update
sudo apt install ufw

2. 基本配置

# 默认拒绝所有入站,允许所有出站
sudo ufw default deny incoming
sudo ufw default allow outgoing

# 允许 SSH(非常重要,先开再启用)
sudo ufw allow 22/tcp

# 允许常用服务
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

3. 启用防火墙

sudo ufw enable

4. 查看状态

sudo ufw status verbose

✅ 适合:新手、云服务器、一般业务


二、现代方式:nftables(Debian 官方推荐)

Debian 10+ 默认使用 nftables。

1. 安装

sudo apt install nftables
sudo systemctl enable nftables

2. 示例规则(/etc/nftables.conf)

table inet filter {
    chain input {
        type filter hook input priority 0;

        # 允许本地
        iif lo accept

        # 已建立连接允许
        ct state established,related accept

        # ICMP
        ip protocol icmp accept
        ip6 nexthdr icmpv6 accept

        # SSH
        tcp dport 22 accept

        # Web
        tcp dport {80, 443} accept

        # 其他拒绝
        drop
    }

    chain forward {
        type filter hook forward priority 0;
        drop
    }

    chain output {
        type filter hook output priority 0;
        accept
    }
}

3. 应用规则

sudo nft -f /etc/nftables.conf
sudo systemctl restart nftables

✅ 适合:需要精细控制、长期维护


三、传统方式:iptables(不推荐新项目)

sudo apt install iptables

# 示例
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -j DROP

# 保存(Debian)
iptables-save > /etc/iptables/rules.v4

⚠️ Debian 新版本更推荐 nftables


四、安全建议(很重要)

  • ✅ 配置前先确保 SSH 不会被锁
  • ✅ 云服务器建议用 安全组 + UFW 双重防护
  • ✅ 修改规则后测试连接再退出会话
  • ✅ 禁止 root 直接暴露 SSH(改端口 / 用密钥)

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

  • 是 物理机 / 云服务器 / 容器
  • 用途(Web / 数据库 / 内网)
  • 是否使用 Docker

我可以给你针对性防火墙配置示例。

0 踩