Setting Up GitHub Actions CI/CD for VPS Deployment
Introduction
Automate your build and deployment pipeline to a VPS using GitHub Actions. This guide covers building, testing, and deploying via SSH and Docker.
Prerequisites
- GitHub repository
- VPS with SSH access
- SSH key stored as GitHub secret
VPS_SSH_KEY
Step 1: Configure Secrets
In GitHub repo settings, add:
VPS_HOST
: server IPVPS_USER
: SSH usernameVPS_SSH_KEY
: private keyDOCKER_IMAGE
: registry image name
Step 2: Create Workflow
.github/workflows/ci-cd.yml
:
name: CI/CD
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build Docker image
run: |
docker build -t ${{ secrets.DOCKER_IMAGE }}:${{ github.sha }} .
echo ${{ secrets.DOCKER_TOKEN }} | docker login --username ${{ secrets.DOCKER_USERNAME }} --password-stdin
docker push ${{ secrets.DOCKER_IMAGE }}:${{ github.sha }}
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup SSH
uses: webfactory/ssh-agent@v0.5.4
with:
ssh-private-key: ${{ secrets.VPS_SSH_KEY }}
- name: Deploy to VPS
run: |
ssh -o StrictHostKeyChecking=no ${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }} \
"docker pull ${{ secrets.DOCKER_IMAGE }}:${{ github.sha }} && \
docker stop myapp || true && \
docker rm myapp || true && \
docker run -d --name myapp -p 80:3000 ${{ secrets.DOCKER_IMAGE }}:${{ github.sha }}"
Summary
This workflow builds and tests your app, pushes a Docker image, and deploys it to your VPS via SSH, automating end-to-end CI/CD.