Skip to content
NevaraCloud

Deployment

CI/CD from GitHub: build and deploy Docker images with GitHub Actions

By , FounderUpdated 11 min read

What the pipeline on this page does, in order:

  1. Every pull request and every push to main runs your tests.
  2. On a push to main, it builds a Docker image and pushes it to GitHub Container Registry (ghcr.io), tagged with the full commit SHA and with latest.
  3. It connects to your server over SSH as a restricted deploy user, which pulls that exact tag, runs database migrations, and restarts the app with docker compose up -d --wait.
  4. If the new container fails its healthcheck, the server switches back to the previous tag.
  5. A final check hits the public health URL. Old tags stay in the registry, so rollback is one click.

It assumes the app already runs on the server with Docker Compose, with a healthcheck defined. If not, start with our Docker production checklist; this page builds on that compose.yaml.

The workflow file

Put this in .github/workflows/deploy.yml. Change IMAGE to your own name; image names on ghcr.io must be all lowercase, even if your GitHub organisation or repo name has capitals. The test job assumes a Node.js project; swap in your own test commands.

.github/workflows/deploy.yml
name: Build and deploy

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

permissions:
  contents: read

env:
  IMAGE: ghcr.io/your-org/myapp

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm test

  build:
    needs: test
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE }}
          tags: |
            type=raw,value=${{ github.sha }}
            type=raw,value=latest,enable={{is_default_branch}}

      - uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://example.com
    concurrency:
      group: production
      cancel-in-progress: false
    steps:
      - name: Install SSH key and pinned host key
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts

      - name: Deploy this commit
        env:
          TARGET: ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}
          IMAGE_TAG: ${{ github.sha }}
        run: ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=yes "$TARGET" "$IMAGE_TAG"

      - name: Check the public health endpoint
        run: curl --fail --silent --show-error --retry 5 --retry-delay 5 --retry-all-errors https://example.com/health

A few things worth knowing about it:

  • GITHUB_TOKEN is created fresh for every run. The packages: write permission on the build job is what lets it push to ghcr.io; everything else only gets read access to the code.
  • type=gha stores Docker layer cache in GitHub's Actions cache, so a commit that only changes app code doesn't reinstall every dependency. mode=max caches the intermediate stages of multi-stage builds too. See Docker's GitHub Actions cache docs for the limits.
  • Secrets and the commit SHA reach the shell through env:, never pasted straight into a run: line. That habit matters most for anything a person can type, such as a rollback input, because text dropped directly into a script can run as a command.
  • If you also release versions, add a tags: ["v*"] trigger under push and a type=semver,pattern={{version}} line to the metadata tags. Keep deploying by SHA either way.

Prepare the server: a deploy user that can do one thing

The pipeline needs to run Docker on your server, and anyone who can run Docker commands can become root on that host. So don't give the CI key a shell. Create a deploy user, and lock its SSH key to a single script that accepts nothing but a commit SHA.

terminal (on the server)
sudo adduser --disabled-password --gecos "" deploy
sudo usermod -aG docker deploy
sudo mkdir -p /srv/myapp
sudo chown deploy:deploy /srv/myapp

Move your compose.yaml and env files into /srv/myapp, and make the app image tag a variable. The :? form makes Compose refuse to start if the tag is missing, instead of silently pulling something else.

/srv/myapp/compose.yaml (excerpt)
services:
  app:
    image: ghcr.io/your-org/myapp:${IMAGE_TAG:?IMAGE_TAG is not set}
/srv/myapp/.env
IMAGE_TAG=3f9c2a1e8b7d6c5f4e3d2c1b0a9f8e7d6c5b4a39

Compose reads .env in the project folder for variable substitution, so this file holds only the current tag. App secrets stay in app.env, loaded with env_file. Neither file belongs in Git. Then the deploy script:

/home/deploy/deploy.sh
#!/bin/sh
# The only command the CI key is allowed to run.
set -eu

TAG="${SSH_ORIGINAL_COMMAND:-}"
if ! printf '%s' "$TAG" | grep -Eq '^[0-9a-f]{40}$'; then
  echo "refusing: expected a full 40-character commit SHA" >&2
  exit 1
fi

cd /srv/myapp
PREV=$(sed -n 's/^IMAGE_TAG=//p' .env)

