Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › CI/CD

How to Deploy to a VPS With GitHub Actions

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest default is to build on a GitHub-hosted runner, copy an immutable release to your VPS over SSH, activate it with a least-privilege deploy account, run a health check, and keep the previous release available for rollback. A self-hosted runner on the VPS is an alternative when jobs need direct Docker, filesystem, or service-manager access, but it puts runner patching and job isolation on you.

Choose how GitHub Actions reaches your VPS

There are two sound deployment architectures. In the first, a temporary GitHub-hosted runner checks out the commit, runs tests and the build, then opens an outbound SSH connection to the VPS. The server receives an archive or pulls a container image, switches to that version, and restarts the application. In the second, a self-hosted runner is installed on the VPS and executes the workflow locally.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Decision axis GitHub-hosted runner plus SSH Self-hosted runner on the VPS
Network path The VPS accepts SSH from the runner’s egress address. The runner makes outbound connections to GitHub and executes locally.
Maintenance GitHub manages the ephemeral runner image; you still patch the VPS. You patch and harden the runner host, operating system, and installed software.
Isolation The build runs on GitHub-hosted infrastructure. Jobs run in the VPS environment. A deployment environment does not automatically place a self-hosted job in a container.
Local access Artifacts, images, and commands cross SSH. Docker, filesystems, systemd, and local networks are directly available.
Typical failures SSH reachability, key rotation, host-key verification, or artifact transfer. Runner downtime, queueing, limited capacity, host compromise, or a damaged runner installation.

Use hosted runners plus SSH unless a specific requirement demands local execution. A self-hosted runner is a system you deploy and manage to execute GitHub Actions jobs; its application must be running on the host to accept work. GitHub supports physical, virtual, containerized, on-premises, and cloud machines, but the operator remains responsible for the machine and its software.

What you need before writing the workflow

  • A Linux VPS with a fixed hostname or address, an application runtime or Docker, and only the inbound ports your application needs.
  • A non-root account dedicated to deployment, with a home directory and write access to the release directories.
  • A service manager configuration, normally systemd or a container supervisor, that can start the application from a stable path such as /srv/myapp/current.
  • A repository build contract: a test command, a reproducible build command, and a known output directory or image name.
  • A production branch, release tag, or manual dispatch policy that prevents every feature-branch push from reaching production.

Decide what constitutes a release before automating it. An archive should contain the exact built files and dependencies needed by the server. For a container deployment, tag the image with the full commit SHA rather than relying only on a mutable latest tag.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Prepare the VPS

Create a restricted deployment account

Log in as an administrator for the initial setup, then create a user that is not root. The name is not important; the permissions are.

sudo adduser deploy
sudo install -d -o deploy -g deploy /srv/myapp/releases
sudo ln -s /srv/myapp/releases/empty /srv/myapp/current

Create the empty directory before making the initial link, or omit the link until the first release. Give the account ownership only where it needs to write. If restarting the service requires elevated privileges, grant a narrowly scoped sudo rule for the exact systemd operations instead of giving the account a full root shell.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo install -d /etc/sudoers.d
echo 'deploy ALL=(root) NOPASSWD: /bin/systemctl restart myapp.service, /bin/systemctl status myapp.service' | sudo tee /etc/sudoers.d/myapp-deploy
sudo chmod 440 /etc/sudoers.d/myapp-deploy
sudo visudo -cf /etc/sudoers.d/myapp-deploy

Adjust the binary path to the distribution’s actual systemctl location and validate the rule before using it. Do not allow arbitrary commands through sudo.

Configure the service and release layout

Keep each release in its own directory and make the service read through a symlink. This makes a rollback a link change rather than an in-place file overwrite.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
[Unit]
Description=My application
After=network.target

[Service]
User=deploy
WorkingDirectory=/srv/myapp/current
ExecStart=/srv/myapp/current/bin/start
Restart=on-failure
EnvironmentFile=/etc/myapp/myapp.env

[Install]
WantedBy=multi-user.target

Save the unit as /etc/systemd/system/myapp.service, install runtime secrets in a root-readable environment file or another secret store, then run:

sudo systemctl daemon-reload
sudo systemctl enable myapp.service

Your real ExecStart may launch a runtime, a compiled binary, or a container wrapper. Keep secrets outside the release archive so a copied release cannot expose them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Limit the network surface

Allow SSH and the application ports you actually use. Bind administrative interfaces to a private network or localhost where possible. The deployment account needs outbound access for the application only if the application requires it; it does not need unrestricted inbound access from the public internet.

Create and install a deployment SSH key

Generate a key used only by this repository or production environment. Ed25519 is a practical default.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
ssh-keygen -t ed25519 -C 'github-actions-production' -f github-actions-production

Append the public key to the deploy user’s authorized keys on the VPS:

