DevOps & Deployment

CI/CD Pipeline Setup & Deployment Guide

From commit to production automatically – the stages of a CI/CD pipeline, a complete example, deployment strategies, secrets and rollbacks.

Updated Official documentation ↗

1. Introduction & use cases

A CI/CD pipeline automates the path from a code change to a running release.

  • Continuous Integration (CI): every push is built and tested automatically, so problems are found within minutes.
  • Continuous Delivery: every change that passes is packaged and ready to release; a person approves production.
  • Continuous Deployment: passing changes go to production automatically.

Tools differ (GitHub Actions, GitLab CI/CD, Jenkins), but good pipelines share the same stages and rules: build once, test early, deploy the same artifact everywhere, and make rollback easy.

Where it is used

  • Teams shipping several times a day with confidence
  • Preventing broken code from reaching main
  • Repeatable releases with an audit trail
  • Fast rollback when something goes wrong

2. Prerequisites

You needVersion / notes
Version controlGit repository with protected main
Automated testsAt least unit tests and a build command
CI toolGitHub Actions, GitLab CI/CD or Jenkins
Target environmentsStaging and production (servers, containers or cloud)

3. Local setup

  1. 1Make the build reproducible locally

    A pipeline can only automate what works from a clean checkout. These commands must succeed on a fresh clone:

    BASH
    git clone <repo> && cd <repo>
    npm ci            # exact dependencies from the lockfile
    npm run lint
    npm test
    npm run build
  2. 2Containerise (recommended)

    A Docker image is a perfect deployable artifact – the same image runs in staging and production. See the Docker guide.

    BASH
    docker build -t my-app:local .
    docker run --rm -p 3000:3000 my-app:local