# Shell variables override .env, so nothing is saved until the deploy succeeds
export IMAGE_TAG="$TAG"
docker compose pull app

# Migrations run with the new image, before it takes traffic
docker compose run --rm app npm run migrate

if docker compose up -d --wait app; then
  sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=$TAG/" .env
  echo "$PREV" > .previous_tag
  echo "deployed $TAG (previous: $PREV)"
else
  echo "new version failed its healthcheck, going back to $PREV" >&2
  export IMAGE_TAG="$PREV"
  docker compose up -d --wait app
  exit 1
fi

Make it executable with sudo chmod 755 /home/deploy/deploy.sh and keep it owned by root, so the deploy user can run it but not change it. Next, make a key pair on your own machine for CI only:

terminal (your machine)
ssh-keygen -t ed25519 -f deploy_key -N "" -C github-actions-deploy

# Record the server's host key, then check the fingerprint
ssh-keyscan -t ed25519 your-server.example.com > known_hosts_entry
ssh-keygen -lf known_hosts_entry

Compare that fingerprint with the output of ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub run on the server itself. If they match, the contents of known_hosts_entry go into a GitHub secret called DEPLOY_KNOWN_HOSTS. This is what stops the runner from talking to an impostor; turning host key checking off (StrictHostKeyChecking=no) throws that protection away.

The private key deploy_key goes into a secret called DEPLOY_SSH_KEY. The public key goes on the server in /home/deploy/.ssh/authorized_keys, with options in front of it:

/home/deploy/.ssh/authorized_keys
restrict,command="/home/deploy/deploy.sh" ssh-ed25519 AAAAC3Nza...rest-of-key github-actions-deploy

restrict turns off port forwarding, agent forwarding and a terminal for this key, and command= means whatever the runner asks to run, the server runs deploy.sh instead, with the request available as SSH_ORIGINAL_COMMAND. That is how the SHA gets through, and why the script checks it is exactly 40 hex characters. Delete the local copy of the private key once it is saved in GitHub.

Finally, the server has to be allowed to pull the image. Either make the package public in its settings on GitHub, or log in once as the deploy user with a classic personal access token that has only the read:packages scope:

terminal (on the server)
sudo -iu deploy docker login ghcr.io -u your-github-username
# Paste the token when asked for the password

Staging, production approvals and secrets

The environment: production line in the deploy job ties it to a GitHub Environment (repository Settings, then Environments). Each environment can hold its own secrets and variables, and can require a named person to approve before the job starts. Store DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS as environment secrets, and DEPLOY_HOST and DEPLOY_USER as environment variables. The same steps then deploy to whichever server the environment points at.

For a staging server, copy the deploy job, name it deploy-staging with environment: staging, and make production wait for it:

.github/workflows/deploy.yml (excerpt)
deploy-staging:
    needs: build
    environment: staging
    # ...same steps as the production job, with the staging URL in the health check

  deploy:
    needs: deploy-staging
    environment:
      name: production
      url: https://example.com

Staging then updates on every merge, and production pauses until a reviewer approves the run in the Actions tab. Restrict the production environment to the main branch as well, so a workflow on some other branch can't use its secrets.

Required reviewers and environment secrets work on public repositories on every GitHub plan. For private repositories, what you get depends on your plan, so check GitHub's current plan comparison before you design the process around approvals.

Rules for secrets that save trouble later:

  • Never commit .env or app.env. Add them to .gitignore and .dockerignore, so they can't end up in the repo or baked into an image.
  • Don't echo secrets or run set -x in steps that handle them. GitHub hides the exact secret values in logs, but not a base64-encoded or otherwise changed copy.
  • Build-time secrets are rarely needed. Runtime secrets live on the server; the image should run anywhere with nothing sensitive inside it.
  • Workflows triggered by pull requests from forks don't get your secrets, which is correct. Don't work around it with pull_request_target plus a checkout of the fork's code.

Database migrations without breaking the running app

The script runs migrations with the new image before the new container takes over, so the new code never starts against an old schema. But for those few seconds the old code is running against the new schema. Migrations therefore have to be backward-compatible: the previous release must keep working after they run.

