Automating Deployments with GitHub Actions (CI/CD)
Manual deployments are risky. You forge to build assets, you forget to restart the server, you forget to run migration.
CI/CD (Continuous Integration / Continuous Deployment) solves this.
Advertisement
The Structure
GitHub Actions live in .github/workflows/deploy.yml.
Example: Node.js CI Pipeline
This pipeline runs every time you Push or open a Pull Request.
name: Node.js CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm test
Creating a CD Pipeline (Deployment)
To deploy via SSH, you need Secrets. Go to repo Settings -> Secrets and variables -> Actions. Add HOST, USERNAME, and SSH_KEY.
Then add a deploy step:
- name: Deploy to VPS
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /var/www/myapp
git pull
npm install
npm run build
pm2 restart all
Why npm ci?
You noticed I used npm ci instead of npm install. ci stands for Clean Install. It deletes node_modules, reads the package-lock.json, and installs exact versions. It is faster and more reliable for CI environments.
Advertisement
Quiz
Why should you use 'npm ci' instead of 'npm install' in a CI/CD pipeline?
Conclusion
Automation buys you sleep. If the tests pass, the code deploys. If they fail, the deploy stops. No more "oops, I broke production on a Friday" moments.
Md Nasim Sheikh
Software Developer at softexForge