// DevOps
CI/CD Pipeline with GitHub Actions: Complete Setup Guide
Build robust CI/CD pipelines using GitHub Actions for automated testing, building, and deployment.
Md Nayeem HossainDec 12, 202411 min read// DevOps
Build robust CI/CD pipelines using GitHub Actions for automated testing, building, and deployment.
Md Nayeem HossainDec 12, 202411 min read
Automation is the heart of modern DevOps. Continuous Integration (CI) and Deployment (CD) allow to ship code faster and with fewer bugs. GitHub Actions is my preferred tool because it lives right next to your code.
A workflow is defined in a YAML file in .github/workflows/. It consists of:
Here is a complete, production-grade workflow for a Node.js app. It runs tests, and if they pass, it builds a Docker image and pushes it to a registry.
1name: CI/CD Pipeline2 3on:4 push:5 branches: [ "main" ]6 pull_request:7 branches: [ "main" ]8 9jobs:10 test:11 name: Run Tests12 runs-on: ubuntu-latest13 14 # We can spin up service containers for testing!15 services:16 mongo:17 image: mongo:618 ports:19 - 27017:2701720 21 steps:22 - uses: actions/checkout@v423 24 - name: Setup Node.js25 uses: actions/setup-node@v426 with:27 node-version: '20'28 cache: 'npm' # Automatically caches dependencies!29 30 - name: Install dependencies31 run: npm ci32 33 - name: Run Tests34 run: npm test35 env:36 DATABASE_URL: mongodb://localhost:27017/test_db37 38 build-and-deploy:39 name: Build & Deploy40 needs: test # Only run if tests pass41 if: github.ref == 'refs/heads/main'42 runs-on: ubuntu-latest43 44 steps:45 - uses: actions/checkout@v446 47 - name: Log in to Docker Hub48 uses: docker/login-action@v349 with:50 username: ${{ secrets.DOCKER_USERNAME }}51 password: ${{ secrets.DOCKER_PASSWORD }}52 53 - name: Build and Push Docker Image54 uses: docker/build-push-action@v555 with:56 context: .57 push: true58 tags: myuser/myapp:latestNotice the ${{ secrets.DOCKER_PASSWORD }}. You never want to commit passwords to your code. Go to your repository Settings > Secrets and variables > Actions to store these securely. They are encrypted and only exposed to the runner during execution.
CI/CD can be slow if you re-download dependencies every time. The actions/setup-node action has built-in caching. By adding cache: 'npm', it saves the node_modules folder. The next run will download the cache instead of hitting the npm registry, shaving minutes off your build time.