全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-25 5 分钟 ✍️ juanwangdev

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指定用户

生产环境内部包的 accesspublish 应设为 $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 插件管理认证
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 prepare与prepublishOnly钩子
下一篇 → pnpm与Yarn对比分析
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码