端口无法使用问题

端口占用与端口不可用问题的排查与解决

#tech / ops / linux #type / howto #status / evergreen

[!info] related notes

端口无法使用问题

现象

启动服务时端口报被占用,换端口仍报错,但 netstat 检测显示无进程占用。改为其他端口段(如 18080)则正常。

原因

  1. 端口被 TIME_WAIT 占用:之前的连接尚未完全释放,端口处于 TIME_WAIT 状态
  2. Hyper-V / WSL 保留端口:Windows 的 Hyper-V 会保留特定端口范围(如 48000-49000)
  3. 防火墙规则:系统防火墙或安全软件拦截了特定端口
  4. net.ipv4.ip_local_port_range 冲突(Linux):系统临时端口范围与应用端口冲突

排查

1. 检查端口占用

# Windows
netstat -ano | findstr ":48080"
Get-Process -Id <PID>

# Linux / macOS
lsof -i :48080
ss -tlnp | grep 48080

2. 检查 Hyper-V 保留端口(Windows 重点排查)

# 查看 Hyper-V 保留的端口范围
netsh interface ipv4 show excludedportrange protocol=tcp

如果目标端口落在保留范围内,这就是根因。

3. 检查防火墙

# Windows
netsh advfirewall firewall show rule name=all | findstr "48080"

# Linux
sudo iptables -L -n | grep 48080
sudo ufw status

4. 检查临时端口范围(Linux)

cat /proc/sys/net/ipv4/ip_local_port_range
# 输出如 32768 60999,如果应用端口在此范围内会冲突

解决

杀掉占用进程

# Windows - 杀掉占用端口的进程
netstat -ano | findstr ":48080"
taskkill /PID <PID> /F

# Linux
kill -9 $(lsof -t -i:48080)

解决 Hyper-V 端口保留问题

# 方法 1:临时关闭 Hyper-V(需要重启)
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

# 方法 2:使用不在保留范围的端口(推荐)
# 将服务端口改为 18080 等不在保留范围的端口

Linux 解决临时端口冲突

# 临时修改临时端口范围
sudo sysctl -w net.ipv4.ip_local_port_range="61000 65535"

# 永久修改
echo "net.ipv4.ip_local_port_range = 61000 65535" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

释放 TIME_WAIT 端口

# Linux - 开启 TIME_WAIT 快速回收
sudo sysctl -w net.ipv4.tcp_tw_reuse=1

# Windows - 等待或换端口,TIME_WAIT 默认 120 秒后自动释放

验证

  1. 重新启动服务,确认端口绑定成功
  2. netstat -ano | findstr ":端口" 确认进程正常监听
  3. 浏览器访问 http://localhost:端口 确认服务可达
创建于 2025/1/1 更新于 2026/5/27