You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

npm从自托管GitLab私有库安装频繁失败:kex_exchange_identification错误

解决npm安装GitLab私有依赖频繁出现SSH连接失败的问题

问题场景

搭建自托管GitLab实例后,在Node.js项目中通过SSH方式引入私有库依赖,package.json配置如下:

{
  ...
  "dependencies": {
    "package-name": "git+ssh://git@GITSERVER/PATH/PROJECT.git#semver:~1.0.0",
    ...
  }
}

执行npm install时频繁失败(十次中有九次失败),需多次重试才能完成所有依赖安装。项目包含8-10个同类型私有依赖,失败位置不固定。

报错信息

npm ERR! An unknown git error occurred
npm ERR! command git --no-replace-objects clone ssh://git@GITSERVER/PATH/PROJECT-XYZ /home/msv/.npm/_cacache/tmp/git-cloneKNBhFm --recurse-submodules
npm ERR! Cloning into '/home/msv/.npm/_cacache/tmp/git-cloneKNBhFm'...
npm ERR! kex_exchange_identification: Connection closed by remote host
npm ERR! Connection closed by x.x.x.x port 22
npm ERR! fatal: Could not read from remote repository.
npm ERR! 
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

单独SSH连接GitLab服务器、直接使用git clone克隆仓库均正常,仅npm安装时出现异常。已禁用GitLab限流、服务器未经过代理、更换过服务器主机,问题仍未解决。


解决方法

1. 配置SSH连接复用与保活

npm安装多私有依赖时会并发发起SSH连接,即使GitLab限流禁用,服务器SSH服务的默认并发限制仍可能触发连接拒绝。在~/.ssh/config中添加以下配置:

Host GITSERVER
  HostName GITSERVER
  User git
  IdentityFile ~/.ssh/your-private-key
  ControlMaster auto
  ControlPath ~/.ssh/sockets/%r@%h-%p
  ControlPersist 60s
  ServerAliveInterval 15
  ServerAliveCountMax 3
  • ControlMaster/ControlPath:实现SSH连接复用,减少重复建立连接的次数
  • ServerAliveInterval/ServerAliveCountMax:保持连接活跃,避免被服务器主动断开

2. 限制npm并发安装数

npm默认并发数过高,短时间内发起过多SSH连接可能触发服务器防御机制。临时限制并发数:

npm install --maxsockets 3

或在~/.npmrc中永久配置:

maxsockets=3

3. 改用HTTPS协议引入依赖

如果SSH连接问题无法解决,可切换为HTTPS方式,使用GitLab个人访问令牌(PAT)认证:

{
  "dependencies": {
    "package-name": "git+https://oauth2:YOUR_PAT@GITSERVER/PATH/PROJECT.git#semver:~1.0.0"
  }
}

将YOUR_PAT替换为具有read_repository权限的GitLab个人访问令牌,也可将令牌配置到~/.npmrc避免明文暴露:

@your-scope:registry=https://GITSERVER/api/v4/packages/npm/
//GITSERVER/api/v4/packages/npm/:_authToken=YOUR_PAT

4. 调整服务器SSH服务的并发限制

服务器端sshd的MaxStartups参数限制未认证的并发连接数,修改/etc/ssh/sshd_config:

MaxStartups 10:30:100

该配置表示:未认证连接数达10时开始随机拒绝30%的连接,达100时全部拒绝,可根据实际情况调高数值。修改后重启sshd服务:

systemctl restart sshd

5. 清理npm缓存重试

缓存的临时文件可能导致异常,清理后重新安装:

npm cache clean --force
rm -rf node_modules package-lock.json
npm install

内容的提问来源于stack exchange,提问作者Mikkel S. Vestergård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:55:37