uv-ci-cd-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

uv CI/CD Integration Skill

uv CI/CD 集成指南

Purpose

用途

This skill helps integrate uv (the fast Rust-based Python package manager) into CI/CD pipelines and containerized deployments. It provides proven patterns for GitHub Actions, GitLab CI, Docker, and PyPI publishing that optimize for performance, reliability, and maintainability.
本指南帮助将uv(快速的基于Rust的Python包管理器)集成到CI/CD流水线和容器化部署中。它提供了经过验证的GitHub Actions、GitLab CI、Docker和PyPI发布模式,可优化性能、可靠性和可维护性。

Quick Start

快速开始

GitHub Actions (basic CI workflow):
bash
undefined
GitHub Actions(基础CI工作流):
bash
undefined

Create .github/workflows/ci.yml

创建 .github/workflows/ci.yml

curl -s https://docs.astral.sh/uv/guides/integration/github/ | grep -A 30 "name: CI" > temp.yaml

**Docker (production build):**
```dockerfile
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

FROM python:3.12-slim
COPY --from=builder /app/.venv /app/.venv
COPY . .
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "myapp"]
GitLab CI (basic pipeline):
bash
undefined
curl -s https://docs.astral.sh/uv/guides/integration/github/ | grep -A 30 "name: CI" > temp.yaml

**Docker(生产构建):**
```dockerfile
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

FROM python:3.12-slim
COPY --from=builder /app/.venv /app/.venv
COPY . .
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "myapp"]
GitLab CI(基础流水线):
bash
undefined

Install uv in before_script, sync dependencies, run tests

在before_script中安装uv,同步依赖,运行测试

curl -LsSf https://astral.sh/uv/install.sh | sh uv sync --all-extras --dev uv run pytest
undefined
curl -LsSf https://astral.sh/uv/install.sh | sh uv sync --all-extras --dev uv run pytest
undefined

Instructions

操作步骤

Step 1: Choose Your CI/CD Platform

步骤1:选择你的CI/CD平台

Identify where your code is deployed:
  1. GitHub Actions - Recommended for GitHub repositories (native support,
    setup-uv
    action)
  2. GitLab CI - For GitLab instances (self-hosted or cloud)
  3. Docker - For containerized deployments (multi-stage builds for optimization)
  4. Other - Jenkins, Cirrus CI, GitHub Enterprise (manual setup required)
For each platform, you'll set up uv installation, dependency caching, and frozen lockfile enforcement.
确定代码的部署平台:
  1. GitHub Actions - 推荐用于GitHub仓库(原生支持
    setup-uv
    动作)
  2. GitLab CI - 适用于GitLab实例(自托管或云版本)
  3. Docker - 用于容器化部署(多阶段构建可优化性能)
  4. 其他平台 - Jenkins、Cirrus CI、GitHub Enterprise(需要手动配置)
针对每个平台,你需要配置uv安装、依赖缓存和冻结锁文件强制策略。

Step 2: Set Up Dependency Caching

步骤2:配置依赖缓存

Why: Cache shared across workflow runs dramatically reduces CI time (10-100x faster warm starts).
GitHub Actions with setup-uv action:
yaml
- name: Install uv
  uses: astral-sh/setup-uv@v6
  with:
    version: "0.9.8"        # Optional: pin specific version
    enable-cache: true      # Enable dependency caching
    cache-dependency-glob: "uv.lock"  # Track changes to this file
GitLab CI with custom cache:
yaml
variables:
  UV_CACHE_DIR: .uv-cache

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .uv-cache
Docker (layer caching):
dockerfile
undefined
原因: 工作流运行之间共享缓存可大幅缩短CI时间(冷启动速度提升10-100倍)。
使用setup-uv动作的GitHub Actions配置:
yaml
- name: Install uv
  uses: astral-sh/setup-uv@v6
  with:
    version: "0.9.8"        # 可选:固定特定版本
    enable-cache: true      # 启用依赖缓存
    cache-dependency-glob: "uv.lock"  # 跟踪该文件的变更
使用自定义缓存的GitLab CI配置:
yaml
variables:
  UV_CACHE_DIR: .uv-cache

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .uv-cache
Docker(分层缓存):
dockerfile
undefined

Layer caching: Only rebuild if pyproject.toml or uv.lock changes

分层缓存:仅在pyproject.toml或uv.lock变更时重新构建

COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project
undefined
COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project
undefined

Step 3: Configure Matrix Testing (Multiple Python Versions)

步骤3:配置矩阵测试(多Python版本)

Why: Test against multiple Python versions to ensure compatibility.
GitHub Actions with matrix:
yaml
strategy:
  matrix:
    python-version: ["3.11", "3.12", "3.13"]
steps:
  - uses: astral-sh/setup-uv@v6
  - run: uv python install ${{ matrix.python-version }}
    env:
      UV_PYTHON: ${{ matrix.python-version }}
  - run: uv sync --all-extras --dev
  - run: uv run pytest
GitLab CI with parallel jobs:
yaml
test:3.11:
  image: python:3.11
  script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - uv sync --all-extras --dev
    - uv run pytest

