How to set up CI/CD

What is CI/CD?

CI stands for Continuous Integration. CD stands for Continuous Delivery.

Continuous Integration means developers merge code frequently into a shared repository and every change is automatically validated through builds and tests.

Continuous Delivery means the software is always deployable.

Modern CI/CD pipelines frequently use Docker containers to package and deploy applications.* Docker is used because it packages a snapshot of an application and all of its dependencies into a portable image. This ensures the application behaves the same way in development, testing, staging, and production environments. Docker also makes deployments predictable, repeatable, and easy to roll back if a release introduces issues.

Note: For the sake of this article, we are going to use the Docker example, which is common for CI/CD but is not always used. It is possible to implement CI/CD pipelines without Docker. For example:

  • Android APK deployments
  • iOS deployments
  • Traditional .NET IIS deployments
  • Serverless deployments

How to set it up

Here is how a CI/CD pipeline is typically set up:

  1. Developer pushes code.
  2. Automated tests run (CI).
  3. Docker builds an image containing the application and its dependencies.
  4. The image is stored in a Docker registry for deployment.
  5. Production servers download the Docker image.
  6. The new version goes live.

Here is a small example of a basic CI/CD pipeline setup. It involves creating a GitHub Actions workflow (deploy.yml) and a deployment script (deploy.sh).

Whenever code is pushed to the main branch, GitHub Actions can be set up to automatically execute the deploy.yml deployment script. Here is what that YAML script can look like. Notice it calls the second script deploy.sh.

name: Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Run deployment script
        run: ./deploy.sh

Then the deploy.sh script can be set up like this:

#!/bin/bash

echo "Running tests..."
pytest

echo "Building Docker image..."
docker build -t myapp:latest .

echo "Pushing image to registry..."
docker push myapp:latest

echo "Deploying latest version..."
ssh prod-server "
    docker pull myapp:latest &&
    docker compose up -d
"

These two scripts together form a basic CI/CD pipeline:

git push
    ↓
GitHub Actions starts
    ↓
deploy.sh runs
    ↓
Tests execute
    ↓
Docker image built
    ↓
Image stored in registry
    ↓
Production server downloads image
    ↓
Application restarts
    ↓
Users see the update

Some notes about Docker

A Docker build creates an “image”. The command docker run creates a docker “container”.

A Docker Image is a blueprint of the code and its dependencies. A Docker Container is a running instance.