sudo install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
sudo sh -c 'cat github-actions-production.pub >> /home/deploy/.ssh/authorized_keys'
sudo chown deploy:deploy /home/deploy/.ssh/authorized_keys
sudo chmod 600 /home/deploy/.ssh/authorized_keys

Where practical, restrict this key in authorized_keys with options such as no-agent-forwarding, no-port-forwarding, no-X11-forwarding, and no-user-rc. A forced command can permit only your deployment script, but test it carefully because an overly strict command can prevent artifact transfer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In the repository’s production environment, add secrets named VPS_HOST, VPS_PORT, VPS_USER, and VPS_SSH_KEY. Store the complete private key, including its begin and end lines, in VPS_SSH_KEY. Never put it in workflow YAML, source code, an issue, or a build artifact. Record the server’s host-key fingerprint independently and place the verified key in a repository secret such as VPS_KNOWN_HOSTS; do not blindly trust an unverified result from ssh-keyscan.

Build once and deploy an immutable release

The workflow should test and build once, then deploy the exact output it produced. Rebuilding on the VPS can produce a different dependency tree, compiler result, or configuration.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Example hosted-runner workflow

This example assumes the repository provides executable scripts named ci/test.sh and ci/build-release.sh. The build script must create a directory named release containing the files the service needs.

name: Deploy production

on:
push:
branches: [main]
workflow_dispatch:

permissions:
contents: read

jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- name: Check out source
uses: actions/checkout@v4

- name: Run tests
run: ./ci/test.sh

- name: Build release
run: ./ci/build-release.sh

- name: Package immutable artifact
run: tar -czf app-${GITHUB_SHA}.tgz release

- name: Install SSH client
run: sudo apt-get update && sudo apt-get install --yes openssh-client

- name: Configure SSH
shell: bash
run: |
install -d -m 700 ~/.ssh
printf '%sn' '${{ secrets.VPS_SSH_KEY }}' > ~/.ssh/deploy_key
printf '%sn' '${{ secrets.VPS_KNOWN_HOSTS }}' > ~/.ssh/known_hosts
chmod 600 ~/.ssh/deploy_key ~/.ssh/known_hosts

- name: Copy artifact and activation script
run: |
scp -i ~/.ssh/deploy_key -P '${{ secrets.VPS_PORT }}' app-${GITHUB_SHA}.tgz deploy/activate.sh '${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}:/tmp/'

- name: Activate release
run: |
ssh -i ~/.ssh/deploy_key -p '${{ secrets.VPS_PORT }}' '${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}' 'bash /tmp/activate.sh' '${GITHUB_SHA}'

- name: Record deployment
run: echo "Deployed ${GITHUB_SHA} by ${GITHUB_ACTOR} at $(date -u +%Y-%m-%dT%H:%M:%SZ)"

Pin third-party actions such as checkout to a reviewed commit SHA, or use a maintained major version under a policy that regularly reviews updates. The example’s major-version notation is readable, but a SHA pin gives stronger supply-chain control. Keep the production environment on the job so its approval gate and secrets apply only to production.

Write an idempotent activation script

Store this script in the repository as deploy/activate.sh. It expects the archive and script to arrive in /tmp, creates a release directory named for the commit, and preserves the previous target if activation or the health check fails.

#!/usr/bin/env bash
set -euo pipefail

sha=${1:?commit SHA is required}
archive=/tmp/app-${sha}.tgz
release=/srv/myapp/releases/${sha}
previous=$(readlink -f /srv/myapp/current || true)

test -f "$archive"
test ! -e "$release" || rm -rf "$release"
install -d -o deploy -g deploy "$release"
tar -xzf "$archive" -C "$release" --strip-components=1
ln -sfn "$release" /srv/myapp/current
sudo systemctl restart myapp.service

if ! curl --fail --silent --show-error --max-time 10 http://127.0.0.1:8080/health; then
if test -n "$previous" && test -d "$previous"; then
ln -sfn "$previous" /srv/myapp/current
sudo systemctl restart myapp.service
fi
exit 1
fi

rm -f "$archive" /tmp/activate.sh

Make the script executable and ensure the archive’s internal layout matches the extraction command. The health endpoint should verify the application is ready, not merely that a process exists. For a database migration, define whether the migration is backward-compatible before enabling automatic rollback; a code rollback cannot undo a destructive schema change.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use GitHub deployment environments for production controls

In the repository, open Settings → Environments → New environment and create production. Add required reviewers, restrict which branches or tags may deploy, and place production-only secrets there. The workflow’s environment: production declaration pauses the job until the configured approval is granted and prevents development jobs from receiving those secrets.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Protect the production branch separately with required pull-request reviews, passing checks, and restrictions on who can push. A manual workflow_dispatch trigger is useful for a rollback or an emergency redeploy, but it should still target the protected environment.

