On this page

FastAPI CI/CD: GitHub Actions Testing & Deployment Guide

Published on August 17, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A CI/CD pipeline automates the two most repetitive and error-prone parts of software delivery: verifying that new code does not break anything (Continuous Integration), and shipping that code to a running server (Continuous Deployment). Without automation, every code change requires a developer to manually run the test suite, build a Docker image, push it to a registry, SSH into the server, pull the image, and restart the container. This takes time, introduces human error, and — critically — it often does not happen at all under deadline pressure. Continuous Integration runs the test suite automatically on every push and pull request, catching broken code within minutes before it reaches the main branch. Continuous Deployment automates the delivery of passing code to a running environment — a developer creates a version tag, the pipeline builds and ships the image, and the server is updated with no manual steps. This guide builds a complete pipeline for a FastAPI application: a CI workflow that runs tests on every push and pull request, and a CD workflow that builds, tags, and pushes a Docker image on every versioned release, then deploys it to a server via SSH.


GitHub Actions Concepts​

GitHub Actions is GitHub's built-in CI/CD platform. It executes workflows — YAML files stored in .github/workflows/ — in response to repository events. Every workflow consists of:


Workflow File Structure​


project/

├── .github/

│   └── workflows/

│       ├── ci.yml          # runs tests on push and PRs

│       └── cd.yml          # builds Docker image and deploys on version tags

├── app/

├── tests/

├── requirements.txt

├── requirements-dev.txt    # dev-only dependencies: pytest, httpx, ruff, mypy

└── Dockerfile

Separating requirements.txt (production) from requirements-dev.txt (development and CI) means the Docker image stays lean — it never installs test tools or linters [5†L7-L8].

📄 requirements-dev.txt


-r requirements.txt        # include all production dependencies

pytest>=8.0.0,<9.0.0

httpx>=0.27.0,<1.0.0

pytest-cov>=5.0.0,<6.0.0

ruff>=0.4.0,<1.0.0

mypy>=1.10.0,<2.0.0

Workflow 1: Continuous Integration​

This workflow runs on every push to any branch and on every pull request targeting main. It gives developers immediate feedback on feature branches — before they even open a PR [0†L21-L24][7†L16-L19].

📄 .github/workflows/ci.yml


name: CI – Test and Lint



on:

  push:

    branches:

      - "**" # all branches, not just main

  pull_request:

    branches:

      - main



jobs:

  test:

    name: Test (Python ${{ matrix.python-version }})

    runs-on: ubuntu-latest



    strategy:

      fail-fast: false # run all matrix jobs even if one fails

      matrix:

        python-version: ["3.11", "3.12", "3.13"]



    steps:

      - name: Checkout repository

        uses: actions/checkout@v4



      - name: Set up Python ${{ matrix.python-version }}

        uses: actions/setup-python@v5

        with:

          python-version: ${{ matrix.python-version }}

          cache: "pip" # built-in pip caching — speeds CI by 60–80%

          cache-dependency-path: | # invalidate cache when either file changes

            requirements.txt

            requirements-dev.txt



      - name: Install dependencies

        run: |

          python -m pip install --upgrade pip

          pip install -r requirements-dev.txt



      - name: Lint with Ruff

        run: ruff check app/ tests/



      - name: Type check with Mypy

        run: mypy app/ --ignore-missing-imports



      - name: Run tests with coverage

        env:

          PYTHONPATH: ${{ github.workspace }} # ensures app/ is importable

          DATABASE_URL: "sqlite://" # in-memory DB for CI

          JWT_SECRET_KEY: "ci-test-secret-key"

        run: |

          pytest tests/ -v \

            --cov=app \

            --cov-report=term-missing \

            --cov-report=xml:coverage.xml



      - name: Upload coverage report

        uses: actions/upload-artifact@v4

        if: matrix.python-version == '3.13' # upload once, from the latest Python

        with:

          name: coverage-report

          path: coverage.xml

          retention-days: 7