In practice that means splitting risky changes across releases:

  • Add columns as nullable or with a default; never add a required column the old code doesn't fill.
  • To rename a column: add the new one, write to both, backfill, switch reads, and drop the old one in a later release.
  • Drop tables and columns only once no deployed version uses them.

Done this way, rolling back the image is safe, because the previous version still understands the schema. A destructive migration breaks that: if it deletes data, no image rollback brings it back. Take a database dump before any release that changes the schema (the production checklist shows a pg_dump command), and make sure your migration tool records what has run, so running it twice does nothing.

If the migration fails, set -e stops the script and the old container keeps serving. If the migration succeeds and the healthcheck then fails, the script brings back the old image, but the schema change stays. That is exactly why the old code must cope with it.

Roll back by redeploying a previous SHA

Every successful build leaves an image tagged with its commit SHA, and those tags never move. A rollback is just deploying an older one. This second workflow does that from the Actions tab:

.github/workflows/rollback.yml
name: Roll back production

on:
  workflow_dispatch:
    inputs:
      image_tag:
        description: "Full commit SHA of the image to redeploy"
        required: true
        type: string

permissions:
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    concurrency:
      group: production
      cancel-in-progress: false
    steps:
      - name: Install SSH key and pinned host key
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts

      - name: Redeploy the chosen tag
        env:
          TARGET: ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}
          IMAGE_TAG: ${{ inputs.image_tag }}
        run: ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=yes "$TARGET" "$IMAGE_TAG"

Find the SHA in your Git history or in /srv/myapp/.previous_tag on the server, then run the workflow from the Actions tab or with the GitHub CLI: gh workflow run rollback.yml -f image_tag=<sha>. It goes through the same environment approval and the same SHA check on the server as a normal deploy.

Why not deploy latest? Because latest means "whatever was pushed most recently", and it changes underneath you. You can't roll back to it, two servers pulling it a minute apart can get different code, and nothing on the server tells you which commit is running. A SHA tag answers all three: it always points at the same image, and it links straight to the commit. The pipeline still pushes latest as a convenience for local testing; production never uses it.

Keep enough old images to roll back to. Don't prune the registry down to the latest tag, and on the server avoid docker image prune -a right after a deploy, so the previous image is still local and the switch back is quick.

Guard rails: one deploy at a time, protected main

The concurrency block on both deploy jobs puts them in one group called production. If two merges land close together, the second deploy waits for the first to finish instead of both running docker compose on the server at once. cancel-in-progress: false stops a running deploy from being killed halfway. If several runs queue up, GitHub keeps only the newest waiting one, which is what you want: the latest commit wins.

The pipeline deploys whatever reaches main, so protect main. In the repository settings, add a branch protection rule or ruleset that:

  • requires a pull request before merging, so nobody pushes straight to production;
  • requires the test status check to pass (it shows up in the list after the workflow has run once);
  • blocks force pushes and deletion of the branch.

Together with environment approvals, a change then has to pass tests, be merged through review and be approved for production before it touches the server.

The same pipeline on GitLab CI

If your code lives on GitLab, the shape doesn't change. A .gitlab-ci.yml with test, build and deploy stages does the same work. GitLab gives each project a built-in container registry, and predefined variables such as CI_REGISTRY_IMAGE and CI_COMMIT_SHA replace the image name and github.sha. Protected environments and protected variables take the place of GitHub Environments, and resource_group on the deploy job stops overlapping deploys. The server side (deploy user, locked key, deploy script, SHA tags) is identical.

Where NevaraCloud fits

Apps hosted on NevaraCloud deploy from GitHub. A frontend fits the Starter plan at LKR 1,500 a month; a frontend plus backend and database runs on the Full-stack plan from LKR 3,500 a month, and Docker Compose stacks on the Multi-container plan, quoted monthly in LKR. See Docker and multi-container hosting for what is included. We don't sell self-managed VPS servers or root access, so if you want to run a pipeline like this against your own server, that server stays yours.

Building CI/CD pipelines is part of our DevOps services for teams in Sri Lanka, usually with GitHub Actions, or GitLab CI if your code is there. Each one is quoted per project after we review your setup. If you only need a hand getting an existing app deployed or fixing a broken one, our deployment help covers that.

Rather we handled it?

Managed hosting billed in LKR, DevOps and deployment automation, or hands-on deployment help. Tell us what you're working on.

Discuss your project