朕喜技术(ZhenxiJS)
2026.08.31
1 分钟阅读

iptables 防火墙规则 DROP 导致端口无法访问:端口 LISTEN 但 curl 超时

日期:2026-08-31
技术栈:Linux、iptables、防火墙、netstat / ss、curl
现象关键词:iptables DROP 规则、端口不通、connection refused、connection timed out、8080 端口无法访问、端口 LISTEN 但连不上

一、问题背景

Linux 服务器上部署了 HTTP 服务监听 8080 端口,服务进程正常、端口显示 LISTEN 状态,但从客户端访问 http://<IP>:8080 一直超时或连接失败。CPU、内存、进程都正常,问题隐藏在防火墙层——iptables 的 INPUT 链存在一条 DROP 所有发往 8080 端口 TCP 包的规则。

这种问题在真实运维中很常见:误执行了过宽的 iptables 规则、脚本自动添加了防火墙规则、或者有人调试时忘了删除临时规则。

二、复现步骤

# 1. 启动复现环境(容器内已内置错误防火墙规则)
cd scenario/2026-08-31-1600
docker compose up -d --build
docker compose exec app bash

# 2. 确认 HTTP 服务确实在监听 8080
ss -tlnp | grep 8080
# LISTEN 0  5  0.0.0.0:8080  0.0.0.0:*  users:(("python3",pid=11,fd=3))

# 3. 尝试访问 8080 端口 —— 发现超时
curl -v --connect-timeout 3 http://localhost:8080
# curl: (28) Failed to connect to localhost port 8080 ... Connection timed out

# 4. 检查 iptables INPUT 链
iptables -L INPUT -n --line-numbers
# Chain INPUT (policy ACCEPT)
# num  target  prot opt source        destination
# 1    DROP    tcp  --  0.0.0.0/0     0.0.0.0/0  tcp dpt:8080

三、根本原因

iptables INPUT 链中存在一条 DROP 规则,丢弃了所有发往 8080 端口的入站 TCP 包。

iptables -A INPUT -p tcp --dport 8080 -j DROP

这条规则在 INPUT 链的最前面(编号 1),所以所有目标是 8080 端口的入站 TCP 包都会被直接丢弃,服务进程虽然监听正常,但收不到任何客户端请求。

四、解决办法

删除这条 DROP 规则,两种方式任选其一:

# 方法 1:按规则编号删除(先查看编号)
iptables -L INPUT -n --line-numbers
iptables -D INPUT 1

# 方法 2:按完整规则匹配删除
iptables -D INPUT -p tcp --dport 8080 -j DROP

如果使用 firewalld,对应的操作是:

firewall-cmd --permanent --remove-port=8080/tcp
firewall-cmd --reload

如果是 ufw:

ufw delete deny 8080/tcp

五、验证

# 确认 INPUT 链已无 DROP 规则
iptables -L INPUT -n --line-numbers
# Chain INPUT (policy ACCEPT)
# num  target  prot opt source  destination

# 访问 8080 端口恢复正常
curl -s --connect-timeout 3 http://localhost:8080
# Hello from HTTP server on port 8080!

六、经验与避坑

排查思路速查

当「服务进程正常 + 端口 LISTEN + 但外部访问不通」时,按以下顺序排查:

  1. 确认监听:ss -tlnp | grep <port>
  2. 本机自测:curl -v --connect-timeout 3 http://localhost:<port>(加超时避免长时间卡住)
  3. 检查防火墙:iptables -L INPUT -n --line-numbers、firewall-cmd --list-all、ufw status verbose
  4. 检查 SELinux(CentOS/RHEL):getenforce,如为 Enforcing 检查 ausearch -m avc
  5. 检查云安全组(云服务器):确认安全组入方向规则放通了目标端口

避坑要点

  • curl 一定要加 --connect-timeout,否则默认会尝试很久才报超时,浪费排查时间
  • 删除 iptables 规则前先看行号,因为链中可能有其他规则,编号可能变动
  • iptables 规则不持久化:重启后规则会丢失,生产环境要用 iptables-save 持久化
  • 区分 connection refused 和 connection timed out:
    • Connection refused:端口没监听或没被监听(进程不在 / bind 到了别的 IP)
    • Connection timed out:包被防火墙丢弃(DROP 而不是 REJECT)
  • DROP vs REJECT:DROP 表现为超时(timeout),REJECT 表现为拒绝(refused),这是快速判断防火墙类型的重要线索
  • Docker 环境测试注意:容器内操作 iptables 需要 --cap-add NET_ADMIN 权限

常用命令速查

# 查看规则(带行号)
iptables -L INPUT -n --line-numbers

# 按编号删除规则
iptables -D INPUT <编号>

# 按规则内容删除
iptables -D INPUT -p tcp --dport <端口> -j DROP

# 查看所有防火墙相关配置
iptables -S
iptables -L -n -v

版权声明

本文为博主原创文章,遵循 CC BY-NC-SA 4.0 许可协议。 转载请注明出处:http://localhost/blogs/2026-08-31-1600-iptables-drop-8080

分享这篇文章