温馨提示×

Debian防火墙如何设置规则

小樊
43
2026-07-06 18:20:45
栏目: 智能运维

Debian 本身没有默认的防火墙服务,通常是通过 iptables / nftables 来实现,或者更常见的是使用 UFW(Uncomplicated Firewall) 作为前端。下面按从简单到专业的方式给你说明。


一、最推荐:使用 UFW(适合大多数用户)

1️⃣ 安装 UFW

sudo apt update
sudo apt install ufw

2️⃣ 基本规则设置

允许 SSH(非常重要,防止被踢出)

sudo ufw allow 22/tcp

允许常用端口

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

允许指定 IP

sudo ufw allow from 192.168.1.100

允许某 IP 访问某端口

sudo ufw allow from 192.168.1.100 to any port 3306

3️⃣ 启用 / 禁用

sudo ufw enable
sudo ufw disable

4️⃣ 查看状态

sudo ufw status verbose

5️⃣ 删除规则

sudo ufw delete allow 80/tcp

二、进阶:iptables(传统方式)

⚠️ 注意:Debian 10+ 默认底层是 nftables,iptables 实际是兼容层。

查看规则

iptables -L -n

允许 SSH

iptables -A INPUT -p tcp --dport 22 -j ACCEPT

允许 HTTP/HTTPS

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

设置默认策略

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

保存规则(Debian)

apt install iptables-persistent
netfilter-persistent save

三、现代方式:nftables(推荐服务器使用)

安装

sudo apt install nftables

查看规则

sudo nft list ruleset

示例规则(允许 SSH、HTTP、HTTPS)

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

保存

sudo nft list ruleset > /etc/nftables.conf

四、如何选择?

场景 推荐
新手 / VPS ✅ UFW
老系统 / 脚本 iptables
新服务器 / 高性能 ✅ nftables

五、常见安全建议 ✅

  • ✅ 先允许 SSH,再启用防火墙
  • ✅ 禁止 root 直接 SSH
  • ✅ 非必要端口全部关闭
  • ✅ 云服务器配合安全组使用

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

  • Debian 版本(cat /etc/debian_version
  • 本地服务器 / VPS / 云服务器
  • 想开放哪些端口

我可以帮你写一套完整可用的防火墙规则

0