Why PYTHONPATH must be set​

The most common reason CI tests fail when local tests pass is that the project root is not on sys.path in the runner. Without PYTHONPATH: ${{ github.workspace }}, importing from app.main import app raises ModuleNotFoundError even though the file exists [1†L8-L9][1†L18-L21]. Setting PYTHONPATH to the workspace root makes every package under it importable. The most robust alternative is to configure this in pyproject.toml with [tool.pytest.ini_options] pythonpath = ["."], but setting it directly in the workflow env is explicit and avoids any risk of the configuration being overlooked [1†L20-L21].

Why the matrix tests three Python versions​

An application that runs correctly on Python 3.11 may silently break on 3.13 due to deprecated standard library usage, changed default behaviours, or package incompatibilities. The matrix tests all three supported versions on every CI run. fail-fast: false ensures that if 3.11 fails, the 3.12 and 3.13 jobs still complete, giving a complete picture rather than stopping at the first failure.

Why cache: "pip" matters​

Without caching, every CI run reinstalls every package from scratch. For a project with a dozen dependencies, this takes 60–90 seconds. With the built-in pip cache on setup-python@v5, the second and subsequent runs restore packages from cache in 5–10 seconds — the cache is keyed on the hash of requirements.txt and requirements-dev.txt, so it is invalidated automatically when dependencies change [5†L7-L8][5†L21-L22].

Why Ruff instead of Flake8​

Ruff is a Python linter and formatter written in Rust. It is 10–100× faster than Flake8 and covers the same rules plus many more. It has become the current standard in new Python projects. A CI step that runs in 0.2 seconds instead of 3 seconds across hundreds of runs saves meaningful time.


Workflow 2: Continuous Deployment​

The CD workflow triggers only when a Git tag matching v*.*.* is pushed — a semantic version tag like v1.2.0 [6†L11]. It:

  1. Builds the Docker image
  2. Tags it with both the version number and latest
  3. Pushes both tags to Docker Hub
  4. SSHes into the production server and restarts the container with the new image

📄 .github/workflows/cd.yml


name: CD – Build, Push, and Deploy



on:

  push:

    tags:

      - "v*.*.*" # triggers on v1.0.0, v1.2.3, v2.0.0-rc.1, etc.



jobs:

  build-and-push:

    name: Build and Push Docker Image

    runs-on: ubuntu-latest



    steps:

      - name: Checkout repository

        uses: actions/checkout@v4



      - name: Log in to Docker Hub

        uses: docker/login-action@v3

        with:

          username: ${{ secrets.DOCKER_USERNAME }}

          password: ${{ secrets.DOCKER_PASSWORD }}



      - name: Extract metadata for Docker

        id: meta

        uses: docker/metadata-action@v5

        with:

          images: ${{ secrets.DOCKER_USERNAME }}/taskmanager

          tags: |

            type=semver,pattern={{version}}   # e.g. 1.2.3

            type=semver,pattern={{major}}.{{minor}}  # e.g. 1.2

            type=raw,value=latest             # always update latest tag



      - name: Build and push Docker image

        uses: docker/build-push-action@v5

        with:

          context: .

          push: true

          tags: ${{ steps.meta.outputs.tags }}

          labels: ${{ steps.meta.outputs.labels }}

          cache-from: type=gha # use GitHub Actions cache for Docker layers

          cache-to: type=gha,mode=max



  deploy:

    name: Deploy to Production

    runs-on: ubuntu-latest

    needs: build-and-push # only runs if build-and-push succeeded



    steps:

      - name: Deploy via SSH

        uses: appleboy/ssh-action@v1

        with:

          host: ${{ secrets.SSH_HOST }}

          username: ${{ secrets.SSH_USERNAME }}

          key: ${{ secrets.SSH_PRIVATE_KEY }}

          script: |

            cd /opt/taskmanager

            docker pull ${{ secrets.DOCKER_USERNAME }}/taskmanager:latest

            docker-compose up -d --no-deps app

            docker image prune -f

