Skip to content

Lesson 56 of 59Production

CI/CD for Python

Build a GitHub Actions pipeline that lints, type checks and tests against Postgres, builds a Docker image and deploys main automatically.

17 min read0/5 questions

On a team, "it works on my machine" is not a status anyone accepts. Every pull request needs the same checks run the same way, on a clean machine, before anyone reviews it, and every merge to main should reach production without someone typing commands from memory. That is CI/CD. In this lesson you build a complete GitHub Actions pipeline for a FastAPI service with uv, Ruff, a type checker, pytest against a real Postgres, a Docker image and a deploy, then lock main so nothing skips it.

CI, CD and the pipeline

Continuous integration (CI) means every change is merged often and checked automatically: install, lint, type check, test. Continuous delivery means every change that passes is packaged and ready to release; continuous deployment goes one step further and releases it automatically. The checks run in a pipeline, a series of stages where each one only runs if the previous passed.

The pipeline you will build
Pull request: or push to mainPull requestor push to mainLint + types: ruff, mypyLint + typesruff, mypyTests: pytest + PostgresTestspytest + PostgresBuild image: tag = commit SHABuild imagetag = commit SHARegistry: ghcr.ioRegistryghcr.ioDeploy: main onlyDeploymain onlypasspasspushmain only

Every pull request starts two parallel jobs. Fast feedback: lint fails in seconds, tests in a minute or two.

1/4

How GitHub Actions is organised

Workflows are YAML files in .github/workflows/. Each has triggers (on: push, pull request, a schedule), jobs that run on fresh virtual machines called runners, and steps inside each job that run commands or reusable actions like actions/checkout. Jobs run in parallel unless one declares needs: another.

Where CI config lives
  • todo-api/
  • .github/
  • workflows/
  • ci.ymllint, test, build, deploy
  • .pre-commit-config.yamlsame checks, locally
  • app/
  • tests/
  • alembic/
  • Dockerfile
  • pyproject.tomltool config for ruff, mypy, pytest
  • uv.lockexact versions CI installs

The checks job

.github/workflows/ci.yml
name: CI
 
on:
  pull_request:
  push:
    branches: [main]
 
permissions:
  contents: read
 
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6     # check for the current major version
        with:
          enable-cache: true
      - run: uv sync --locked
      - run: uv run ruff check .
      - run: uv run ruff format --check .
      - run: uv run mypy app

uv sync --locked installs exactly what uv.lock says and fails if the lockfile is out of date with pyproject.toml, which catches the classic "added a dependency, forgot to commit the lock" mistake. ruff format --check fails instead of rewriting files, because CI should report problems, not fix them silently. uv installs the Python version your project asks for (from .python-version or requires-python), so local and CI match.

Caching. enable-cache: true stores uv's download cache between runs, keyed on your lockfile, so a run with unchanged dependencies skips most downloads. When uv.lock changes, the key changes and the cache rebuilds. You get this without writing any cache configuration yourself.

Tests against a real Postgres

Tests that touch the database should run against the same database engine as production. Actions can start a service container next to your job:

.github/workflows/ci.yml (continued)
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: app
          POSTGRES_PASSWORD: app
          POSTGRES_DB: app_test
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U app"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    env:
      DATABASE_URL: postgresql+psycopg://app:app@localhost:5432/app_test
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
        with:
          enable-cache: true
      - run: uv sync --locked
      - run: uv run alembic upgrade head
      - run: uv run pytest --cov=app --cov-report=term-missing

The options health check makes the job wait until Postgres accepts connections, so the first test does not fail with "connection refused". Running alembic upgrade head before tests also proves your migrations apply cleanly to an empty database. The password in this file is fine because the database is thrown away after the job; real secrets never go in YAML.

Quick check
Your job runs directly on the runner (no container: key) and maps the Postgres service with ports: ["5432:5432"]. Which host should DATABASE_URL use?
Need a nudge? A hint rules out a wrong answer.

Build the image and deploy main

.github/workflows/ci.yml (continued)
  build:
    needs: [lint, test]
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          push: ${{ github.ref == 'refs/heads/main' }}
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
 
  deploy:
    needs: [build]
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production
    concurrency: production
    steps:
      - run: curl --fail -X POST "$DEPLOY_HOOK_URL"
        env:
          DEPLOY_HOOK_URL: ${{ secrets.DEPLOY_HOOK_URL }}

