Introduction
This tutorial describes how you can deploy an application on a VPS using GitHub Actions. This way, changes in your GitHub repository are automatically deployed to your VPS.
Prerequisites
- GitHub Account
- GitHub Repository
- Server + SSH access to the server
Step 1 - SSH Login to Server
Open a terminal and log in via SSH.
Then navigate to the .ssh
directory
ssh user@hostname
cd ~/.ssh
Step 2 - Create an SSH Key
Now create a new SSH key that we will use for auto-deployment. In the following dialog, simply press “Enter” repeatedly until the key is created.
ssh-keygen -t ed25519 -C "service-name-deploy-github"
Step 3 - Add the Key to the authorized_keys
File
cat id_ed25519.pub >> authorized_keys
(If you named the key file differently, change this accordingly)
Step 4 - GitHub Secrets
In order for the GitHub Action to perform the deployment later, some secrets must be stored in the repository. Open the repository on GitHub. Navigate to “Settings” -> “Secrets And Variables” -> “Actions”. Add the following variables:
HOST
: Hostname or IP address of the serverUSERNAME
: Username you use to log in via SSHSSHKEY
: The private key (copy the content fromcat ~/.ssh/id_ed25519
)PORT
: 22
Step 5 - Create the GitHub Action
Now create the GitHub Action for auto-deployment.
The following GitHub Action will be used: https://github.com/appleboy/scp-action
In your local repository, create the file .github/workflows/deploy.yml
:
name: Deploy
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Copy repository content via scp
uses: appleboy/scp-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
port: ${{ secrets.PORT }}
key: ${{ secrets.SSHKEY }}
source: "."
target: "/your-target-directory"
- name: Executing a remote command
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
port: ${{ secrets.PORT }}
key: ${{ secrets.SSHKEY }}
script: |
ls
This action copies the repository files to your server using scp
.
Afterwards, the ls
command is executed.
Here you can add appropriate commands that rebuild your service or similar.
To rebuild and start a docker service you could use something like this or similar: docker compose -f target-dir/docker-compose.yml up --build -d
Now commit this file and in the “Actions” tab of your repository, the newly created action should now be visible and executed.
With every future change, the git repository will now be automatically copied to your server.
Sources
I read this when trying out, but it did not work and I adapted the deploy.yml
file: https://dev.to/knowbee/how-to-setup-continuous-deployment-of-a-website-on-a-vps-using-github-actions-54im