Deploy to a VPS with GitHub Actions
Push to main triggers one SSH deploy script every time - dedicated deploy key, pinned known_hosts, docker compose with healthchecks, and a loopback curl on /health before the workflow goes green. Roll back by checking out the last good SHA by hand.
People still ship a backend by opening SSH, running git pull, and restarting Docker by hand. That works once. It breaks when the deploy starts from a cafe laptop, when two people push at the same time, or when the terminal looks fine and the process is already dying on port 3000. A GitHub Actions pipeline to the VPS makes a push to main the only way production updates, and the same script runs every time.
This sits on a server that is already running. If Docker, Nginx, and TLS are not in place, start with نشر مشروع Node.js على VPS بـ Docker و Nginx و SSL. If the app receives payment webhooks, read Building reliable payment webhooks before a restart can drop in-flight requests. The same caution applies if a Telegram payment bot shares the server.
What this setup assumes
- An Ubuntu VPS, a non-root user with
sudo, and SSH by key only. - The app lives in a directory such as
/var/www/app, already cloned from the same GitHub repository. docker composestarts the app, and Nginx on the host terminates TLS.- The app exposes a health route, for example
GET /health, that returns 200 only when the process can accept traffic.
The repository does not hold .env or TLS certificates. Those stay on the server, with tight file permissions, and the deploy script refuses to start if they are missing.
A deploy user and a key that stays in GitHub
Do not reuse the key from your laptop. Give the pipeline a user, or at least a key, whose only job is to update the app directory.
On the VPS:
``bash sudo adduser --disabled-password --gecos "" deploy sudo mkdir -p /home/deploy/.ssh sudo chmod 700 /home/deploy/.ssh ``
On your laptop, generate a key that has no passphrase (GitHub Actions cannot type one):
``bash ssh-keygen -t ed25519 -f ./github-actions-deploy -C "github-actions-deploy" -N "" ``
Append the public key to /home/deploy/.ssh/authorized_keys on the VPS, paste the private key into GitHub, then delete the local copies. The private key should exist only as a GitHub Actions secret, with its public half on the VPS.
Give deploy just enough sudo to run Compose. A tight sudoers drop-in looks like this:
`` deploy ALL=(root) NOPASSWD: /usr/bin/docker, /usr/bin/docker-compose, /usr/libexec/docker/cli-plugins/docker-compose ``
Adjust the paths to what which docker reports on your image. Do not grant NOPASSWD: ALL.
In the GitHub repo, Settings > Secrets and variables > Actions, add:
SSH_HOST: the server IP or hostnameSSH_USER:deploySSH_KEY: the full private key, including theBEGINandENDlinesSSH_KNOWN_HOSTS: the output ofssh-keyscan -t ed25519,rsa YOUR_HOST, reviewed against the fingerprint your VPS provider showed you
Pin known_hosts. Running ssh-keyscan on every job will accept a new host key without you noticing.
The deploy user also needs to pull the repo. Generate a second, read-only deploy key on the VPS, add the public half under GitHub Deploy keys, and use it only for git fetch. The Actions key opens SSH. The VPS key talks to GitHub. Keep them separate.
The workflow
Create .github/workflows/deploy.yml. The workflow stays thin: it opens SSH and runs a script from the repo, so I can test that script by hand on the server.
```yaml name: Deploy to VPS
on: push: branches: [main]
concurrency: group: production-deploy cancel-in-progress: false
jobs: deploy: runs-on: ubuntu-latest timeout-minutes: 15 steps:
- uses: actions/checkout@v4
- name: Write SSH key and known_hosts
env: SSH_KEY: ${{ secrets.SSH_KEY }} SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }} run: | umask 077 mkdir -p ~/.ssh printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key printf '%s\n' "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts chmod 600 ~/.ssh/deploy_key ~/.ssh/known_hosts
- name: Run deploy.sh on the VPS
env: HOST: ${{ secrets.SSH_HOST }} USER: ${{ secrets.SSH_USER }} run: | ssh -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes \ "$USER@$HOST" 'bash -s' < scripts/deploy.sh ```
concurrency.cancel-in-progress: false is intentional. Cancelling mid-compose up can leave the stack half started, so later jobs wait their turn. actions/checkout@v4 is only there so the runner can stream scripts/deploy.sh into SSH. The VPS pulls the app from Git itself, so a dirty runner cannot upload leftover files.
The script the VPS runs
scripts/deploy.sh should be safe to run twice, and it should stop on the first error.
```bash #!/usr/bin/env bash set -euo pipefail
APP_DIR=/var/www/app HEALTH_URL=http://127.0.0.1:3000/health COMPOSE="sudo docker compose"
cd "$APP_DIR"
if [[ ! -f .env ]]; then echo "missing .env in $APP_DIR" >&2 exit 1 fi
git fetch origin main git reset --hard origin/main
$COMPOSE build --pull $COMPOSE up -d --remove-orphans --wait --wait-timeout 60
for i in 1 2 3 4 5 6; do if curl -fsS "$HEALTH_URL" >/dev/null; then echo "health check passed" exit 0 fi sleep 5 done
echo "health check failed after deploy" >&2 $COMPOSE ps $COMPOSE logs --tail 80 exit 1 ```
Mark it executable in Git (chmod +x scripts/deploy.sh). --wait blocks until Compose sees a healthy container, if you defined a healthcheck. The curl loop is a second check from the host, through the loopback address Nginx uses.
A minimal healthcheck in compose.yaml:
```yaml services: api: build: . env_file: .env expose:
- "3000"
restart: unless-stopped healthcheck: test: ["CMD", "curl", "-fsS", "http://127.0.0.1:3000/health"] interval: 10s timeout: 3s retries: 6 start_period: 20s ```
/health should be a cheap test: the process is up and it can open a database connection. No side effects. git reset --hard is blunt on purpose. It keeps production equal to origin/main and discards manual edits on the server. If you keep editing over SSH, the next deploy will surprise you. Put the change in Git.
Migrations and files that must not come from Git
Run migrations after the new image is up, and only if they still work with in-flight requests from the previous release. I do not auto-run destructive migrations from this hook. A column drop waits for a second release, after the old code is gone.
.env never comes from the workflow. Add a new variable on the server first, then merge the code that reads it. You can also fail the script when a required name is absent:
``bash required="DATABASE_URL APP_SECRET" for name in $required; do if ! grep -q "^${name}=" .env; then echo "missing $name in .env" >&2 exit 1 fi done ``
Uploaded files and Postgres data stay in Docker volumes or a directory outside the git tree. The deploy script must not delete them.
When the new release is bad
The workflow fails if /health does not return 200. The new containers may already be running. I keep the previous image on the host so I can go back without a rebuild. Rollback is a manual SSH session, not a second broken workflow:
``bash cd /var/www/app # list images tagged by this compose project sudo docker compose images # check out the last known good commit, then: sudo docker compose up -d --no-build ``
Better: tag each release. In deploy.sh, after a successful health check:
``bash git rev-parse --short HEAD > /var/www/app/.released-sha sudo docker compose exec -T api sh -c 'echo "$GIT_SHA"' || true ``
Pass GIT_SHA as a build arg so /health can report it. To go back, reset to the previous SHA (save it before you overwrite the file) and run compose up. For a store or a payment bot I also hit the public URL in the first minutes, and the webhook path if one exists. A green Actions run is not the end of the story if customers are mid-checkout.
What I leave out on purpose
I do not start with Kubernetes, blue-green at the load balancer, or a self-hosted runner. For one or two apps on a single machine, a push to main, an SSH script, and a health check are enough. A self-hosted runner can wait until builds are heavy; it is also another process to patch. Pull request branches never deploy to production. Protect main (reviews if there is a second person, and no force push). A staging branch can use a second directory on the same VPS, or a smaller machine, with the same script and different secrets.
Frequently asked questions
Can I deploy with rsync instead of `git pull` on the server?
Yes. Some people rsync the Actions workspace and skip Git on the VPS. I prefer a fetch on the server because the running tree always matches a commit you can check out later. If you rsync, still record the SHA and keep .env out of the upload.
Do I need a GitHub-hosted runner?
No. The default Ubuntu runner is fine for a typical Node or Python image. Use a self-hosted runner when the build is heavy or the VPS cannot pull images reliably.
What if SSH is on a non-standard port?
Add -p and your port to the ssh command, and store the port in a secret. Restrict the port to your IP and GitHub's documented Actions IP ranges, or put SSH behind WireGuard. The first option is the usual start.
Will this restart drop payment webhooks?
A short restart can, if the app does not finish in-flight requests and the provider does not retry. Keep the process up until /health is ready, and make webhook handlers idempotent, as in the webhooks article. Compose --wait plus a healthcheck reduces the window. It does not replace retries on the provider side.
How much do you charge if I want you to set this up?
VPS setup starts at $40 one-time (server, Docker, Nginx, and TLS). A later speed or outage fix starts at $50, and ongoing server care is $25 per month. The VPS invoice itself is paid to your provider.