Home/Engineer/Git / CI·CD/Building a CI/CD Pipeline wi…
Git / CI·CDIntermediateubuntugithub-actionscicdautomation

Building a CI/CD Pipeline with GitHub Actions

A step-by-step guide to writing GitHub Actions workflows that automate tests, builds, and deployments on push events.

Contents
  1. Basic Workflow Structure
  2. Environment Variables and Secrets
  3. Conditional Execution
  4. Matrix Strategy
  5. Docker Build and Push
  6. Deploy to a Server over SSH

Basic Workflow Structure

YAML
# .github/workflows/ci.yml
name: CI/CD Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Test
        run: npm test

Environment Variables and Secrets

YAML
steps:
  - name: Deploy
    env:
      API_KEY: ${{ secrets.API_KEY }}
      DB_URL: ${{ vars.DATABASE_URL }}
    run: ./deploy.sh

Conditional Execution

YAML
steps:
  - name: Deploy to production
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    run: ./deploy-prod.sh

  - name: Slack notification
    if: always()
    run: ./notify-slack.sh

Matrix Strategy

YAML
jobs:
  test:
    strategy:
      matrix:
        node-version: [18, 20, 22]

    runs-on: ubuntu-latest
    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}

Docker Build and Push

YAML
- name: Log in to Docker Hub
  uses: docker/login-action@v3
  with:
    username: ${{ secrets.DOCKER_USERNAME }}
    password: ${{ secrets.DOCKER_TOKEN }}

- name: Build and push image
  uses: docker/build-push-action@v5
  with:
    context: .
    push: true
    tags: myapp:${{ github.sha }}
    cache-from: type=gha
    cache-to: type=gha,mode=max

Deploy to a Server over SSH

YAML
- name: Deploy to server
  uses: appleboy/ssh-action@v1
  with:
    host: ${{ secrets.SSH_HOST }}
    username: deploy
    key: ${{ secrets.SSH_KEY }}
    script: |
      cd /opt/myapp
      git pull origin main
      docker compose up -d --build
#github-actions#cicd#automation#pipeline#deploy
Editorial note

AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us

Topic-related official docs (auto-linked · not per-claim sources)Git documentation ↗

Questions & answers

Ask a question about this guide. We'll review and reply.