AI Hints
CI/CD with GitHub Actions · Lesson 80 of 138

Building a Docker Image

Packaging the app.

⏱ 2 min read▶ Video at 1:32:37🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

The most common artifact today is a Docker image. It holds your code, its dependencies, and the exact Python version, so it runs the same way everywhere. A Dockerfile is the recipe.

Building a Docker Image
From the video: Building a Docker Image
  • Code plus dependencies
  • Runs the same everywhere
  • Dockerfile is the recipe

The Dockerfile

We start from a slim Python image. Copy the requirements, and install them. Then copy the app. And the command, which here just runs a quick total. Copying requirements first means Docker can reuse that layer, when only the code changes.

Dockerfiledockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
CMD ["python", "-c", "import app; print(app.total([10, 20]))"]

Building it in CI

On every push to main, this job checks out the code, sets up Docker build x, and builds the image with the build push action. Push is false for now, so it only checks that the image builds. The tag uses the commit SHA, so every image is unique.

.github/workflows/image.ymlyaml
name: Image
on:
  push:
    branches: [main]
jobs:
  image:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/build-push-action@v6
        with:
          context: .
          push: false
          tags: shop:${{ github.sha }}

Good image habits

Use a small base image, like slim, to keep images fast to pull. Add a dot docker ignore file, so you don't copy tests, git history, or secrets into the image. And turn on layer caching in CI, so rebuilds take seconds.

keyvalue
Slim basesmaller, faster
.dockerignorekeep junk out
Cache layersfast rebuilds
Never bake secretspass them at runtime

Summary

A Dockerfile packages the app, and the build push action builds it in CI. Next, naming images with tags.

Key takeaways
  • Dockerfile
  • docker/build-push-action
  • Tag with the SHA
Next up: Image Tags — naming what you built