What docker/metadata-action does​

docker/metadata-action@v5 reads the Git tag and generates the correct Docker image tags automatically. Pushing v1.2.3 produces three image tags: 1.2.3, 1.2, and latest [4†L17-L18][4†L22-L23]. Without this action, developers must manually compose tag strings and frequently forget to update the latest tag, breaking any deployment that pulls by that tag.

Why cache-from: type=gha and cache-to: type=gha​

Docker build layers are cached by default on a developer's machine, making rebuilds fast. In CI, every run starts with a fresh runner and a cold cache. type=gha stores Docker layer cache in GitHub Actions' cache storage and restores it on the next run [2†L11-L13][2†L29-L30]. For a project where only the source code changes frequently, this eliminates most of the build time — the base image and dependency layers are restored from cache, and only the final COPY app/ /code/app layer rebuilds. The mode=max setting ensures the cache includes all layers, not just the final image.

Why the deploy job uses needs: build-and-push​

needs: creates an explicit dependency between jobs. The deploy job only starts if build-and-push succeeded. Without this, GitHub Actions runs both jobs in parallel — the deployment would begin before the image is available in Docker Hub.

The SSH deployment step​

appleboy/ssh-action@v1 opens an SSH connection to the production server using a private key stored in GitHub Secrets and executes the deployment script [3†L37-L38]. The script:

  1. Changes to the project directory where docker-compose.yml lives
  2. Pulls the new latest image from Docker Hub
  3. Restarts only the app service with --no-deps (database and monitoring containers are unaffected)
  4. Prunes dangling images to reclaim disk space

Configuring GitHub Secrets​

Secrets are encrypted at rest and never exposed in workflow logs. Configure them in the repository under Settings → Secrets and variables → Actions → New repository secret.

Secret nameValueDOCKER_USERNAMEYour Docker Hub usernameDOCKER_PASSWORDA Docker Hub access token (not your password — generate under Account Settings → Security)SSH_HOSTThe IP address or hostname of your production serverSSH_USERNAMEThe SSH username on the server (e.g., ubuntu on AWS EC2)SSH_PRIVATE_KEYThe entire contents of your SSH private key file (the ~/.ssh/id_rsa content)

Use a Docker Hub access token rather than your account password. Access tokens are scoped to specific permissions, can be revoked individually, and do not expose your account login.


Semantic Versioning and Tagging​

Semantic versioning communicates the nature of changes using a MAJOR.MINOR.PATCH number:

SegmentIncremented whenMAJORBreaking changes — existing clients must updateMINORNew features, backward-compatiblePATCHBug fixes, no new features

Create and push a tag to trigger the CD pipeline:


# Tag the current commit

git tag v1.0.0



# Push the tag to GitHub — this triggers the CD workflow

git push origin v1.0.0

To tag a specific past commit:


git tag v1.0.1 abc1234   # abc1234 is the commit hash

git push origin v1.0.1

To list all existing tags:


git tag --list

To delete a tag locally and remotely (for example, after a failed release):


git tag --delete v1.0.0

git push origin --delete v1.0.0

Protecting the main Branch​

Branch protection rules prevent broken code from reaching main by requiring the CI checks to pass before a pull request can be merged.

In the repository go to Settings → Branches → Add rule:

With these rules in place, a pull request that fails any CI test cannot be merged — not even by an administrator.


Complete Pipeline Flow​


Developer pushes a feature branch

        │

        ▼

CI workflow fires on push

  ├── Lint (Ruff)

  ├── Type check (Mypy)

  └── Test (Python 3.11, 3.12, 3.13 in parallel)

        │

        ▼ (all checks pass)

Developer opens pull request → CI fires again

        │

        ▼ (checks pass)

Pull request is approved → merged to main

        │

        ▼

Developer creates and pushes v1.x.x tag

        │

        ▼

