Learn Docker · 11/12

Continuous Integration and Deployment (CI/CD)

8 min read

Before we automate the world, let us look at the fundamental problem of software delivery. You have written a brilliant piece of code. It runs perfectly on your laptop. You manually build the application, compress it, transfer it to a server, and suddenly it crashes. Your server has a different operating system, a different version of Python or Node.js, and missing environment variables. You spend the next six hours debugging, sweating profusely, while your users wait.

This manual, error-prone process is exactly why Continuous Integration and Continuous Deployment (CI/CD) exists. CI/CD is a method of frequently delivering apps to customers by introducing automation into the stages of app development.

When you combine Docker with CI/CD, you guarantee that the exact same environment used to build and test your code is the one running in production. Let us break down how this is done in the industry.


1. Integrating Docker into Your Daily Development Workflow

The Problem

If you only use Docker for production, you are missing half of its value. Developing locally without Docker means every developer on your team must manually install databases, cache servers, and language runtimes. When a new developer joins, they spend their first three days just trying to get the app to run.

The Solution

We solve this by containerizing the local development environment using Docker Compose. Instead of installing a complex stack on their host machine, a developer simply runs a single command to start the entire ecosystem.

Imagine you manage a large restaurant. If every chef brings their own custom pots, pans, and ingredients from home, coordinating a single meal is going to be chaos. Instead, the restaurant provides a standardized kitchen. Docker Compose is that standardized kitchen for your code. Everyone uses the exact same ovens and utensils, ensuring the soup tastes the same no matter who turns on the stove.

Industry Standard Practice

In the industry, we do not want to rebuild our Docker image every time we change a line of code during local development. Building images takes time. Instead, we use Bind Mounts. A bind mount links a directory on your local laptop to a directory inside the running container. When you save a file on your laptop, the container instantly sees the change.

Example: A Practical docker-compose.yml for Development

Here is how a standard modern development setup looks. We will use a Node.js application as our baseline, paired with a Redis database.

yaml
# docker-compose.yml
version: '3.8'

services:
  api:
    build: 
      context: .
      # We target a specific stage in our Dockerfile for development
      target: development
    ports:
      - "3000:3000"
    volumes:
      # Bind mount: Mounts the current local directory to /app in the container
      # This allows hot-reloading (e.g., nodemon) to work!
      - ./:/app
      # Anonymous volume: Prevents local node_modules from overwriting the container's modules
      - /app/node_modules
    environment:
      - NODE_ENV=development
      - REDIS_HOST=cache
    depends_on:
      - cache

  cache:
    image: redis:7-alpine
    ports:
      - "6379:6379"

What is happening under the hood?
When you run docker-compose up, Docker reads this file, pulls the Redis image, builds your Node API image, creates an isolated network, and starts both. Because of the volumes mapping, your local code edits bypass the container's static file system and instantly reflect inside the running process.

Funny Exaggeration: Without bind mounts, you would make a typo, run docker build for 5 minutes, realize you missed a semicolon, run docker build for another 5 minutes, and eventually rethink your career choices. Bind mounts keep you sane.


2. Automating Image Builds with CI/CD Pipelines

The Problem

You have finished developing locally. Now it is time to build the official production Docker image. If developers build production images on their local laptops, severe issues arise:

  1. Security: A developer's laptop might have malware that gets baked into the image.
  2. Inconsistency: Local caching might result in an outdated dependency sneaking into the production build.
  3. Stolen Weekends: A developer manually builds an image, pushes it to production at 4:59 PM on a Friday, closes their laptop, and goes hiking. The image is broken. No one else has the source files used to build it. Chaos ensues.

The Solution

Continuous Integration (CI). CI is the practice of automating the building and testing of code every time a team member commits changes to version control.

Instead of a human building the image, a robot (a CI server) does it. It creates a pristine, temporary virtual machine, downloads your code, builds the Docker image, runs automated tests against that image, and verifies it is safe.

Industry Standard Practice

The industry overwhelmingly uses cloud-based CI tools like GitHub Actions or GitLab CI. These platforms use ephemeral runners—virtual machines that live just long enough to execute your pipeline and then self-destruct.

Example: GitHub Actions Pipeline

Here is a standard, minimal GitHub Actions workflow that automatically builds your Docker image every time code is pushed to the main branch.

Create a file in your repository at .github/workflows/build.yml:

yaml
name: CI Pipeline

# Trigger the workflow on pushes to the main branch
on:
  push:
    branches:
      - main

jobs:
  build-and-test:
    # Use the latest Ubuntu virtual machine provided by GitHub
    runs-on: ubuntu-latest

    steps:
      # Step 1: Clone the repository into the runner
      - name: Checkout Code
        uses: actions/checkout@v4

      # Step 2: Set up Docker Buildx (an advanced Docker building tool)
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # Step 3: Build the Docker Image (without pushing yet)
      - name: Build Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: false
          # We tag it locally so we can test it in the next step
          tags: my-api:test

      # Step 4: Run a quick test container to ensure it actually starts
      - name: Test Image Execution
        run: |
          docker run -d -p 3000:3000 --name api-test my-api:test
          sleep 5 # Wait for server to start
          curl --fail http://localhost:3000/health || exit 1

