Skip to main content

Building a Docker CI/CD Pipeline

Build a Docker CI/CD pipeline with GitHub Actions: multi-stage build, Trivy scan, ECR push with OIDC, and SSH deploy with rollback.

44 Terms

Overview and What You Will Learn

A Docker CI/CD pipeline builds an image from a commit, tests and scans it, pushes it to a registry under an immutable tag, and deploys exactly that tag. Doing the steps in the right order means you never ship a known critical vulnerability, and you can always roll back to a specific earlier build.

In this lab you will:

  • Write a multi-stage Dockerfile that produces a small, non-root production image.
  • Build once on every pull request, and push only from the main branch.
  • Fail the pipeline on HIGH and CRITICAL vulnerabilities with Trivy before anything is pushed.
  • Authenticate to AWS ECR with short-lived OIDC credentials instead of stored keys.
  • Deploy a specific image tag to an EC2 host with Compose, verify health, and roll back automatically.

Why This Matters in Production

Teams that deploy several times a day cannot rely on manual checks. A scan gate stops a vulnerable base image at the pull request, not after it reaches production, and an immutable tag per commit turns a bad release into a one-line rollback instead of an investigation. Payment-focused teams at companies like Razorpay and Stripe treat these properties as table stakes because an outage or a known vulnerability costs far more than the minutes the checks take.

The pipeline also becomes your audit trail. Each running container maps to a commit, a build log, and a scan report.

Core Principles

Order matters: test first because it is cheapest, scan before pushing so a vulnerable image never reaches the registry, and deploy only what was scanned.

flowchart TD T[Test] -->|pass| B[Build image] B -->|local image| S{Trivy scan} S -->|CVEs found| X[Pipeline fails] S -->|clean| P[Push to ECR] P -->|main only| D[Deploy by SHA tag] D -->|healthy| V([Release done]) D -->|unhealthy| R[Roll back] classDef ok fill:#10B981,color:#FFFFFF classDef step fill:#DBEAFE,color:#1E293B classDef bad fill:#EF4444,color:#FFFFFF class T,B,P,D step class V ok class X,R bad

Principles to follow:

  1. Scan the exact image you will push. Build it locally, scan it, then tag and push the same image.
  2. Use immutable tags. Tag by commit SHA. Avoid pushing latest, and enable immutable tags on the ECR repository.
  3. Never store long-lived cloud keys in CI. Use GitHub OIDC to assume an IAM role for the duration of the job.
  4. Deploy by tag, verify, then keep the old tag. The previous tag is your rollback.
  5. Run PR builds too. Building and scanning on pull requests finds problems before merge, while pushing and deploying stay limited to main.

Detailed Step-by-Step Practical Lab

How to Write a Multi-Stage Production Dockerfile
Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=builder /app/dist ./dist
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/server.js"]

Add a .dockerignore that excludes node_modules, .git, and .env* so the build context stays small and free of secrets.

How to Prepare ECR and AWS Access Once
Bash
# Create the repository with immutable tags and scan-on-push
aws ecr create-repository \
--repository-name payment-api \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--region ap-south-1

In IAM, create an OIDC identity provider for token.actions.githubusercontent.com and a role (for example github-actions-ecr-push) whose trust policy is limited to your repository and branch. Grant it only the ECR push permissions it needs, such as ecr:GetAuthorizationToken, ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload, and ecr:PutImage.