CD workflow fires on tag

  ├── Job 1: build-and-push

  │     ├── Build Docker image (with layer cache)

  │     └── Push taskmanager:1.x.x and taskmanager:latest to Docker Hub

  │

  └── Job 2: deploy (runs after Job 1 succeeds)

        ├── SSH into production server

        ├── Pull new image

        ├── Restart app container

        └── Prune old images

Common Mistakes to Avoid​

Using outdated action versions. actions/checkout@v3, actions/setup-python@v4, and docker/login-action@v2 produce deprecation warnings and will eventually stop working. Always use the current stable version of each action — @v4, @v5, and @v3 respectively.

Installing pytest in the workflow instead of requirements-dev.txt. Ad-hoc installs create version inconsistency between local runs and CI. Every development dependency belongs in a versioned dev requirements file.

Not setting PYTHONPATH in the CI environment. The most common cause of ModuleNotFoundError in CI when tests pass locally. Set PYTHONPATH: ${{ github.workspace }} as an environment variable on the test step [1†L8-L9].

Pushing only the version tag without latest. Deployments that pull taskmanager:latest will use an outdated image. Use docker/metadata-action to push both tags simultaneously.

Storing SSH credentials or Docker tokens as plain text in the workflow file. Anything hardcoded in a workflow file is visible in the repository. Always use ${{ secrets.SECRET_NAME }} for credentials.

Running the deploy job in parallel with build-and-push. Without needs: build-and-push, the deployment starts before the image is available in Docker Hub and fails. Always declare the dependency explicitly.

Not pruning old Docker images on the server. Each deployment pulls a new image but leaves old ones consuming disk space. docker image prune -f in the deployment script removes dangling images automatically.


Practice Challenge​

Frequently Asked Questions​

What is the difference between Continuous Integration and Continuous Deployment?

Continuous Integration (CI) automatically runs the test suite, linter, and type checker on every push and pull request, catching broken code within minutes before it reaches main. Continuous Deployment (CD) automatically builds and ships passing code to a running environment — building a Docker image, pushing it to a registry, and restarting the server. CI answers whether the code is correct. CD answers whether the correct code reached production.

How do I create a GitHub Actions workflow for FastAPI?

Create a YAML file inside .github/workflows/ in your repository. Define the on trigger (push, pull_request, or a tag pattern), declare one or more jobs each with a runs-on runner, and list the steps: checkout the repository with actions/checkout@v4, set up Python with actions/setup-python@v5, install dependencies, and run pytest. GitHub detects and executes any workflow file in that directory automatically.

Why do my FastAPI tests pass locally but fail in GitHub Actions with ModuleNotFoundError?

The project root is not on sys.path in the GitHub Actions runner by default. Without it, import statements like from app.main import app raise ModuleNotFoundError even though the files exist. Fix this by adding PYTHONPATH: ${{ github.workspace }} as an environment variable on the test step. This makes every package under the workspace root importable, matching the behaviour of a local environment where you typically run pytest from the project root.

How do I speed up GitHub Actions by caching pip dependencies?

Use the built-in caching in actions/setup-python@v5 by setting cache: 'pip' and pointing cache-dependency-path at both requirements.txt and requirements-dev.txt. GitHub Actions stores the installed packages and restores them on subsequent runs, reducing dependency installation from 60-90 seconds to 5-10 seconds. The cache is invalidated automatically whenever either requirements file changes.

What GitHub Actions versions should I use for a FastAPI project?

Use actions/checkout@v4, actions/setup-python@v5, docker/login-action@v3, docker/build-push-action@v5, docker/metadata-action@v5, and actions/upload-artifact@v4. Earlier versions such as checkout@v3 and setup-python@v4 produce deprecation warnings and will eventually stop working. Always use the current stable major version of each action.

How do I push a Docker image to Docker Hub with GitHub Actions?