test:3.12:
  image: python:3.12
  script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - uv sync --all-extras --dev
    - uv run pytest
原因: 针对多个Python版本测试以确保兼容性。
带矩阵的GitHub Actions配置:
yaml
strategy:
  matrix:
    python-version: ["3.11", "3.12", "3.13"]
steps:
  - uses: astral-sh/setup-uv@v6
  - run: uv python install ${{ matrix.python-version }}
    env:
      UV_PYTHON: ${{ matrix.python-version }}
  - run: uv sync --all-extras --dev
  - run: uv run pytest
带并行任务的GitLab CI配置:
yaml
test:3.11:
  image: python:3.11
  script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - uv sync --all-extras --dev
    - uv run pytest

test:3.12:
  image: python:3.12
  script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - uv sync --all-extras --dev
    - uv run pytest

Step 4: Use Frozen Lockfiles in Production

步骤4:在生产环境中使用冻结锁文件

Why: Frozen lockfiles ensure exact reproducibility - prevents unexpected updates.
Command pattern:
bash
undefined
原因: 冻结锁文件确保完全可复现性 - 避免意外更新。
命令模式:
bash
undefined

Fails if lockfile is out of sync with pyproject.toml

如果锁文件与pyproject.toml不同步则失败

uv sync --frozen --no-dev
uv sync --frozen --no-dev

For development environments (interactive)

开发环境(交互式)使用

uv sync --all-extras --dev

**Docker production:** Always use `--frozen` flag
```dockerfile
RUN uv sync --frozen --no-dev --no-install-project
GitHub Actions CI:
yaml
- name: Sync with frozen lockfile
  run: uv sync --frozen --all-extras --dev
Commit
uv.lock
to version control. Update it with
uv lock --upgrade
when ready.
uv sync --all-extras --dev

**Docker生产环境:** 始终使用`--frozen`参数
```dockerfile
RUN uv sync --frozen --no-dev --no-install-project
GitHub Actions CI:
yaml
- name: Sync with frozen lockfile
  run: uv sync --frozen --all-extras --dev
uv.lock
提交到版本控制系统。准备更新时使用
uv lock --upgrade
命令。

Step 5: Implement Production Deployment Patterns

步骤5:实现生产环境部署模式

Multi-stage Docker build (recommended for size/security):
dockerfile
undefined
多阶段Docker构建(推荐用于体积/安全性优化):
dockerfile
undefined

Stage 1: Builder - compile dependencies

阶段1:构建器 - 编译依赖

FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv WORKDIR /app
COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv WORKDIR /app
COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project

Stage 2: Runtime - minimal image with only .venv

阶段2:运行时 - 仅包含.venv的极简镜像

FROM python:3.12-slim
WORKDIR /app COPY --from=builder /app/.venv /app/.venv
FROM python:3.12-slim
WORKDIR /app COPY --from=builder /app/.venv /app/.venv

Copy application code

复制应用代码

COPY . .
COPY . .

Ensure virtual environment is in PATH

确保虚拟环境在PATH中

ENV PATH="/app/.venv/bin:$PATH"
ENV PATH="/app/.venv/bin:$PATH"

Run application

运行应用

CMD ["python", "-m", "myapp"]

**Benefits:**
- Final image ~70% smaller (builder dependencies not included)
- Faster deployments and reduced bandwidth
- Improved security (build tools not in production)
CMD ["python", "-m", "myapp"]

**优势:**
- 最终镜像体积缩小约70%(不包含构建器依赖)
- 部署速度更快,带宽消耗更低
- 安全性提升(生产环境中无构建工具)

Step 6: Set Up PyPI Publishing with Trusted Publishing

步骤6:配置基于可信发布的PyPI发布

Why: Trusted publishing (OIDC) is more secure than static tokens. No need to manage secrets.
GitHub Actions workflow:
yaml
name: Publish

on:
  push:
    tags:
      - "v*"

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Required for OIDC/trusted publishing
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v6

      - name: Build distributions
        run: uv build

      - name: Publish to PyPI
        run: uv publish
        # No credentials needed - uses OIDC tokens
Setup in PyPI (one-time):
  1. Go to https://pypi.org/manage/account/
  2. Add "Trusted Publisher" for your GitHub repository
  3. Set trusted publisher to your GitHub organization/repository + workflow name
For custom index/private PyPI:
yaml
- name: Publish to custom index
  run: uv publish --index-url https://example.org/pypi
  env:
    UV_PUBLISH_TOKEN: ${{ secrets.CUSTOM_PYPI_TOKEN }}
原因: 可信发布(OIDC)比静态令牌更安全,无需管理密钥。
GitHub Actions工作流:
yaml
name: Publish

on:
  push:
    tags:
      - "v*"

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # OIDC/可信发布所需
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v6

      - name: Build distributions
        run: uv build

      - name: Publish to PyPI
        run: uv publish
        # 无需凭据 - 使用OIDC令牌
PyPI端一次性配置:
  1. 访问https://pypi.org/manage/account/
  2. 为你的GitHub仓库添加「可信发布者」
  3. 将可信发布者设置为你的GitHub组织/仓库 + 工作流名称
