在 Debian 中配置防火墙,常见做法有 iptables(传统) 和 nftables / ufw(推荐、易用)。下面按从易到难给你一套实用方案。
UFW 是 iptables 的前端,适合大多数服务器。
sudo apt update
sudo apt install ufw
# 默认拒绝所有入站,允许所有出站
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
sudo ufw enable
sudo ufw status verbose
✅ 适合:新手、云服务器、一般业务
Debian 10+ 默认使用 nftables。
sudo apt install nftables
sudo systemctl enable nftables
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
}
}
sudo nft -f /etc/nftables.conf
sudo systemctl restart nftables
✅ 适合:需要精细控制、长期维护
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
如果你愿意,可以告诉我:
我可以给你针对性防火墙配置示例。