Composer 引入私有库失败主因是 SSH 认证未通或 repositories 类型未设为 vcs;需在 composer.json 中用 "type": "vcs" 声明 SSH 地址,并确保 ~/.ssh/config 配置正确、私钥权限为 600、name 字段与 require 一致。

Composer 引入私有库失败,大概率不是 composer.json 写错了,而是 SSH 认证没通或仓库地址没配对 —— 重点检查 ~/.ssh/config 和 composer.json 中的 repositories 类型是否匹配。
私有 Git 仓库必须用 vcs 类型声明
Composer 不会自动识别 SSH 地址为可拉取源,必须显式指定类型。直接写 "git@github.com:org/private-repo.git" 是无效的。
正确做法是把仓库地址放进 repositories 数组,并设 "type": "vcs":
{
"repositories": [
{
"type": "vcs",
"url": "git@github.com:org/private-repo.git"
}
],
"require": {
"org/private-repo": "^1.0"
}
}
注意:url 必须是完整 SSH 地址(含 git@),不能是 HTTPS;require 中的包名需与该仓库 composer.json 里的 name 字段完全一致。
~/.ssh/config 要配对 Host 别名
如果私有库域名不标准(比如自建 GitLab、Gitee 企业版、内部 Git 服务器),或想统一管理密钥路径/端口,就得靠 ~/.ssh/config 做映射。否则 Composer 执行 git clone 时找不到密钥或连错主机。
例如对接内部 Git 服务 git.example.com:
Host git.example.com
HostName git.example.com
User git
IdentityFile ~/.ssh/id_rsa_private_repo
PreferredAuthentications publickey
-
Host值必须和composer.json中url的域名部分完全一致 -
IdentityFile指向的私钥必须已用ssh-keygen -t ed25519生成且权限为600 - 执行
ssh -T git@git.example.com能成功返回欢迎信息,才代表 SSH 配置生效
避免 git@ 地址被 Composer 缓存污染
Composer 会缓存 VCS 包的元数据(如 composer.lock 里记录的 commit hash)。一旦改过 SSH 配置或换了密钥,旧缓存可能导致 composer update 卡在 “Cloning into ‘…’” 或报 Permission denied (publickey)。
解决方法是清掉相关缓存:
- 删掉
vendor/下对应包目录 - 删掉
composer.lock中该包的条目(或整删重生成) - 运行
composer clear-cache - 再执行
composer install或composer update org/private-repo
特别注意:如果私有库用了子模块(submodule),还要确认 git config --global submodule.recurse true 已启用,否则 composer install 可能静默跳过子模块拉取。
最常被忽略的是:私有库自己的 composer.json 里 name 字段拼写错误,或没提交到默认分支(比如只推到了 main,但 Composer 默认找 master)。这类问题不会报 SSH 错误,但会提示 Could not find package org/private-repo —— 此时要进私有库跑一遍 composer validate 并确认 tag/branch 是否可达。