When a self-hosted runner is the better fit

Choose a self-hosted runner when the workflow must use a local Docker daemon, private network, large cache, attached volume, or service manager that is difficult to expose safely over SSH. Install the runner application on a dedicated machine or isolated VM, register it with the repository or organization, and apply a distinctive label such as deploy-vps. Keep the runner service running so it can accept jobs.

jobs:
deploy:
runs-on: [self-hosted, linux, deploy-vps]
environment: production
steps:
- uses: actions/checkout@v4
- run: ./ci/test.sh
- run: ./ci/build-release.sh
- run: ./deploy/local-activate.sh

Labels select a runner; they are not a security boundary. Restrict which repositories can use the runner, avoid broad organization-wide registration, and do not put unrelated workloads on the same host. GitHub notes that self-hosted jobs are not container-isolated merely because a deployment environment is used. A compromised workflow can potentially read local files, credentials, Docker sockets, and other trust-boundary resources available to the runner account.

Run the runner under a dedicated account, patch the operating system and runner promptly, monitor job and system logs, cap disk usage, and remove the registration when the repository or team no longer needs access. Treat the runner as production infrastructure rather than as a disposable build VM.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Secrets, tokens, and supply-chain safeguards

  • Use GitHub Actions secrets or environment secrets for private keys, registry credentials, and runtime configuration. Masking is not a substitute for avoiding accidental command output.
  • The built-in GITHUB_TOKEN authenticates workflow actions to GitHub and expires after 60 minutes. It does not replace the separately scoped SSH key or registry credential required by the VPS.
  • Grant the workflow only the permissions it needs; contents: read is sufficient for the checkout in this example.
  • Rotate the deployment key after a runner compromise, team change, repository transfer, or unexplained access. Remove the public key from authorized_keys when it is retired.
  • Use immutable commit-SHA artifact names and record the commit, actor, environment, and UTC deployment time in the workflow log or an external audit system.
  • Make the remote script safe to rerun. A retry should either detect an existing release or replace it deterministically, not partially overwrite the active directory.

Health checks, rollback, and retention

A successful SSH command proves only that a command ran. The workflow should fail unless the service responds correctly after activation. Check an authenticated internal endpoint when possible, verify a dependency that is essential to serving traffic, and set a finite timeout so a hung request cannot leave the job waiting indefinitely.

Retain at least the currently active release and the immediately previous known-good release. A rollback consists of changing /srv/myapp/current back to the previous directory, restarting the service, and running the same health check. Keep a separate, documented command for operators who need to perform this without rerunning the build. Delete older releases only after the new release has passed its observation period and logs have been retained.

Troubleshoot the common failures

Symptom Likely cause Fix
Permission denied (publickey) The wrong private key, user, file mode, or public-key location is being used. Confirm the secret contains the complete key, the workflow uses the intended user and port, and authorized_keys is owned by that user with mode 600. Test with verbose SSH logging from a controlled machine.
Host-key verification failed The stored fingerprint is absent or no longer matches the VPS. Verify the new fingerprint out of band before updating VPS_KNOWN_HOSTS. Do not disable host-key checking to make the job pass.
The archive copies but activation fails The deploy account cannot write the release directory, the archive layout differs from the script, or the sudo rule is wrong. Check ownership, inspect the archive contents, run the activation script interactively as the deploy user, and validate the sudoers file.
The service restarts but the health check fails The application has a startup error, missing runtime secret, incompatible migration, or incorrect bind address. Read journalctl -u myapp.service, verify the environment file and listening port, then activate the previous release.
A self-hosted job remains queued No online runner matches every label in runs-on, or the runner is busy. Check the runner’s online status, labels, service process, and capacity. Remove stale labels and registrations.
A rerun produces a different result The workflow rebuilds on the server or pulls a mutable image tag. Build once on the runner, identify the artifact by commit SHA, and deploy that exact archive or image digest.

Recommended operating pattern

  1. Prepare the VPS with a non-root deploy account, a service definition, a release directory, and a restricted firewall.
  2. Create a repository-specific SSH key, verify the server fingerprint, and store the private key and connection details in the production environment.
  3. Trigger only from a protected branch, release tag, or approved manual dispatch.
  4. Check out the commit, run tests, and build exactly once on a hosted runner.
  5. Package a versioned archive or publish a container image tagged with the commit SHA.
  6. Transfer or pull that immutable artifact, activate it through an idempotent script, and keep the previous release.
  7. Run a readiness check, record who deployed what and when, and fail the job on an unhealthy service.
  8. For self-hosted execution, apply a dedicated label, limit repository access, patch the host, and assume jobs can reach the runner’s local trust boundary.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

CI/CDDevOpsGitHub ActionsLinuxSSHVPS deployment

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.