GitHub Actions pipeline for the Python service
Run tests, build the image and push it on every merge to main.
By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.
In short
A GitHub Actions workflow is a YAML file that runs jobs on GitHub's machines when events happen. For the Python service it lints and tests every push and PR, then builds and pushes the image only on main.
Explained simply
GitHub Actions is the CI/CD system built into GitHub. You describe what to do in a YAML file inside the folder .github/workflows. GitHub reads the file and, when something happens (a push, a pull request, a schedule), it starts a fresh virtual machine and runs your steps.
A workflow has jobs, and a job has steps. Each step either runs a shell command with run, or uses a ready-made action with uses, such as actions/checkout to download your code. Jobs run in parallel unless you tell one to wait for another.
For our Python service, every push and pull request should run the linter and the tests. Only when code lands on main should the workflow build the Docker image and push it to a registry. That keeps untested or untrusted code out of your registry.
Passwords and tokens never go in the YAML file. You store them as repository secrets in the GitHub settings and refer to them by name. GitHub hides their values in the logs.
Press Play on a diagram to walk through it one step at a time.
- Developer to GitHub: git push to main1git push to main
- GitHub to Runner: Queue job from ci.yml2Queue job from ci.yml
- Runner to GitHub: Checkout: fetch the code3Checkout: fetch the code
- Runner to GitHub: Logs: lint and pytest pass4Logs: lint and pytest pass
- Runner to Registry: Push image tagged with SHA5Push image tagged with SHA
- Runner to GitHub: Report status: success6Report status: success
- GitHub to Developer: Green check on commit7Green check on commit
- on
- push
- pull_request
- workflow_dispatch
- permissions
- contents: read
- packages: write (build job)
- jobs.test
- runs-on: ubuntu-latest
- steps: checkout, setup-python, pytest
- jobs.build
- needs: test
- if: push to main
- steps: login, build-push
In depth
Triggers, jobs and runners
The on key lists the events that start a workflow. push and pull_request are the common ones, and both can be filtered by branches or paths. workflow_dispatch adds a manual Run button, and schedule runs on a cron expression in UTC.
Each job runs on a runner named by runs-on. GitHub-hosted runners like ubuntu-latest are fresh virtual machines: nothing survives from one run to the next, which is why caching exists. Steps in one job share the same machine and files. Different jobs get different machines, so pass files between them with actions/upload-artifact and actions/download-artifact, or rebuild.
needs makes a job wait for others and skip if they fail. A matrix runs the same job for several values, for example Python 3.11, 3.12 and 3.13, in parallel. concurrency with cancel-in-progress cancels older runs on the same branch when you push again, which saves minutes.
- on: push, pull_request, workflow_dispatch, schedule
- needs: test makes a job wait for the test job
- strategy.matrix runs one job across many versions
- Each job starts on a clean machine
Lint, test and cache in CI
actions/setup-python installs the exact Python version you ask for and puts it on the PATH. Pin a version like "3.12" rather than relying on whatever the runner image ships. Quote it in YAML, because 3.10 without quotes is read as the number 3.1.
With cache: pip, setup-python saves pip's download cache at the end of a run and restores it at the start of the next one. The cache key includes a hash of your requirements files, so changing a dependency creates a new cache automatically. Packages still install, but from local files instead of the internet.
Make test output useful. pytest -q keeps logs short, --maxfail=1 stops early, and --cov with pytest-cov reports coverage. If your tests need Postgres, a job can declare services: postgres, and GitHub starts that container next to the job, reachable on localhost when you map the port.
- Quote Python versions in YAML: "3.10", not 3.10
- cache: pip is keyed on your requirements file hash
- services: starts Postgres or Redis containers for tests
Building and pushing the image only on main
Keep the image build in its own job that needs the test job and has an if condition: github.event_name == 'push' && github.ref == 'refs/heads/main'. Pull requests then run tests but never publish.
For GitHub Container Registry (ghcr.io) you do not need a personal token. Give the job permissions: packages: write and log in with the built-in GITHUB_TOKEN. Docker Hub or ECR need their own credentials stored as secrets, or for AWS, an OIDC role.
The official Docker actions do the heavy work: docker/setup-buildx-action enables BuildKit, docker/login-action logs in, and docker/build-push-action builds and pushes. Add cache-from: type=gha and cache-to: type=gha,mode=max to reuse layers between runs through the GitHub Actions cache. Tag with github.sha so every image maps to exactly one commit.
Security note: pull requests from forks get a read-only GITHUB_TOKEN and no repository secrets, by design.
- 1Event
push or pull_request
- 2test job
ruff and pytest, on every event
- 3if: push to main
PR runs stop here
- 4build job
needs: test; buildx with GHA cache
- 5Push to GHCR
Tagged with github.sha
Status badges, permissions and good hygiene
A status badge is an image that shows whether the workflow passes on a branch. The URL pattern is https://github.com/OWNER/REPO/actions/workflows/ci.yml/badge.svg, and adding ?branch=main shows main only. Put it at the top of the README as an image linked to the Actions page.
Set the least permissions the workflow needs. A top-level permissions: contents: read makes GITHUB_TOKEN read-only, and the build job can add packages: write for itself.
Pin actions to a version tag like actions/checkout@v4, or to a full commit SHA for third-party actions, because a tag can be moved by the action's owner. Set timeout-minutes on jobs; the default limit is 360 minutes, which can burn minutes on a hung test. Finally, protect main with a branch rule that requires the test job to pass before merging.
- Badge: /actions/workflows/ci.yml/badge.svg?branch=main
- Top-level permissions: contents: read
- Pin third-party actions to a commit SHA
- Add timeout-minutes to every job
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Write a workflow triggered on push and PR~1h
- 2Run lint and pytest in CI~1h
- 3Cache pip dependencies~1h
- 4Build and push the image on main~1h
- 5Add a status badge to the README~1h
Key points
- Workflows live in .github/workflows and trigger on events like push and pull_request.
- setup-python with cache: pip reuses downloaded packages between runs.
- Use an if condition so image pushes happen only on main, not on PRs.
- Store registry credentials as secrets, never in the workflow file.
Key terms
Tap a card to flip it. 0/4 known
Examples
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.12", cache: pip }
- run: pip install -r requirements.txt ruff pytest
- run: ruff check . && pytest -q
- if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: echo "build and push image here".github/workflows/ci.yml: test everywhere, publish only from main.
Run tests against a real Postgres in CI
Your integration tests need a database. Step 1: declare a postgres service; GitHub starts the container before the steps run. Step 2: map port 5432 and add a health check so steps wait until Postgres is ready. Step 3: pass the connection string as an environment variable. Step 4: run pytest. The job runs directly on the runner, so localhost reaches the mapped port.
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env: { POSTGRES_PASSWORD: test }
ports: ["5432:5432"]
options: --health-cmd pg_isready --health-interval 5s --health-retries 10
env: { DATABASE_URL: "postgresql://postgres:test@localhost:5432/postgres" }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.12", cache: pip }
- run: pip install -r requirements.txt && pytest -qBuild and push to GHCR on main
Step 1: the build job waits for test with needs. Step 2: the if condition skips it for pull requests. Step 3: permissions give the token write access to packages. Step 4: log in to ghcr.io with GITHUB_TOKEN. Step 5: build and push, tagged with the commit SHA and latest, reusing layers from the GitHub Actions cache. No checkout step is needed, because build-push-action builds from the Git context by default. Image names on GHCR must be lowercase.
build:
needs: test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions: { contents: read, packages: write }
steps:
- 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: true
tags: ghcr.io/acme/api:${{ github.sha }},ghcr.io/acme/api:latest
cache-from: type=gha
cache-to: type=gha,mode=maxQuick reference
- Workflows live in .github/workflows/*.yml and start on events listed under on
- Quote Python versions in YAML, for example "3.10", or YAML reads it as 3.1
- setup-python with cache: pip restores pip downloads keyed on your requirements files
- needs: test makes a job wait; if: github.ref == 'refs/heads/main' limits it to main
- GHCR login works with GITHUB_TOKEN when the job has permissions: packages: write
- concurrency with cancel-in-progress: true stops outdated runs on the same branch
- Badge URL: https://github.com/OWNER/REPO/actions/workflows/ci.yml/badge.svg
- Fork pull requests get no secrets and a read-only token
Common mistakes
- Pushing images from pull request runs, which publishes untested or untrusted code.
- Not pinning the Python version, so CI silently changes when defaults move.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a status badge for ci.yml on main to the top of your README, linked to the workflow runs.
- Exercise 2medium
Make the workflow cancel older runs when you push again to the same branch, give the token read-only access by default, and stop any job after 15 minutes.
- Exercise 3hard
Only run the expensive integration test job when files under app/ or requirements.txt changed, but always run lint. Keep it working for both push and pull_request.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is GitHub Actions free?
- Public repositories get free minutes on standard GitHub-hosted runners. Private repositories get a monthly allowance of free minutes depending on the plan, then pay per minute.
- Why does my workflow not run on a pull request from a fork?
- It usually does run, but with a read-only token and without secrets, and first-time contributors may need a maintainer to approve the run. Steps that need secrets, like pushing images, will fail by design.
- How do I run a workflow by hand?
- Add workflow_dispatch under on. A Run workflow button then appears on the Actions tab, and you can also start it with gh workflow run ci.yml.
- Where do I store secrets for GitHub Actions?
- In the repository or organization settings under Secrets and variables, Actions. Reference them as secrets.NAME inside an expression; their values are masked in logs.