温馨提示×

Debian防火墙怎么添加端口

小樊
39
2026-07-06 18:14:33
栏目: 智能运维

在 Debian 中,防火墙通常使用 ufw(简单)或 iptables/nftables(底层)。下面按常见情况说明,你可以按需要选择。


一、使用 UFW(推荐,最简单)

1️⃣ 安装 UFW

sudo apt update
sudo apt install ufw

2️⃣ 启用 UFW

sudo ufw enable

启用前建议先允许 SSH,否则可能会被断开连接。

3️⃣ 允许指定端口

允许 TCP 端口(常用)

sudo ufw allow 8080/tcp

允许 UDP 端口

sudo ufw allow 8080/udp

允许某个服务(如 SSH、HTTP)

sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

4️⃣ 查看规则

sudo ufw status verbose

5️⃣ 删除端口规则

sudo ufw delete allow 8080/tcp

二、使用 iptables(传统方式)

1️⃣ 添加端口(以 8080 为例)

sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

2️⃣ 保存规则(Debian 不会自动保存)

sudo apt install iptables-persistent
sudo netfilter-persistent save

3️⃣ 查看规则

sudo iptables -L -n

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

1️⃣ 安装并启用

sudo apt install nftables
sudo systemctl enable nftables

2️⃣ 添加端口

sudo nft add rule inet filter input tcp dport 8080 accept

3️⃣ 保存配置

sudo nft list ruleset > /etc/nftables.conf

四、快速选择建议 ✅

场景 推荐
新手 / 服务器 ✅ UFW
高级定制 iptables / nftables
Debian 10+ nftables(底层)

五、常见坑提醒 ⚠️

  • 云服务器要同时开放 安全组端口
  • 修改前先允许 SSH:
    sudo ufw allow 22
    
  • 规则不生效?检查:
    sudo ufw status
    

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

  • Debian 版本(cat /etc/debian_version
  • 使用的防火墙(UFW / iptables / nftables)
  • 要开放的端口和用途(如 Web、数据库、Docker)

我可以给你精确命令

0