A few details carry most of the value:

  • needs makes build wait for both checks, and deploy wait for build. On a pull request the image is built (proving the Dockerfile still works) but not pushed, and deploy is skipped by its if.
  • Docker layer cache (type=gha) stores image layers in GitHub's cache. Combined with the Dockerfile from the deploying lesson, which installs dependencies before copying code, a code-only change rebuilds in seconds.
  • The SHA tag means production runs an image you can name exactly, and rolling back is redeploying the previous SHA.
  • environment: production lets you attach production-only secrets and, if you want, require a manual approval. concurrency stops two deploys from racing each other.
  • The deploy step is platform specific. Render, Railway and Fly.io accept a deploy hook or CLI command; on AWS you would update the ECS service to the new image. Prefer OIDC over long-lived cloud keys: the workflow gets a short-lived credential for each run, so there is no static key to leak. Your cloud provider's docs show the exact setup.
  • permissions at the top gives every job read-only access by default; build asks for packages: write only because it pushes to the registry. Least privilege limits the damage if a third-party action is ever compromised.

Database migrations need care in the deploy. Run them as a release step before new code starts (many platforms have a "pre-deploy command"), and keep each migration compatible with the old code still running during the rollout.

To see how Actions decides what runs when, here is the needs graph scheduled in waves, the way the runner does it:

Pythonneeds_graph.py
from graphlib import TopologicalSorter jobs = { "lint": [], "test": [], "build": ["lint", "test"], "deploy": ["build"],} sorter = TopologicalSorter(jobs)sorter.prepare()wave = 1while sorter.is_active(): ready = sorted(sorter.get_ready()) # every job whose needs are done note = " (in parallel)" if len(ready) > 1 else "" print(f"wave {wave}: {', '.join(ready)}{note}") sorter.done(*ready) wave += 1
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

Add "audit": [] (a pip-audit job with no needs) and change build to need ["lint", "test", "audit"]. What does the program print for wave 1?

jobs = {"lint": [], "test": [], "audit": [], "build": ["lint", "test", "audit"], "deploy": ["build"]}
Need a nudge? Hints walk you through it.

Keep the pipeline fast and trustworthy

A pipeline people wait twenty minutes for gets bypassed, and one that fails randomly gets ignored. Aim for pull request checks that finish in a few minutes, and treat speed and reliability as features of the codebase.

  • Fail fast. Put the cheapest checks first or in their own job. Ruff takes seconds; there is no reason to wait for a full test run to learn about an unused import.
  • Fix flaky tests immediately. A test that sometimes fails teaches everyone to click "re-run" without reading the error. Find the cause (shared state between tests, real clocks, network calls, test ordering) or quarantine the test with a tracked issue. Never leave it red and ignored.
  • Split slow suites. Mark slow tests with a pytest marker and run them in a separate job, or shard the suite across several runners when it grows.
  • Test a matrix only when you need one. An application deploys on one Python version, so test that one. A library others install should test every supported version with strategy: matrix: python-version: ["3.12", "3.13"] and pass the version to uv.
  • Run scheduled jobs. An on: schedule trigger with a cron expression can run pip-audit every night, because new vulnerabilities are published against code that has not changed.
  • Know what forks can see. Pull requests from forks do not receive your repository secrets by default. That is deliberate: otherwise anyone could open a pull request that prints them. Keep checks that need secrets out of the pull request path.

Protect main

A pipeline only helps if nobody can skip it. In your repository settings, add a branch protection rule or ruleset for main:

  • Require a pull request before merging, with at least one approving review.
  • Require status checks to pass, and pick the lint and test jobs as required checks. The merge button stays disabled until they are green.
  • Require branches to be up to date before merging, so checks ran against the latest main, not a stale base.
  • Block force pushes and deletion of main.

A CODEOWNERS file in .github/ can also require a review from a specific person or team when certain paths change, for example the alembic/ folder or the workflow files themselves. Protecting the workflow files matters: a pull request that edits ci.yml could otherwise quietly remove a check.

Teams then add the same Ruff and type checks as pre-commit hooks, so most problems are caught in seconds on the developer's machine and CI is the safety net, not the first line of feedback.

Put it in order5 steps

Order the life of a change from branch to production.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each workflow setting to what it does.

Choose an item, then its match on the other side.
Quick check
CI runs on every pull request, but someone merged a PR with failing tests last week. What setting was missing?
Need a nudge? A hint rules out a wrong answer.
Key terms
continuous integration
Merging changes often and checking each one automatically with linting, type checks and tests.
continuous deployment
Automatically releasing every change that passes the pipeline to production.
runner
The fresh virtual machine GitHub Actions starts to run one job.
service container
A container, such as Postgres, that Actions starts alongside a job for tests to use.
required check
A CI job that must pass before branch protection allows a pull request to merge.
image tag
A name for one built image. Tagging with the commit SHA makes deploys traceable and rollbacks easy.
OIDC
Letting a workflow exchange a short-lived token for cloud credentials instead of storing long-lived keys.