CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
A small notes API, three pytest tests and one ci.yml: GitHub runs the tests on every push and pull request, builds the Docker image only if they pass, and shows a red or green check before anyone merges.
What you will learn
- Explain continuous integration (CI) and what a red or green check means
- Read a GitHub Actions workflow: on, jobs, steps, runs-on and uses
- Make one job wait for another with needs, so the image is built only after the tests pass
- Watch a broken change fail the tests and stop the build
Before you start
- Git and GitHub Fundamentals
- Testing a FastAPI App with pytest
- Containerising a Model API: A Dockerfile
A teammate tidies up a helper function, tries it once, and pushes. The test that would've caught the bug was right there in the project, and nobody ran it. This happens on every team, and the fix fits in three words: every push, checked.
We'll make GitHub test our code and build our Docker image automatically, every time we push. The project is a small notes API with one test file and one workflow file. Along the way you'll meet four things: a workflow, jobs, steps and checks.
An inspector at the gate
Think of a factory gate. The truck is your commit. At the gate, an inspector runs the same checklist on every truck. It doesn't get tired and it doesn't forget. Only after that does the truck get on the open road. In our world, that means only checked code gets merged.
Continuous integration, CI for short, is the inspector. The workflow file is the checklist.
Three tests, one command
First, what will the inspector check? tests/test_notes.py has three tests. The style is the same as in Testing a FastAPI App with pytest: a TestClient calls the app with no server running.
import pytest
from fastapi.testclient import TestClient
from app.main import app, validate_note
client = TestClient(app)
def test_health_route():
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_validate_note_trims_spaces():
assert validate_note(" Buy milk ") == "Buy milk"
def test_validate_note_rejects_empty_title():
with pytest.raises(ValueError):
validate_note(" ")
The first calls /health and expects 200 and ok. The second passes "Buy milk" with spaces around it and expects it back trimmed. The third checks that an empty title raises a ValueError. Here's the function they test, in app/main.py:
def validate_note(title: str) -> str:
"""Trim the title and refuse an empty one."""
title = title.strip()
if not title:
raise ValueError("title must not be empty")
return title
pytest -q
... [100%]
3 passed in 0.79s
That's the exact command the inspector will run for us.
ci.yml: when, and what
The checklist is a plain text file, ci.yml, and it lives in .github/workflows/. GitHub finds it there by itself.
name: CI
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install dependencies
run: pip install -r requirements-dev.txt
- name: Run tests
run: pytest -q
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build the image
run: docker build -t notes-api:ci .
onsays when to run: on every push and every pull request.jobsholds two jobs,testandbuild.runs-on: ubuntu-latestgives each job a fresh Ubuntu machine.- Steps run in order. The test job has four: check out the code, set up Python 3.13, install the packages, run pytest.
needs: testis the important line in build. Build starts only after the tests pass.- Steps that start with
usesare ready-made actions, pinned to a major version (@v4,@v5) so an update doesn't surprise you. Steps withrunare shell commands.
A small helper script in the project, 01_show_workflow.py, reads the file and prints its shape:
workflow: CI
runs on : push, pull_request
job test
1. uses actions/checkout@v4
2. uses actions/setup-python@v5
3. run pip install -r requirements-dev.txt
4. run pytest -q
job build (needs test)
1. uses actions/checkout@v4
2. run docker build -t notes-api:ci .
requirements-dev.txt pulls in the app's requirements plus the test tools:
-r requirements.txt
pytest==9.1.1
httpx==0.28.1
What happens on a push
- Your commit lands on GitHub.
- GitHub sees the push and starts a fresh machine, a clean one every time. Its docs call this a GitHub-hosted runner. That machine reads our workflow file.
- The test job runs first:
pytest -q. - If it passes, the build job runs
docker build. - At the end, a green check shows up on your pull request, so it's safe to merge.
If any step fails, you get a red cross instead, and the later jobs don't even start. They're the same steps you'd run on your laptop. (The test and build outputs in this article come from running those same commands locally; GitHub Actions itself wasn't run for this lesson.) The difference is that they run on a clean machine, every time, without anyone asking.
Break it
Now the teammate's change, from broken/app/main.py. It still checks for an empty title, but look at the return:
def validate_note(title: str) -> str:
"""Trim the title and refuse an empty one."""
if not title.strip():
raise ValueError("title must not be empty")
return title
It returns title as it came in, so the spaces never get trimmed. Same tests, new code:
.F. [100%]
================================== FAILURES ===================================
_______________________ test_validate_note_trims_spaces _______________________
def test_validate_note_trims_spaces():
> assert validate_note(" Buy milk ") == "Buy milk"
E AssertionError: assert ' Buy milk ' == 'Buy milk'
E
E - Buy milk
E + Buy milk
E ? ++ ++
tests\test_notes.py:16: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_notes.py::test_validate_note_trims_spaces - AssertionError:...
1 failed, 2 passed in 1.28s
One failed, two passed. We expected "Buy milk" and got it with the spaces still around it. On a pull request, this shows up as a red cross, and the build job never starts. The bug never reaches the customer.
The build job
The second job builds this Dockerfile:
FROM python:3.13-slim
WORKDIR /srv
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Requirements are copied and installed first, so Docker can reuse that layer when only the code changes, and the app folder goes in last because it changes most. (Containerising a model API walks through a Dockerfile like this line by line.) The build ends by naming the image:
#10 naming to docker.io/library/notes-api:ci 0.0s done
#10 unpacking to docker.io/library/notes-api:ci 1.0s done
#10 DONE 3.5s
If the tests pass, the code is correct. If the image builds too, it's shippable.
Common mistakes
- The file in the wrong folder. It has to be
.github/workflows/, or GitHub never sees it. - Forgetting
needs. Without it, jobs run side by side, and the image gets built even when the tests fail. - Test tools missing on the runner. The runner is empty. Anything pytest needs must be in
requirements-dev.txt. - Unpinned actions. Pin
usesto a version, so a new release doesn't change your checklist overnight.
Recap
| Word | Meaning |
|---|---|
| Workflow | The checklist, .github/workflows/ci.yml |
on | When it runs: push, pull_request |
| Job and steps | A job runs on a fresh machine; its steps run in order |
needs | Sets the order: build waits for test |
| Check | Red cross or green check on the pull request, before merging |
Try it yourself: push the project to your own GitHub repository (see Git and GitHub fundamentals), break one assert on a branch, and open a pull request. Then fix it and watch the check turn green.
Next, the same idea for the model itself: a quality gate in CI/CD.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
Next →CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.