Use three actions in sequence: docker/login-action@v3 to authenticate using secrets.DOCKER_USERNAME and secrets.DOCKER_PASSWORD, docker/metadata-action@v5 to generate image tags from the Git ref, and docker/build-push-action@v5 with push: true and the generated tags. Store Docker Hub credentials as encrypted GitHub Secrets, never as plaintext in the workflow file.

How do I tag a Docker image with both a version number and latest in GitHub Actions?

Use docker/metadata-action@v5 with multiple tag patterns. Configure type=semver,pattern={{version}} to produce the version number (e.g. 1.2.3), type=semver,pattern={{major}}.{{minor}} for the minor version (e.g. 1.2), and type=raw,value=latest to always update the latest tag. Pass the generated tags to docker/build-push-action@v5 via steps.meta.outputs.tags. This pushes all three tags in a single build step.

What does docker/metadata-action do in a GitHub Actions CD pipeline?

docker/metadata-action reads the Git tag or branch that triggered the workflow and generates the correct Docker image tag names automatically. When a v1.2.3 tag is pushed, it produces 1.2.3, 1.2, and latest as image tags. It also generates Open Container Initiative labels with build metadata. Without it, developers must manually compose tag strings and frequently forget to update the latest tag.

How do I make a GitHub Actions job wait for another job to finish?

Add needs: job-name to the dependent job. For example, adding needs: build-and-push to the deploy job ensures deployment only starts after the build succeeds. Without needs, GitHub Actions runs all jobs in a workflow in parallel by default. A deploy job running in parallel with the build would attempt to pull an image that does not exist in Docker Hub yet.

How do I deploy a FastAPI Docker container via SSH from GitHub Actions?

Use the appleboy/ssh-action@v1 action with the server host, SSH username, and private key stored as GitHub Secrets. In the script parameter, write the deployment commands: pull the new image with docker pull, restart only the application service with docker-compose up -d --no-deps app, and clean up old images with docker image prune -f. The action opens an SSH connection, executes the script on the server, and closes the connection.

What GitHub Secrets do I need for a FastAPI CI/CD pipeline with Docker and SSH?

You need DOCKER_USERNAME (your Docker Hub username), DOCKER_PASSWORD (a Docker Hub access token, not your account password), SSH_HOST (the server IP address or hostname), SSH_USERNAME (the login user on the server, such as ubuntu on AWS EC2), and SSH_PRIVATE_KEY (the full contents of your SSH private key file). Configure these in the repository under Settings, Secrets and variables, Actions.

Should I use a Docker Hub password or access token in GitHub Actions?

Always use a Docker Hub access token, not your account password. Access tokens are generated under Docker Hub Account Settings and can be scoped to read-only or read-write permissions. They can be revoked individually without changing your account password. If a token is compromised, you revoke it and generate a new one without affecting your account login or other tokens.

How do I trigger a GitHub Actions deployment only on version tags?

Use a tag pattern in the on.push.tags trigger: tags: ['v*.*.*']. This matches any tag beginning with v followed by three dot-separated numbers, such as v1.0.0, v1.2.3, or v2.0.0-rc.1. The workflow does not run on regular branch pushes or commits — only when a matching tag is pushed with git tag v1.0.0 followed by git push origin v1.0.0.

What is semantic versioning and how does it apply to FastAPI deployments?

Semantic versioning uses a MAJOR.MINOR.PATCH numbering scheme. MAJOR increments for breaking changes that require clients to update. MINOR increments for new backward-compatible features. PATCH increments for bug fixes. Applying it to FastAPI deployments means pushing v1.1.0 when a new endpoint is added and v1.1.1 when a bug in that endpoint is fixed. The CD pipeline triggers on any v-prefixed tag and the Docker image is tagged with the same version number.

How do I test against multiple Python versions in GitHub Actions?

