Verdaccio私有仓库搭建
Verdaccio 是轻量级 NPM 私有仓库,零依赖即可运行,适合企业内部包管理与依赖缓存代理。
Verdaccio私有仓库搭建
安装与启动
Bash
# 全局安装
npm install -g verdaccio
# 启动(默认端口 4873)
verdaccio
# 指定端口和配置
verdaccio --listen 0.0.0.0:4873 --config ./config.yaml
首次启动自动生成配置文件
~/.config/verdaccio/config.yaml和存储目录~/.local/share/verdaccio/storage。
核心配置
YAML
# config.yaml
storage: ./storage
plugins: ./plugins
web:
title: 企业私有NPM仓库
enable: true
auth:
htpasswd:
file: ./htpasswd
max_users: 100
uplinks:
npmjs:
url: https://registry.npmjs.org/
cache: true
npmmirror:
url: https://registry.npmmirror.com/
cache: true
packages:
'@company/*':
access: $authenticated
publish: $authenticated
unpublish: $authenticated
proxy: npmjs
'**':
access: $all
publish: $authenticated
proxy: npmjs npmmirror
listen: 0.0.0.0:4873
packages配置按包名模式匹配,@company/*限定内部包仅认证用户可访问和发布。
权限与用户管理
Bash
# 创建用户
npm adduser --registry http://localhost:4873
# 指定用户名密码
npx verdaccio-htpasswd -c user1 password123
# htpasswd 文件格式
# user1:$apr1$xxx...
# user2:$apr1$yyy...
权限角色说明:
| 角色 | 说明 |
|---|---|
$all | 任何人(含匿名) |
$anonymous | 仅匿名用户 |
$authenticated | 仅已认证用户 |
user1 user2 | 指定用户 |
生产环境内部包的
access和publish应设为$authenticated,禁止匿名访问。
上游代理与缓存
YAML
uplinks:
npmjs:
url: https://registry.npmjs.org/
cache: true
maxage: 30m
timeout: 30s
max_fails: 5
fail_timeout: 10m
- 请求私有仓库中不存在的包时,自动从 upstream 拉取并缓存
maxage控制缓存有效期,过期后重新验证fail_timeout内连续max_fails次失败后暂停代理
配置国内镜像作为 upstream 可大幅提升拉取速度,同时私有仓库充当缓存层减少外网依赖。
发布与使用私有包
Bash
# 配置项目 registry
npm config set registry http://localhost:4873
# 或在 .npmrc 中按 scope 配置
@company:registry=http://localhost:4873
Bash
# 发布
npm publish --registry http://localhost:4873
# 安装私有包
npm install @company/utils
JSON
// package.json
{
"name": "@company/utils",
"version": "1.0.0",
"publishConfig": {
"registry": "http://localhost:4873"
}
}
publishConfig.registry确保包发布到私有仓库,而非公共 npmjs.org。
进程守护与持久化
Bash
# 使用 pm2 守护
npm install -g pm2
pm2 start verdaccio --name npm-registry
# Docker 部署
docker run -d \
--name verdaccio \
-p 4873:4873 \
-v /path/to/config:/verdaccio/conf \
-v /path/to/storage:/verdaccio/storage \
verdaccio/verdaccio
生产环境必须使用进程守护(pm2)或容器化部署,并定期备份 storage 目录。
插件扩展
Bash
# 安装认证插件(如 LDAP)
npm install -g verdaccio-ldap
# 配置使用插件
YAML
auth:
ldap:
type: ldap
client_options:
url: ldap://ldap.company.com
bindDN: cn=admin,dc=company,dc=com
企业环境建议集成 LDAP/SSO 认证,避免手动管理 htpasswd 文件。
要点总结
- Verdaccio 零依赖轻量部署,
verdaccio命令即可启动,默认端口 4873 packages配置按包名模式控制访问和发布权限,内部包限制为$authenticated- upstream 代理 + 缓存实现私有包本地存储、公共包透明代理
.npmrc按 scope 配置 registry,publishConfig.registry确保发布目标正确- 生产环境使用 pm2 或 Docker 守护,集成 LDAP/SSO 插件管理认证