What happens here?

  1. GitHub provisions a fresh Linux server.
  2. It pulls your code.
  3. setup-buildx-action installs the modern Docker build engine (BuildKit) which is much faster and supports advanced caching.
  4. It builds the image and tags it as my-api:test.
  5. It runs the container and hits a /health endpoint to ensure the app doesn't immediately crash.

If any of these steps fail, the pipeline stops, a red "X" appears on GitHub, and production is saved from disaster.


3. Tagging and Pushing Images to Private Container Registries

The Problem

You automated the build process. Great! But the built image is currently sitting on a temporary GitHub virtual machine that is about to be deleted. You need a centralized storage location where your production servers can download the final image.

Additionally, if you simply name your image my-app:latest every single time, you create a massive operational risk. If latest breaks production, how do you roll back? Which previous version was the stable one? latest is just a floating pointer; it carries no historical data.

The Solution

Container Registries and Semantic Tagging.
A container registry is a repository specifically designed to host and distribute container images (like Docker Hub, Amazon ECR, or GitHub Container Registry).
Tagging is the process of assigning a string alias to a specific image ID.

Think of a container registry as a giant warehouse for shipping containers. If every container arriving at the warehouse is just labeled "New Stuff", warehouse workers will have no idea what is inside. By assigning specific serial numbers (tags) to every single box, they know exactly what to put on the trucks, and what to recall if a batch is bad.

Industry Standard Practice

In the industry, we almost never rely on the latest tag for production deployments. Instead, we tag images using the Git Commit SHA (a unique string generated by Git for every code change, e.g., a1b2c3d).

By tagging your Docker image with the exact Git SHA, you establish an unbreakable link between the code in your repository and the binary running in production. If image a1b2c3d breaks, you look up commit a1b2c3d in Git and instantly know exactly what lines of code caused the issue.

Example: Pushing to GitHub Container Registry (GHCR)

Let us update our previous GitHub Actions pipeline to tag the image with the Git commit SHA and push it to a private registry.

yaml
name: CI/CD Pipeline

on:
  push:
    branches:
      - main

# Define variables for the registry
env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    
    # We need specific permissions to push to the GitHub registry
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      # Log into the registry so Docker has permission to push
      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Extract metadata (tags, labels) for Docker
      # This automatically generates the Git SHA tag and a 'latest' tag
      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=sha,format=long
            type=raw,value=latest

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # Build and explicitly set push to true
      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          # Apply the tags generated in the metadata step
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          # Use GitHub Actions cache to make future builds blazing fast!
          cache-from: type=gha
          cache-to: type=gha,mode=max

The Final Flow:

  1. You commit code and push to GitHub.
  2. The pipeline spins up, securely logs into the registry using temporary credentials (GITHUB_TOKEN).
  3. The metadata-action generates a tag looking something like this: ghcr.io/yourusername/yourapp:sha-a1b2c3d4e5f6....
  4. The image is built, heavily utilizing caching (type=gha) so it only rebuilds layers that changed.
  5. The image is securely uploaded to your private registry.
  6. Your production server can now run docker pull ghcr.io/yourusername/yourapp:sha-a1b2c3d4e5f6... and boot up the exact application you just tested.

Automation achieved. Your weekends are safe.


Reference / Further Reading

Challenge

Challenge: Create a CI/CD Pipeline for Docker

You are tasked with creating a robust Continuous Integration pipeline for a Dockerized application using GitHub Actions. Your goal is to write a complete workflow file that automates building, tagging, and pushing a Docker image to the GitHub Container Registry (GHCR).

Your workflow file must meet the following specifications:

  1. Trigger: The workflow must run automatically on every push to the main branch.
  2. Job Definition: Define a single job named build-and-push. This job must run on an ubuntu-latest runner.
  3. Permissions: Grant the job contents: read and packages: write permissions to allow it to read the repository and write to GHCR.
  4. Steps: The job must include the following sequential steps:
    • Checkout: Use the standard actions/checkout@v4 to get the repository code.
    • Login to GHCR: Use the docker/login-action@v3 to log in to ghcr.io. Use the ${{ github.actor }} for the username and ${{ secrets.GITHUB_TOKEN }} for the password.
    • Extract Metadata: Use docker/metadata-action@v5 to generate appropriate tags. This step must be given an id of meta. Configure it to produce a tag based on the short Git commit SHA for the image name ghcr.io/my-user/my-app.
    • Set up Buildx: Use the docker/setup-buildx-action@v3 to set up the Docker Buildx builder.
    • Build and Push: Use docker/build-push-action@v5. This final step must:
      • Be configured to push the image.
      • Use the tags and labels generated from the meta step.
      • Enable the build cache using the GitHub Actions cache backend (type=gha).

Expected result

Your solution should be a single, valid YAML file for a GitHub Actions workflow that correctly implements all the specified requirements. The final code should look like this:

yaml
name: Docker Build and Push

on:
  push:
    branches:
      - 'main'

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/my-user/my-app
          tags: |
            type=sha,format=short

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - 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
          cache-to: type=gha,mode=max
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.