Use a strategy matrix with a python-version list: matrix: python-version: ['3.11', '3.12', '3.13']. GitHub Actions runs one job instance per matrix entry in parallel. Set fail-fast: false so that if one Python version fails, the others continue running and produce a complete picture of compatibility. Reference the current version in steps with ${{ matrix.python-version }}.

How do I protect the main branch from broken code in GitHub?

In the repository go to Settings, Branches, and add a branch protection rule for main. Enable Require status checks to pass before merging and select the CI job names from your workflow — such as test (3.11), test (3.12), and test (3.13). Enable Require branches to be up to date before merging and Do not allow bypassing the above settings. With these rules, no pull request can be merged until all selected checks pass, even for repository administrators.

What is the difference between requirements.txt and requirements-dev.txt in a FastAPI CI/CD project?

requirements.txt contains only the packages the running application needs in production — FastAPI, SQLModel, Uvicorn, and similar runtime dependencies. requirements-dev.txt includes production dependencies via -r requirements.txt and adds development-only tools: pytest, httpx, pytest-cov, ruff, and mypy. The Docker image installs only requirements.txt, keeping it lean. The CI workflow installs requirements-dev.txt to have access to all testing and linting tools.

Why should I use Ruff instead of Flake8 for linting in GitHub Actions?

Ruff is a Python linter written in Rust that runs 10 to 100 times faster than Flake8 while covering the same rules and many additional ones. In a CI pipeline that runs on every push, a linting step that completes in 0.2 seconds instead of 3 seconds accumulates into meaningful time savings across hundreds of runs. Ruff also replaces isort, pyupgrade, and several Flake8 plugins in a single tool with one configuration file.

How do I cache Docker build layers in GitHub Actions?

Add cache-from: type=gha and cache-to: type=gha,mode=max to the docker/build-push-action@v5 step. This stores Docker layer cache in GitHub Actions' cache storage and restores it on subsequent runs. Layers that have not changed — the base image pull, pip install, and other stable layers — are restored from cache instead of being rebuilt, significantly reducing build time when only application source code has changed.

Why is my coverage report not appearing in the GitHub Actions artifacts?

Check that the upload step uses if: matrix.python-version == '3.13' to ensure the report is uploaded only once. Also verify that the coverage.xml file is actually generated by the pytest-cov step. Ensure the --cov-report=xml:coverage.xml flag is present and that the path matches the upload step's path field. If the test step fails, the upload step may not run at all unless the if condition accounts for failure status.

How do I debug a failing GitHub Actions workflow without repeatedly pushing code?

Add a step with run: sleep 600 after the failing step to keep the runner alive, then SSH into the runner using the tmate debugging action: uses: mxschmitt/action-tmate@v3. This gives you a live SSH session into the runner where you can inspect files, run commands, and debug interactively. Remove or comment out the step before merging to avoid unnecessary delays.

What should I do if my Docker build fails in GitHub Actions with 'Cannot connect to the Docker daemon'?

This error typically occurs when the runner does not have Docker installed. Use runs-on: ubuntu-latest, which has Docker pre-installed. If you are using a custom runner or a self-hosted runner, ensure Docker is installed and the daemon is running. Also verify that you are not attempting to run Docker commands inside a container step without the docker service available.

Can I use GitHub Actions to run FastAPI tests with a real PostgreSQL database instead of SQLite?

Yes. Use the services key in the workflow to spin up a PostgreSQL container alongside the test job. Define the service with image: postgres:16-alpine, set environment variables for POSTGRES_USER and POSTGRES_PASSWORD, and map the port. Then set DATABASE_URL in the test step to postgresql://user:password@localhost:5432/testdb. The service is reachable at localhost from the job.

How do I manually trigger a deployment without pushing a Git tag?

Add workflow_dispatch: to the on section of the CD workflow. This creates a Run workflow button in the GitHub Actions tab where you can enter inputs such as the version number or the environment to deploy to. Use the inputs context to pass the version to the docker/metadata-action tag generation.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Deploy FastAPI with Docker

Next

Monitoring and Observability