私有 Git 仓库必须在 composer.json 的 repositories 中显式声明 type 为 vcs 的源,否则即使认证通过也会报“Could not find package”;auth.json 仅负责认证,需正确配置位置、权限及凭据类型;repositories 顺序决定包解析优先级,私有源须置于官方源之前。

私有 Git 仓库必须声明为 composer.json 中的 repository
Composer 默认只认 Packagist,所有非 Packagist 的包(包括私有 Git 仓库)都必须显式声明 repository。不加这节,哪怕 URL 正确、认证通过,composer require 也会报 Could not find package xxx。
常见错误是以为配置了 auth.json 就够了——其实它只管认证,不管发现路径。
-
type必须是vcs(不是git或package) -
url要写完整仓库地址,如https://git.example.com/team/utils.git或git@git.example.com:team/logger.git - 多个私有源就写多个
repository对象,顺序无关,但建议按域名分组
HTTP/HTTPS 私有源需在 auth.json 配置 token 或账号密码
Git over HTTPS 认证失败时,composer install 会卡住或报 401 Unauthorized,不是网络问题,而是凭据缺失。
auth.json 必须放在项目根目录或全局配置目录(COMPOSER_HOME),且权限不能太宽松(Linux/macOS 下需 chmod 600 auth.json,否则 Composer 会忽略)。
- GitHub:用
github-oauth字段配 personal access token - GitLab/Gitee:用
http-basic,username填 token(GitLab 推荐用Private Token),password留空或填任意值(部分版本要求非空) - Bitbucket:同
http-basic,但username是账号名,password是 app password(不是登录密码)
composer.json 的 repositories 顺序影响包解析优先级
当多个仓库都提供同名包(如 myorg/core),Composer 按 repositories 数组从上到下扫描,命中第一个就停。这不是“覆盖”,而是“短路匹配”。
这意味着:如果把 Packagist 官方源({"type": "packagist", "url": "https://packagist.org"} )放在最前面,你的私有同名包永远无法被加载。
- 务必把私有源放在官方源之前
- 若用
packagist.org作为兜底,应显式声明并置于数组末尾 - 禁用默认 Packagist:设
"packagist.org": false在repositories里,避免意外拉取公共版本
SSH 私有源要确保运行用户能无密码访问对应 ~/.ssh/id_rsa
用 git@ 地址时,Composer 底层调用的是系统 git 命令,所以依赖的是当前执行用户的 SSH 配置,不是 Composer 自己的认证机制。
CI/CD 环境最容易出问题:部署用户没加载 key,或 ssh-agent 未启动,或 known_hosts 缺失目标主机指纹。
- 测试方式:切换到目标用户,手动执行
git ls-remote git@git.example.com:team/lib.git HEAD - CI 中建议用
ssh-keyscan预填充~/.ssh/known_hosts - 避免使用
git+ssh://格式,直接用git@host:path.git更稳定