How to Write the GitHub Actions Workflow
YAML
# .github/workflows/ci-cd.yml
name: Docker CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
id-token: write # lets the job request an OIDC token for AWS
env:
AWS_REGION: ap-south-1
ECR_REPOSITORY: payment-api
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- run: npm ci
- run: npm test
build-scan-push:
needs: test
runs-on: ubuntu-latest
outputs:
image-tag: ${{ steps.vars.outputs.tag }}
steps:
- uses: actions/checkout@v4
- name: Compute image tag
id: vars
run: echo "tag=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- uses: docker/setup-buildx-action@v3
- name: Build image locally
uses: docker/build-push-action@v6
with:
context: .
load: true
push: false
tags: ${{ env.ECR_REPOSITORY }}:${{ steps.vars.outputs.tag }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Scan image with Trivy
uses: aquasecurity/trivy-action@0.28.0 # pin a release tag or commit SHA
with:
image-ref: ${{ env.ECR_REPOSITORY }}:${{ steps.vars.outputs.tag }}
format: table
severity: HIGH,CRITICAL
ignore-unfixed: true
exit-code: "1"
- name: Configure AWS credentials (OIDC)
if: github.ref == 'refs/heads/main'
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-ecr-push
aws-region: ${{ env.AWS_REGION }}
- name: Log in to Amazon ECR
if: github.ref == 'refs/heads/main'
id: ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Tag and push
if: github.ref == 'refs/heads/main'
run: |
LOCAL="${ECR_REPOSITORY}:${{ steps.vars.outputs.tag }}"
REMOTE="${{ steps.ecr.outputs.registry }}/${LOCAL}"
docker tag "$LOCAL" "$REMOTE"
docker push "$REMOTE"
deploy:
needs: build-scan-push
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- name: Deploy over SSH
uses: appleboy/ssh-action@v1.2.0 # pin a release tag or commit SHA
with:
host: ${{ secrets.EC2_HOST }}
username: ubuntu
key: ${{ secrets.EC2_SSH_KEY }}
script: |
set -euo pipefail
cd /opt/payment-api
NEW_TAG="${{ needs.build-scan-push.outputs.image-tag }}"
PREVIOUS_TAG=$(grep '^IMAGE_TAG=' .env | cut -d= -f2)
aws ecr get-login-password --region ap-south-1 | \
docker login --username AWS --password-stdin \
123456789012.dkr.ecr.ap-south-1.amazonaws.com
sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=${NEW_TAG}/" .env
docker compose pull payment-api
if ! docker compose up -d --no-deps --wait --wait-timeout 90 payment-api; then
echo "Deploy of ${NEW_TAG} failed, rolling back to ${PREVIOUS_TAG}"
sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=${PREVIOUS_TAG}/" .env
docker compose up -d --no-deps --wait payment-api
exit 1
fi
How to Configure the Deploy Host

The host keeps a compose.yaml that references the tag from .env, and an instance role that can pull from ECR.

YAML
# /opt/payment-api/compose.yaml
services:
payment-api:
image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-api:${IMAGE_TAG}
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/health"]
interval: 15s
timeout: 5s
retries: 3
start_period: 15s
Bash
# /opt/payment-api/.env
IMAGE_TAG=9b21d4e

Grant the instance role only ecr:GetAuthorizationToken, ecr:BatchGetImage, and ecr:GetDownloadUrlForLayer.

How to Run the Trivy Scan Locally
Bash
docker build -t payment-api:local .
trivy image \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--exit-code 1 \
payment-api:local
# Machine-readable output for dashboards or the GitHub Security tab
trivy image --format sarif -o trivy-results.sarif payment-api:local
How to Roll Back by Hand
Bash
cd /opt/payment-api
sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=9b21d4e/' .env
docker compose pull payment-api
docker compose up -d --no-deps --wait payment-api
docker inspect payment-api-payment-api-1 --format '{{.Config.Image}}'

Production Best Practices & Common Pitfalls

  • Tag by commit SHA and keep tags immutable: every deployed container maps to one commit, and rollback is exact.
  • Treat the scan as a hard gate: exit-code: "1" on HIGH and CRITICAL stops the release. Use ignore-unfixed to avoid blocking on issues with no available fix, and track those separately.
  • Pin third-party actions: use release tags or commit SHAs rather than @master, because a moved branch can change your pipeline without a pull request.
  • Use OIDC, not stored access keys: short-lived credentials limit the damage of a leaked token.
  • Protect production with an environment: a GitHub environment can require approval before the deploy job runs.
  • Be honest about downtime: recreating a container on one host causes a brief interruption. For zero-downtime releases you need multiple instances behind a load balancer or an orchestrator.
  • Build on pull requests: catching a failing build or a vulnerable dependency before merge is cheaper than catching it on main.
Tip

Add a lifecycle policy to the ECR repository that expires old untagged images and keeps the last 20 to 30 tagged ones, so storage costs stay bounded while rollbacks remain possible.

Remember

Scan the local image before pushing. If you push first and scan afterwards, a vulnerable image already sits in the registry and may be pulled by other jobs.

Common Mistake

Pushing only latest, or pushing latest to a repository with immutable tags. The first makes rollback impossible, and the second fails on the second push. Use the commit SHA tag.

Security

Limit the OIDC role's trust policy to your repository and branch, and give the CI role push-only ECR access. Never attach AdministratorAccess to a CI role or a production instance profile.

Quick Reference & Troubleshooting Commands

Command Description
docker build -t app:$(git rev-parse --short HEAD) . Build with a commit tag
trivy image --severity HIGH,CRITICAL <image> Scan an image
aws ecr get-login-password --region ap-south-1 Get a short-lived ECR password
docker compose up -d --no-deps --wait <svc> Recreate one service and wait for health
docker inspect <ctr> --format '{{.Config.Image}}' Confirm the running image tag
aws ecr describe-images --repository-name payment-api List pushed tags
Problem Likely cause Fix
tag invalid: already exists Immutable tags and a repeated tag Use a unique SHA tag
Trivy fails the build HIGH or CRITICAL CVE in base or deps Update the base image or dependency
Not authorized to perform sts:AssumeRoleWithWebIdentity Trust policy mismatch Check repo, branch, and id-token: write
Deploy step hangs Health check never passes Check docker compose logs on the host
Wrong version running .env tag not updated Verify with docker inspect and fix the tag

Resources

Explore More in Docker Compose and Multi-Container Applications

All 6 Topics

Frequently Asked Questions

Is Building a Docker CI/CD Pipeline free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Building a Docker CI/CD Pipeline topic cover?

Build a Docker CI/CD pipeline with GitHub Actions: multi-stage build, Trivy scan, ECR push with OIDC, and SSH deploy with rollback.

Found a mistake, an outdated step or a broken link?