4. Create & run a project

  1. 1Plan the stages

    Fast checks first so feedback arrives quickly.

    OUTPUT
    1. Lint & unit tests        (every push / PR, ~1-3 min)
    2. Build artifact / image    (tagged with the commit SHA)
    3. Integration & e2e tests  (against the built artifact)
    4. Security scans           (dependencies, image)
    5. Deploy to staging        (automatic on main)
    6. Smoke tests on staging
    7. Approve → deploy to production (same artifact)
    8. Monitor; roll back if health checks fail
  2. 2Write the pipeline (GitHub Actions example)

    Build once, push an image tagged with the commit SHA, deploy it to staging, then to production after approval.

    .github/workflows/pipeline.yml
    name: pipeline
    on:
      push:
        branches: [main]
    permissions:
      contents: read
      packages: write
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with: { node-version: lts/*, cache: npm }
          - run: npm ci && npm run lint --if-present && npm test
    
      build:
        needs: test
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - 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/${{ github.repository }}:${{ github.sha }}
    
      staging:
        needs: build
        runs-on: ubuntu-latest
        environment: staging
        steps:
          - run: ./scripts/deploy.sh staging ${{ github.sha }}
          - run: curl -fsS https://staging.example.com/health
    
      production:
        needs: staging
        runs-on: ubuntu-latest
        environment: production   # requires reviewer approval
        steps:
          - run: ./scripts/deploy.sh production ${{ github.sha }}
          - run: curl -fsS https://example.com/health
  3. 3Write a deploy script with a health check

    The script pulls the exact image, restarts and verifies; if the health check fails it restores the previous tag.

    scripts/deploy.sh
    #!/usr/bin/env bash
    set -euo pipefail
    ENV=$1; TAG=$2
    HOST=$([ "$ENV" = production ] && echo prod.example.com || echo staging.example.com)
    ssh deploy@$HOST bash -s <<EOF
      cd /srv/app
      PREV=\$(cat .current_tag 2>/dev/null || echo none)
      TAG=$TAG docker compose pull && TAG=$TAG docker compose up -d
      sleep 5
      if curl -fsS http://127.0.0.1:3000/health; then echo $TAG > .current_tag
      else echo 'health check failed, rolling back'; TAG=\$PREV docker compose up -d; exit 1; fi
    EOF

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Keep secrets in the CI tool’s secret store, scoped per environment (staging vs production), and inject them at deploy time. Never echo them in logs.

CI secrets
# per environment (CI secret store)
STAGING_HOST=staging.example.com
PROD_HOST=prod.example.com
SSH_PRIVATE_KEY=...
DATABASE_URL=...   # different value per environment

Key dependencies

Package / toolUsed for
CI serverGitHub Actions, GitLab CI/CD, Jenkins, CircleCI
Artifact store / registryGHCR, ECR, Docker Hub, S3
Test toolsJest, Playwright …
Security scannersnpm audit, Trivy, CodeQL, Dependabot
MonitoringHealth checks, uptime, error tracking for automatic rollback decisions

Folder structure

project structure
repo/
├── .github/workflows/pipeline.yml
├── scripts/
│   ├── deploy.sh
│   └── smoke-test.sh
├── Dockerfile
└── compose.yaml        # on servers: image tag via $TAG

Essential commands

CommandWhat it does
git pushStarts the pipeline
gh run watch / GitLab pipeline viewFollow progress
Re-run failed jobRetry flaky infrastructure steps
Deploy previous SHA/tagRollback

6. Production deployment

Choose a release strategy that fits your risk and infrastructure:

Server & hosting requirements

RequirementRecommendation
Rolling updateReplace instances a few at a time (Kubernetes default) – no extra servers
Blue-greenTwo identical environments; switch traffic at once; instant rollback
CanarySend a small % of traffic to the new version first, then increase
Feature flagsDeploy code dark; turn features on separately from deploys
RollbackAlways possible in one step: previous image tag / previous release

Deployment steps

  1. 1Protect production

    Require approvals on the production environment, allow deploys only from main/tags, and keep production secrets separate.

  2. 2Promote the same artifact

    Deploy the image built in CI (tagged with the commit SHA) to staging and then to production – never rebuild for production.

  3. 3Run database migrations safely

    Make migrations backward-compatible (expand → deploy → contract), and run them as a separate step before switching traffic.

  4. 4Add health checks and automatic rollback

    Every deploy must verify /health (and ideally key user flows) and restore the previous version when checks fail – as in deploy.sh above.

  5. 5Observe and measure

    Track deployment frequency, lead time, change failure rate and time to restore (the DORA metrics) to improve the pipeline over time.

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminalpipeline · main · a1b2c3d✓ test 58s✓ build 1m 34s ghcr.io/you/app:a1b2c3d✓ staging 42s https://staging.example.com/health → 200⏸ production waiting for approval (environment: production)✓ production 39s https://example.com/health → 200
Figure 1: terminal output of the sample CI/CD Pipeline project (section 4).
1Commit2CI: lint + test3Build image (SHA)4Staging + smoketest5Approve →production
Figure 2: production deployment flow (section 6).
repo/├── .github/workflows/pipeline.yml├── scripts/│ ├── deploy.sh│ └── smoke-test.sh├── Dockerfile└── compose.yaml # on servers: image tag via $TAG
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Pipeline is slow (20+ minutes)

Cache dependencies, run jobs in parallel, split slow e2e tests, and run only affected tests on PRs.

Flaky tests block releases

Quarantine and fix flaky tests; never just re-run until green. Use retries only for known-unstable infrastructure.

Works in staging, fails in production

Environments differ (config, data, versions). Keep them as similar as possible and deploy the same artifact.

Secrets leaked in logs

Never echo secrets; use masked variables; rotate any secret that appeared in a log.

No way to roll back quickly

Keep previous images/releases, tag every deploy and script the rollback.

Best practices

  • Keep main always deployable; small, frequent changes.
  • Build once, deploy many.
  • Automate tests at several levels (unit, integration, e2e).
  • Infrastructure and pipeline as code, reviewed like application code.
  • Make rollback a one-command operation and practise it.