How to Setup SSH Key for GitHub Auto Deployment to VPS

 

SSH Keys & GitHub Deployment Guide

 Overview

Many developers prefer to automate deployment so that whenever they push code to GitHub (e.g., to the main branch), the code automatically deploys to their VPS.

This is done using SSH keys.

⚠️ Please note: SSH keys are not provided by VPS providers. You need to generate your own SSH keys and configure them with your VPS and GitHub.

This guide explains the complete process step by step.

 Procedure

Step 1: Generate an SSH Key Pair

Run the following command on your local computer (Linux/Mac/WSL) or directly inside your VPS:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Press Enter to accept defaults.

Do not enter a passphrase (just press Enter).

This will create two files:

  • id_rsa → Private key (keep this safe, never share)
  • id_rsa.pub → Public key (this will be added to the VPS)
Step 2: Add the Public Key to Your VPS

If generated on your local computer, upload the public key to your VPS:

ssh-copy-id -i ~/.ssh/id_rsa.pub root@YOUR_SERVER_IP

Or copy the content of id_rsa.pub manually into:

~/.ssh/authorized_keys
Step 3: Add the Private Key to GitHub

Go to your GitHub Repository.

Navigate to:

  • Settings → Deploy Keys (for single repo deployment), or
  • Settings → Secrets and Variables → Actions (if using GitHub Actions).

Add a new key:

  • Title: VPS Deploy Key
  • Key: Paste the content of your private key (id_rsa).
  • Allow write access ✅ if needed.
Step 4: Test the Connection

On your VPS, test GitHub connection:

ssh -T git@github.com

If successful, you’ll see:

Hi username! You've successfully authenticated...
Step 5: Automate Deployment (Optional)

To automate, create a GitHub Action workflow:

.github/workflows/deploy.yml
name: Deploy to VPS

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Deploy to VPS
        run: |
          ssh -o StrictHostKeyChecking=no root@YOUR_SERVER_IP "
            cd /var/www/your-project &&
            git pull origin main &&
            npm install &&
            npm run build &&
            pm2 restart all
          "
        

Now, every push to main will trigger deployment on your VPS.

❓ FAQ

Q: Do you (the VPS provider) give SSH keys?

A: No. SSH keys are user-generated for security. We provide you with VPS access (IP, username, password). You must generate and configure SSH keys yourself.

Q: What if I can’t configure it myself?

A: You may send us your public key, and we can help install it on your VPS. Never share your private key.

Q: Can I use GitHub Actions for automatic deployment?

A: Yes. You can configure GitHub Actions to connect via SSH and run deployment commands automatically.

  • 0 Users Found This Useful
Was this answer helpful?