If you're deploying code to a Linux server (VPS) from a private GitHub repository, you can't just git pull directly. GitHub will deny access unless you set up secure authentication.

In this guide, we'll show you how to configure a dedicated user, set up SSH keys, and connect your VPS to GitHub using Deploy Keys β€” the safest way to pull private repo code.


πŸ” Step 1: Create a Dedicated Deploy User

Instead of using root, let’s create a non-root user for deployment:

sudo adduser deployer

This will prompt you to set a password. You can skip other fields by pressing Enter.


πŸ“ Step 2: Grant Access to Your Project Folder

Assume your project is at /var/www/myapp.

You can either:

βœ… Option 1: Give full access to deployer

sudo chown -R deployer:deployer /var/www/myapp

πŸ” Option 2 (Recommended): Use Group-Based Access

This is safer if multiple users access the server.

sudo usermod -aG www-data deployer
sudo chown -R www-data:www-data /var/www/myapp
sudo chmod -R 775 /var/www/myapp

πŸ”‘ Step 3: Generate SSH Key Pair (Deploy Key)

Log in as the deployer user or your current user and run:

ssh-keygen -t rsa -b 4096 -C "github-deploy"

When it asks for a filename, save as:

~/.ssh/id_rsa_github

You now have two files:

  • id_rsa_github β†’ Your private key
  • id_rsa_github.pub β†’ Your public key

Verify them:

cat ~/.ssh/id_rsa_github
cat ~/.ssh/id_rsa_github.pub

πŸ”— Step 4: Add the Public Key as a GitHub Deploy Key

  1. Go to your GitHub repo.
  2. Click Settings > Deploy Keys > Add Deploy Key.
  3. Give it a name (e.g., VPS deploy).
  4. Paste the contents of id_rsa_github.pub.
  5. βœ… Check "Allow write access" if needed.
  6. Click Add key.

βš™οΈ Step 5: Configure SSH to Use This Key

Back on your server, configure SSH to use the key with GitHub:

nano ~/.ssh/config

Paste this:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_github

Save and exit.


βœ… Step 6: Test the Connection

Run:

ssh -T git@github.com

You should see something like:

Hi username/repo! You've successfully authenticated...

πŸŽ‰ That means your server can now securely pull from your private repo.


πŸ“₯ Step 7: Clone or Pull the Repo

Now you can run:

git clone git@github.com:your-username/private-repo.git

Or if the repo already exists:

git pull origin main

βœ… Done!

You’ve now securely connected your VPS to GitHub using SSH Deploy Keys.

This setup:

  • Keeps access limited
  • Avoids storing passwords or GitHub tokens
  • Makes your deployment safer and more manageable

In the next post, we’ll automate this process using GitHub Actions, so your server pulls updates automatically when you push code. πŸ”„

This is the second part of our deployment series: