Setting Up CI/CD with GitHub Actions
devops

Setting Up CI/CD with GitHub Actions

A step-by-step guide to setting up continuous integration and deployment pipelines using GitHub Actions.

Author

Md Mim Shifat

Full Stack Developer

2023-12-20 8 min read

Setting Up CI/CD with GitHub Actions

GitHub Actions makes it easy to automate your software workflows. Let's set up a complete CI/CD pipeline.

What is CI/CD?

  • CI (Continuous Integration): Automatically build and test code changes
  • CD (Continuous Deployment): Automatically deploy to production
  • Basic Workflow Structure

    YAML
    name: CI/CD Pipeline
    
    on:
      push:
        branches: [main]
      pull_request:
        branches: [main]
    
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - name: Run tests
            run: npm test

    Complete Example for Node.js

    YAML
    name: Node.js CI/CD
    
    on:
      push:
        branches: [main]
      pull_request:
        branches: [main]
    
    jobs:
      test:
        runs-on: ubuntu-latest
        
        strategy:
          matrix:
            node-version: [18.x, 20.x]
        
        steps:
          - uses: actions/checkout@v4
          
          - name: Use Node.js ${{ matrix.node-version }}
            uses: actions/setup-node@v4
            with:
              node-version: ${{ matrix.node-version }}
              cache: 'npm'
          
          - run: npm ci
          - run: npm run build --if-present
          - run: npm test
    
      deploy:
        needs: test
        runs-on: ubuntu-latest
        if: github.ref == 'refs/heads/main'
        
        steps:
          - uses: actions/checkout@v4
          
          - name: Deploy to production
            run: |
              echo "Deploying to production..."
              # Add your deployment commands here

    Using Secrets

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

    Caching Dependencies

    YAML
    - name: Cache node modules
      uses: actions/cache@v3
      with:
        path: ~/.npm
        key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}

    Docker Build and Push

    YAML
    - name: Build and push Docker image
      uses: docker/build-push-action@v5
      with:
        push: true
        tags: myapp:latest

    Best Practices

    1. Keep workflows fast - Parallelize jobs when possible

    2. Use caching - Speed up dependency installation

    3. Fail fast - Put quick checks first

    4. Use environments - Separate staging and production

    Conclusion

    GitHub Actions provides a powerful, flexible platform for automating your development workflow. Start simple and expand as needed.

    CI/CD
    GitHub Actions
    DevOps
    Automation