简介:本文将详细介绍如何使用Verdaccio搭建私有化npm仓库,帮助开发者与企业用户实现依赖包的集中管理与安全分发。
在软件开发过程中,依赖管理是核心环节之一。对于企业级项目或团队协作场景,直接使用公共npm仓库可能存在安全风险、网络依赖等问题。Verdaccio作为一款轻量级、高可定制的私有npm代理仓库,能够完美解决这些问题。本文将从环境准备到高级配置,逐步指导你完成私有化npm仓库的搭建。
Verdaccio基于Node.js运行,因此需要提前安装:
验证环境是否就绪:
node -v # 应输出v18.x.x
npm -v # 应输出9.x.x或更高
通过npm全局安装Verdaccio:
npm install -g verdaccio
安装完成后,运行verdaccio --version
验证安装成功。
直接运行以下命令启动默认配置的Verdaccio:
verdaccio
服务默认监听4873
端口,访问http://localhost:4873
应看到Web界面。此时已具备基础功能,但需进一步配置以满足生产需求。
Verdaccio的主配置文件为config.yaml
,默认位于:
~/.config/verdaccio/config.yaml
%APPDATA%\verdaccio\config.yaml
可通过--config
参数指定自定义路径:
verdaccio --config /path/to/custom-config.yaml
修改storage
字段指定包存储路径:
storage: ./my-storage # 相对路径
# 或
storage: /var/verdaccio/storage # 绝对路径
启用用户名密码认证,修改auth
部分:
auth:
htpasswd:
file: ./htpasswd # 用户数据库文件
algorithm: md5 # 加密算法(可选sha1/crypt)
生成用户密码文件:
npm install -g htpasswd # 安装工具
htpasswd -B -b -c htpasswd admin mypassword # 创建admin用户
配置上游npm仓库以缓存公共包:
uplinks:
npmjs:
url: https://registry.npmjs.org/
packages:
'@*/*':
access: $authenticated
publish: $authenticated
proxy: npmjs # 允许代理未缓存的包
'**':
access: $authenticated
publish: $authenticated
proxy: npmjs
精细控制包的读写权限:
packages:
'my-company-*':
access: $authenticated
publish: admin # 仅admin用户可发布
'**':
access: $all # 公开包允许所有人访问
生成SSL证书(以自签名为例):
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
修改配置启用HTTPS:
https:
key: ./key.pem
cert: ./cert.pem
port: 8443
listen: https://0.0.0.0:8443
安装日志插件:
npm install -g verdaccio-audit
在配置中启用:
plugins: ./plugins
middlewares:
audit:
enabled: true
对于大型仓库,调整内存限制:
max_body_size: 100mb # 允许大文件上传
或通过启动参数:
node --max-old-space-size=4096 $(which verdaccio)
使用PM2守护进程:
npm install -g pm2
pm2 start verdaccio --name verdaccio -- -c /path/to/config.yaml
pm2 save
pm2 startup # 设置开机自启
Nginx示例配置:
server {
listen 80;
server_name npm.mycompany.com;
location / {
proxy_pass http://localhost:4873;
proxy_set_header Host $host;
}
}
storage
目录verdaccio-prometheus-plugin
)检查:
packages
规则的publish
列表中@scope/*
规则调整:
server:
keepAliveTimeout: 60 # 默认5秒可能不足
设置自动清理:
# 安装清理插件
npm install -g verdaccio-memory-cache
配置中添加:
store:
memory:
limit: 1024 # 1GB缓存限制
通过以上步骤,你已成功搭建了一个功能完善、安全可靠的私有npm仓库。Verdaccio的模块化设计使得后续扩展(如添加LDAP认证、集成公司SSO等)变得简单。建议定期审查配置,根据团队规模调整存储和性能参数。