nexus@docker部署nexus社区版

在企业或团队开发中,使用 Nexus Repository Manager 搭建 PyPI 私服(Python 包索引私有镜像)是一种常见做法,可以缓存官方 PyPI 包,或者上传和管理私有包


一、Nexus 搭建 PyPI 私服

1. 安装 Nexus

参考官方文档安装(建议使用 Nexus 3):

1
docker run -d -p 8081:8081 --name nexus sonatype/nexus3

Nexus 默认访问地址为:http://localhost:8081

挂载卷启动

/nexus-data

docker run -d \
  -p 8081:8081 \
  --name nexus \
  -v /opt/nexus-data:/nexus-data \
  sonatype/nexus3
version: '3'
services:
  nexus:
    image: sonatype/nexus3
    container_name: nexus
    ports:
      - "8081:8081"
    volumes:
      - /opt/nexus-data:/nexus-data
    restart: unless-stopped

2. 登录 Nexus 并创建 PyPI 仓库

登录管理后台

  • 默认账户:admin
  • 密码位置:容器路径 /nexus-data/admin.password

初始化默认密码

创建三个类型的仓库:

a. Hosted 仓库(私有上传包)
  • 名称:pypi-hosted
  • 类型:pypi (hosted)
  • 版本策略:Release
b. Proxy 仓库(代理官方 PyPI)
c. Group 仓库(聚合仓库)
  • 名称:pypi-group
  • 类型:pypi (group)
  • 包含:pypi-hosted, pypi-proxy

注意:pypi-group 配置为 pip 使用的源地址。


二、配置 pip 使用私服

修改配置文件或命令使用私服源:

方法一:修改 ~/.pip/pip.conf (Linux/macOS)

1
2
3
[global]
index-url = http://<nexus-host>:8081/repository/pypi-group/simple/
trusted-host = <nexus-host>

方法二:pip 安装时指定源

1
pip install <package-name> -i http://<nexus-host>:8081/repository/pypi-group/simple/ --trusted-host <nexus-host>

三、上传包到 Nexus PyPI Hosted 仓库

1. 准备上传包

确保目录结构类似:

your_package/
├── setup.py
├── README.md
├── your_module/
│   └── __init__.py

2. 安装打包工具

1
pip install setuptools wheel twine

3. 构建包

1
python setup.py sdist bdist_wheel

生成的文件在 dist/ 目录下。

4. 上传到 Nexus

1
twine upload --repository-url http://<nexus-host>:8081/repository/pypi-hosted/ dist/* --username <your-nexus-user> --password <your-password>

四、可选:配置 ~/.pypirc 简化上传命令

1
2
3
4
5
6
7
8
[distutils]
index-servers =
nexus

[nexus]
repository: http://<nexus-host>:8081/repository/pypi-hosted/
username: <your-nexus-user>
password: <your-password>

上传命令简化为:

1
twine upload -r nexus dist/*

五、常见问题

问题 原因或解决方案
403 Forbidden 上传失败 账号权限不足,检查 Nexus 仓库权限设置
twine 提示认证失败 检查用户名密码或 URL 配置是否正确
pip 安装包找不到 确保 pip 使用的是 group 仓库,且包上传成功