温馨提示×

怎样配置debian防火墙规则

小樊
47
2026-09-29 11:31:41
栏目: 智能运维

在 Debian 系统中,配置防火墙通常有几种常见方式,最常用的是 iptables(传统) 和 nftables(新一代,Debian 10+ 默认),以及更友好的前端工具 ufw。下面按使用场景给你说明。


一、使用 ufw(推荐,简单易用)

1. 安装 ufw

sudo apt update
sudo apt install ufw

2. 基本配置示例

# 允许 SSH(非常重要,避免被锁外面)
sudo ufw allow 22/tcp

# 允许 HTTP / HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

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

# 启用防火墙
sudo ufw enable

# 查看状态
sudo ufw status verbose

3. 常用命令

sudo ufw allow 3306/tcp        # 允许 MySQL
sudo ufw delete allow 80/tcp  # 删除规则
sudo ufw disable               # 关闭

二、使用 nftables(Debian 10+ 推荐)

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

        # 允许 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

三、使用 iptables(传统方式)

Debian 新版本已逐步用 nftables 替代 iptables

示例

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -P INPUT DROP

保存规则:

sudo apt install iptables-persistent
sudo netfilter-persistent save

四、选择建议

  • 新手 / 普通服务器:✅ ufw
  • 复杂网络 / 高性能:✅ nftables
  • 老系统兼容:⚠️ iptables

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

  • Debian 版本(cat /etc/debian_version)
  • 是 云服务器 / 物理机 / 内网
  • 需要开放哪些端口(如 SSH、Web、数据库)

我可以直接帮你写一套可复制的防火墙配置。

0 踩