GKE环境下带Axios KeepAlive的NodeJS微服务TCP连接数查看方法
查看NodeJS应用与目标服务的TCP连接数(GKE Pod环境)
一、使用系统工具查看
很多轻量Node镜像默认不带netstat、lsof这类工具,先按需安装:
- Alpine镜像:
apk add --no-cache net-tools lsof iproute2 - Debian/Ubuntu镜像:
apt update && apt install -y net-tools lsof iproute2
1. 用ss命令(推荐,更高效)
先解析目标服务的IP:
nslookup any.example.restapis.com
然后过滤Node进程与目标IP的TCP连接:
# 查看所有状态的TCP连接(ESTABLISHED、TIME_WAIT等) ss -t -a -p | grep 'node' | grep <目标IP> # 只看已建立的活跃连接 ss -t -a -p state established | grep 'node' | grep <目标IP>
参数说明:
-t:只显示TCP连接-a:显示所有状态(监听/已建立等)-p:显示进程信息
2. 用lsof命令
通过进程ID过滤,只看与目标IP的TCP连接:
lsof -n -p <你的Node进程PID> -i TCP | grep <目标IP>
参数说明:
-n:不解析域名,避免延迟-p:指定进程ID-i TCP:只筛选TCP连接
二、通过NodeJS代码直接查看连接池状态
Axios的httpsAgent本身会维护连接池,直接打印其内部属性能更精准获取连接状态:
const https = require('https'); const axios = require('axios'); // 初始化带keepAlive的Agent并保存引用 const keepAliveAgent = new https.Agent({ keepAlive: true }); const axiosClient = axios.create({ httpsAgent: keepAliveAgent }); // 定时打印连接池状态(可按需调整间隔) setInterval(() => { console.log(`=== 连接池状态 ===`); console.log(`活跃连接数: ${Object.keys(keepAliveAgent.sockets).reduce((total, key) => total + keepAliveAgent.sockets[key].length, 0)}`); console.log(`空闲连接数: ${Object.keys(keepAliveAgent.freeSockets).reduce((total, key) => total + keepAliveAgent.freeSockets[key].length, 0)}`); console.log(`等待队列中的请求数: ${Object.keys(keepAliveAgent.requests).reduce((total, key) => total + keepAliveAgent.requests[key].length, 0)}`); }, 10000);
部署后查看应用日志即可看到实时的连接池数据,这比系统工具更能反映Axios实际使用的连接情况。
常见问题排查
- 之前
netstat无结果:大概率是镜像未安装net-tools包,或者未过滤目标IP导致结果被淹没,建议用ss替代netstat(前者是现代版工具,很多镜像默认预装)。 - 找不到Node进程PID:用
ps aux | grep node获取进程ID。
内容的提问来源于stack exchange,提问作者NNP
相关产品推荐
相关产品推荐