自定义索引/私有PyPI配置:
yaml
- name: Publish to custom index
  run: uv publish --index-url https://example.org/pypi
  env:
    UV_PUBLISH_TOKEN: ${{ secrets.CUSTOM_PYPI_TOKEN }}

Examples

示例

Example 1: Complete GitHub Actions CI Workflow

示例1:完整的GitHub Actions CI工作流

See
examples/github-actions-complete.yml
for a production-ready workflow including:
  • uv installation with caching
  • Multiple Python version matrix
  • Linting, type checking, testing
  • Coverage reporting
  • Dependency vulnerability scanning
查看
examples/github-actions-complete.yml
获取生产级工作流,包括:
  • 带缓存的uv安装
  • 多Python版本矩阵
  • 代码检查、类型校验、测试
  • 覆盖率报告
  • 依赖漏洞扫描

Example 2: Docker Development Environment

示例2:Docker开发环境

See
examples/dockerfile-development
for a development-optimized Dockerfile that includes:
  • uv installation with all dev dependencies
  • Source code mounting for hot reload
  • All development tools (linters, type checkers, test frameworks)
查看
examples/dockerfile-development
获取优化开发体验的Dockerfile,包括:
  • 包含所有开发依赖的uv安装
  • 源代码挂载以支持热重载
  • 所有开发工具(代码检查器、类型校验器、测试框架)

Example 3: GitLab CI Pipeline Configuration

示例3:GitLab CI流水线配置

See
examples/gitlab-ci-complete.yml
for a complete GitLab CI setup including:
  • Matrix testing across Python versions
  • Parallel jobs for linting and testing
  • Cache optimization
  • Test coverage artifacts
查看
examples/gitlab-ci-complete.yml
获取完整的GitLab CI配置,包括:
  • 跨Python版本的矩阵测试
  • 代码检查和测试的并行任务
  • 缓存优化
  • 测试覆盖率产物

Example 4: PyPI Publishing Workflow

示例4:PyPI发布工作流

See
examples/pypi-publishing-workflow.yml
for:
  • Trusted publishing (OIDC) setup
  • Automated versioning from git tags
  • Publication to both PyPI and test PyPI
  • Release notes generation
查看
examples/pypi-publishing-workflow.yml
获取:
  • 可信发布(OIDC)配置
  • 基于Git标签的自动版本控制
  • 同时发布到PyPI和测试PyPI
  • 发布说明生成

Requirements

要求

System Requirements

系统要求

  • Git repository: GitHub, GitLab, or another CI/CD platform
  • uv available: Version 0.9.0 or later (action/installation script ensures this)
  • Docker (if using container deployments): Docker 20.10+ for multi-stage builds
  • lockfile:
    uv.lock
    must be committed to version control
  • Git仓库:GitHub、GitLab或其他CI/CD平台
  • uv可用:版本0.9.0或更高(动作/安装脚本会确保满足要求)
  • Docker(如果使用容器部署):Docker 20.10+以支持多阶段构建
  • 锁文件
    uv.lock
    必须提交到版本控制系统

Credentials (Optional)

凭据(可选)

  • PyPI Token (only for legacy token auth): Create at https://pypi.org/manage/account/publishing/
    • Better approach: Use trusted publishing (OIDC) - no credentials needed
  • Private PyPI credentials (if using custom index): Configure via environment variables or keyring
  • PyPI令牌(仅用于传统令牌认证):在https://pypi.org/manage/account/publishing/创建
    • 更优方案:使用可信发布(OIDC) - 无需凭据
  • 私有PyPI凭据(如果使用自定义索引):通过环境变量或密钥环配置

Python Versions

Python版本

  • Tested: Python 3.11, 3.12, 3.13
  • Minimum: Python 3.9 (for uv itself), but recommend 3.11+
  • Pin in
    .python-version
    : Create with
    uv python pin 3.12
  • 已测试:Python 3.11、3.12、3.13
  • 最低要求:Python 3.9(uv本身的要求),但推荐使用3.11+
  • .python-version
    中固定版本
    :使用
    uv python pin 3.12
    命令创建

See Also

相关链接

  • examples/github-actions-complete.yml - Full CI workflow with all features
  • examples/dockerfile-development - Development container setup
  • examples/gitlab-ci-complete.yml - GitLab CI pipeline
  • examples/pypi-publishing-workflow.yml - Publishing automation
  • references/cache-optimization.md - Cache strategies and tuning
  • references/docker-patterns.md - Advanced Docker patterns
  • references/troubleshooting.md - Common issues and solutions
  • examples/github-actions-complete.yml - 包含所有功能的完整CI工作流
  • examples/dockerfile-development - 开发容器配置
  • examples/gitlab-ci-complete.yml - GitLab CI流水线配置
  • examples/pypi-publishing-workflow.yml - 发布自动化工作流
  • references/cache-optimization.md - 缓存策略与调优
  • references/docker-patterns.md - 高级Docker模式
  • references/troubleshooting.md - 常见问题与解决方案