Skip to content

20 min read

CI/CD with GitHub Actions and Docker on a VPS

In one sentence: CI/CD means every change passes the tests without anyone asking (continuous integration) and, if it passes them, reaches the server on its own (continuous deployment). Here, GitHub Actions checks every pull request and, with every push to main, publishes the shop's image to ghcr.io; your server asks every two minutes whether there's a new one, deploys it and goes back to the previous one if it doesn't get healthy.

What you will learn

  • Explain what continuous integration and continuous deployment are, and read piece by piece the workflow that publishes the image.
  • Publish the shop's image to ghcr.io from your own repository, for amd64 and arm64 processors.
  • Make the server deploy every new image on its own, with a backup, migrations and a rollback if it doesn't get healthy.
  • Go back to an earlier version on purpose, and know what a rollback can't undo.

Before you start, read: 05-https.md phase-7/08-registries.md

Imagine Ana changes the shop’s title. To get it to the server, she copies the folder with rsync, logs in over SSH, types docker compose up --build and waits for the image to build. Five steps by hand, and any of them can be forgotten.

One Friday night she forgets to run the tests. The new version doesn’t start, the shop answers 502 and Ana doesn’t remember which version was there before.

Every step done by hand is a step someone skips. In this lesson, a git push runs the tests, publishes the image and reaches the server without you logging in to it; and if the new version doesn’t work, the server goes back to the previous one on its own.

The analogy

Think of a newsstand. The printer (GitHub) only prints an edition if the proofreader (the tests) approves it, and leaves it at the distributor’s warehouse (ghcr.io).

The vendor (your server) drops by the warehouse every little while. If there’s a new edition, they take it, put it in the window and keep yesterday’s under the counter. If the new one came out badly printed, they put yesterday’s back.

Where the analogy breaks down

  • The warehouse doesn’t deliver anything to the newsstand: it’s the vendor who goes. That part does match: GitHub doesn’t get into your server.
  • Changing the newspaper in the window is instant. Changing the API leaves the shop a few seconds without answering.
  • Going back to yesterday’s paper changes nothing else. Going back to the previous version doesn’t undo what the new one’s migrations changed.

CI and CD: check every change and deploy it on its own

Section titled “CI and CD: check every change and deploy it on its own”

They’re two halves of the same idea:

  • Continuous integration (CI)CI stands for Continuous Integration.Merging changes into the main branch often, with a program that checks each one before it is accepted (installs, checks the types, runs the tests). If something breaks, you know within minutes, and you know which change did it.Go to definition (CI) merges changes into the main branch often, and a program checks each one first: it installs, checks the types and runs the tests. If something breaks, you know within minutes, and you know which change it was.
  • Continuous deployment (CD)CD stands for Continuous Deployment.Every change that passes the continuous integration checks reaches production by itself, without anyone deploying it by hand. If the last step is a button a person presses, it is called continuous delivery, with the same initials.Go to definition (CD) takes every change that passes those checks to production, with nobody in between. If the last step is a button a person presses, it’s called continuous delivery, with the same initials.

In the shop, a change travels this way:

  1. Yougit push to main

    tells it about the push

  2. GitHub Actionsthe tests and, if they pass, the image

    publishes sha-… and main

  3. ghcr.ioGitHub's registry

    every two minutes: has main changed?

  4. Your serverdeploy.sh, with a timer

    backup, migrations and the new API

  5. The shopwith the new version

GitHub Actions: a borrowed computer for every push

Section titled “GitHub Actions: a borrowed computer for every push”

GitHub ActionsThe GitHub service that runs tasks when something happens in a repository, such as a push or a pull request, for example running the tests or publishing an image. They are described in YAML files in .github/workflows, and every job runs on a fresh virtual machine GitHub lends.Go to definition runs tasks when something happens in a repository. They’re described in a workflow, a YAML file in .github/workflows, with jobs made of steps. Each job runs on a fresh virtual machine that GitHub lends you, the runner, which is deleted when it’s done.

GitHub only reads the workflows at the root of a repository. In the step’s folder, inside the course’s repository, publish.yml does nothing: in “Try it,” the step will be the root of your own repository. In October 2026, Actions is free for public repositories; for private ones, a free account gets 2,000 minutes a month, and each push to main uses about 4.

When it runs: pull request and push to main

Section titled “When it runs: pull request and push to main”
.github/workflows/publish.yml
on:
push:
branches: [main]
pull_request:
# A new push to the same branch cancels the previous check, which is no longer useful. On main
# nothing is cancelled: a half-done publication would leave main not knowing which image is the
# latest.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
  • pull_request: with every pull request, a proposed change that’s reviewed before it’s merged into main. It only checks.
  • push to main: yours, or the one GitHub makes when it accepts a pull request. It checks and publishes.
  • concurrency: in a pull request, a new push cancels the previous check; on main, none is cut off halfway.

The first job starts with a database:

.github/workflows/publish.yml
check:
runs-on: ubuntu-24.04
timeout-minutes: 15
# The tests' database: PostgreSQL 18, the shop's version, pinned by its digest (the same one
# compose.production.yaml uses). Its port is published on the runner only.
services:
postgres:
image: postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336 # 18
env:
POSTGRES_PASSWORD: postgres
ports:
- 127.0.0.1:5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 2s
--health-timeout 5s
--health-retries 15

services starts containers that live as long as the job: the shop’s PostgreSQL 18, pinned by its Digest (of an image)The SHA-256 hash that names a Docker image by its content, written as sha256 followed by 64 characters. A digest always names exactly the same image, and Docker checks it when downloading it, so pinning an image by its digest keeps it from changing unless you decide so.Go to definition and with its HealthcheckA command Docker runs every few seconds inside a container to find out whether its program really works, not just whether it’s running. If it ends well, the container is healthy; after several failures in a row, it’s unhealthy. Compose uses it to wait for a service before starting the ones that depend on it.Go to definition, which the steps wait for. Then come the tests’ user and the commands you’ve used on your computer since Phase 3:

.github/workflows/publish.yml
# The role and the database the tests use (test/.env): the same ones the PostgreSQL lesson
# asks you to create, with a password that is only good for tests.
- name: role and database for the tests
env:
PGHOST: 127.0.0.1
PGUSER: postgres
PGPASSWORD: postgres
run: |
psql -v ON_ERROR_STOP=1 \
-c "CREATE ROLE shop LOGIN PASSWORD 'shop'" \
-c "CREATE DATABASE shop_test OWNER shop"
.github/workflows/publish.yml
# npm ci installs exactly what package-lock.json says (and .npmrc runs no install scripts).
# Every check runs even if the previous one failed, to see all the failures at once.
- name: install
id: install
run: npm ci
- name: types
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
run: npm run check
# The Redis store's tests skip themselves when there is no Redis: there isn't one here.
- name: tests
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
run: npm test

The steps with uses: are actions, programs other people publish on GitHub: checkout downloads your repository and setup-node installs Node.

.github/workflows/publish.yml
# Actions are pinned by the SHA of their commit, not by their tag: a tag can be moved to
# malicious code (the tj-actions/changed-files attack, 2025) and a SHA cannot. The version
# number goes in the comment. To keep them up to date, switch on Dependabot in your repository:
# a .github/dependabot.yml with package-ecosystem: github-actions.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
# No step pushes anything, so the token is not left in .git/config for other steps to read.
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 26
cache: npm

After the @ there’s no v7, but the action’s commit SHA. It’s Phase 7’s rule for digests: a tag can be moved to other code, as in the attack on trivy-action, and a SHA can’t. persist-credentials: false doesn’t leave checkout’s token on the disk, where another program could read it.

publish: only on main, and only if check passes

Section titled “publish: only on main, and only if check passes”
.github/workflows/publish.yml
publish:
# Only after check passes, and only on main: a pull request never publishes.
needs: check
if: ${{ github.event_name == 'push' }}
runs-on: ubuntu-24.04
timeout-minutes: 30
# Here, and only here, the token can write packages (the image on ghcr.io).
permissions:
contents: read
packages: write
  • needs: check: it waits for check to finish successfully. If it fails, publish doesn’t even start.
  • if: … == 'push': in a pull request it’s skipped. A proposal publishes nothing.
  • permissions: the only job that can write packages, packages: write. Above, for the whole workflow, there’s only reading: permissions: contents: read.

It’s Phase 6’s Least privilegeThe rule of giving each user and each program only the permissions it needs, and no more. If something fails or someone gets in where they shouldn’t, the damage stays within the little it could touch.Go to definition: check runs the code of every pull request and of hundreds of npm packages, and its token can’t publish.

The GITHUB_TOKEN: a key that lasts one run

Section titled “The GITHUB_TOKEN: a key that lasts one run”

In Phase 7 you logged in to ghcr.io with a token you created yourself. In Actions you don’t need one:

.github/workflows/publish.yml
# Logs in to ghcr.io with the token GitHub gives this run: there is no password to create, and
# the token stops working when the run ends.
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

secrets.GITHUB_TOKEN is created by GitHub when each job starts, with that job’s permissions, and stops working when the job ends: there’s no password to keep or to leak. In a pull request from someone else’s copy (a fork), it can only read.

.github/workflows/publish.yml
# QEMU and Buildx let it build the image for two architectures at once: amd64 (most servers)
# and arm64 (Apple Silicon, Raspberry Pis and some servers).
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

The image is built twice: linux/amd64, for Intel and AMD, the ones in most VPSs, and linux/arm64, for ARM, like the Multipass VM on a Mac with an Apple chip. QEMU imitates ARM on the runner, which is amd64, and Buildx joins both into an index, like node:26-slim’s in Phase 7:

$ docker buildx imagetools inspect ghcr.io/backendfromscratch/shop-api:main
Name: ghcr.io/backendfromscratch/shop-api:main
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:c4160dfa995813805af864b6c353de84e7e886e8a0bddeb5282fe5f9932bce63
…
Platform: linux/amd64
…
Platform: linux/arm64
…
Platform: unknown/unknown
…
Platform: unknown/unknown
…

One image per processor, and two unknown/unknown notes about how they were built. Your server downloads only its own.

Two tags: sha-… forever, main for the latest

Section titled “Two tags: sha-… forever, main for the latest”
.github/workflows/publish.yml
# Works out the tags: sha-<7 letters of the commit> (this version) and main (the latest). No
# latest: whoever deploys follows a branch, not "the last one that was uploaded".
- id: meta
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ steps.image.outputs.name }}
flavor: latest=false
tags: |
type=sha,format=short
type=raw,value=main
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

Each image comes out with two Tag (of an image)The version name that goes after the colon in a Docker image’s name, like 26-slim in node:26-slim. If you don’t write one, Docker uses latest. Anyone who can write to the registry can move a tag to another image whenever they want, so it doesn’t guarantee which image you get.Go to definition:

  • sha- and the first 7 letters of the commit, like sha-3ace67e: this version, forever.
  • main: the latest one that passed the tests. It moves with every push, and it’s the one your server follows.

The first time, ghcr.io creates the shop-api package as private, even if your repository is public, and your server, with no GitHub account, can’t download it:

$ docker pull ghcr.io/backendfromscratch/shop-api:main
Error response from daemon: error from registry: unauthorized
unauthorized

Make it public once, in “Try it.” It can’t be made private again, but it carries no secrets: they live in the server’s .env. For a private image, the server would need docker login ghcr.io with a token of yours with a single permission, read:packages.

GitHub doesn’t send anything to your server. It’s the server that asks, every two minutes, whether main points to another image:

  • GitHub can’t reach your VM. It has a Private IP addressIP stands for Internet Protocol.An IP address that only works inside a local network, such as 192.168.1.133. The same ones are reused in millions of homes, and they can’t be reached from the internet.Go to definition behind your router, and nobody on the internet can start a conversation with it: Phase 0’s NAT. By asking, the VM and a VPS work the same.
  • GitHub keeps no key to your server. Whoever gets into your GitHub account will be able to publish an image, but not to open a terminal on your server. Careful: your server deploys that image on its own, with your secrets. Protect your account with two-factor authentication.
  • There’s no new door. The server only goes out, and ufw stays as in lesson 2.

The one that asks is a systemdThe first program Linux starts when it boots, process number 1. It starts the programs that must always be running (the services), restarts them if they crash and keeps what they write in a journal.Go to definition, like the nightly backup’s in lesson 3, with its service:

deployment/shop-deploy.timer
# When to look for a new image (Phase 1: a systemd timer is a cron with better logging).
[Unit]
Description=Every two minutes, looks for a new image of the shop
[Timer]
# One minute after the server starts (the first time)…
OnBootSec=1min
# …and every two minutes since the previous run started. If one lasts longer than two minutes, the
# next trigger waits for it to end: systemd doesn't start two at once (and flock wouldn't allow it).
OnUnitActiveSec=2min
[Install]
WantedBy=timers.target
deployment/shop-deploy.service
# The shop's deployment (shop-deploy.timer launches it). Install it with:
# sudo cp deployment/shop-deploy.service deployment/shop-deploy.timer /etc/systemd/system/
# sudo systemctl daemon-reload && sudo systemctl enable --now shop-deploy.timer
# Its log: journalctl -u shop-deploy. Change User and the two paths if your user or your folder
# aren't ubuntu and /opt/shop.
[Unit]
Description=Deploys the shop's new image, if there is one
# Without Docker running there is nothing to deploy, and without a network the registry can't be reached.
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target
[Service]
# Type=oneshot: it does a task and ends (it isn't a server that stays).
Type=oneshot
# The same user as the backup (in the docker group; you know what that implies) and, always, the
# same one that runs deploy.sh by hand: they share the lock file.
User=ubuntu
WorkingDirectory=/opt/shop
ExecStart=/opt/shop/deployment/deploy.sh
# If it hangs (a download that never ends), systemd cuts it after 15 minutes.
TimeoutStartSec=15min

OnUnitActiveSec=2min means “two minutes after the previous run started.” systemd can delay it up to a minute to group tasks together: in practice, between two and three.

The service runs deployment/deploy.sh. First of all, it makes sure there aren’t two at once:

deployment/deploy.sh
# One deployment at a time. File descriptor 9 opens (and creates) a lock file, and flock -n tries
# to take it without waiting: if another deployment holds it (the timer and you at once, or a slow
# one that hasn't finished yet), this one ends doing nothing and without an error (0). The system
# releases the lock when the script ends, even if it's from a failure. Always run it as the same
# user: in /run/lock, Linux doesn't let another user open somebody else's lock file.
exec 9>/run/lock/shop-deploy.lock
flock -n 9 || exit 0

flock is a lock on a file: if the timer and you launch it at the same time, the second one ends without doing anything. Then it keeps the running image under a name of its own, :previous:

deployment/deploy.sh
# The image that is running is kept under a name of its own (<name>:previous) BEFORE asking the
# registry. If main pointed to another image and the tag moved, the old one would be left without a
# name and Docker could delete it: this way going back depends neither on the registry (it may be
# down) nor on the previous image still having its tag. It's a new tag on an image that is already
# on this disk: it downloads and writes nothing else, and it repeats on every run without noise.
# Only if the container is healthy: an image that doesn't work isn't one worth going back to, and
# the :previous that already existed is kept.
if [ -n "$running" ] &&
[ "$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$container")" = healthy ]; then
docker tag "$running" "$previous"
fi

That way, going back doesn’t depend on the registry, which may be down. Only if the API is healthy: a broken version isn’t worth going back to. Now it asks the registry and compares:

deployment/deploy.sh
# Asks the registry: if main points to a new image, it downloads it and moves the local tag to it.
# With build and image together in the service, pull downloads the image, it doesn't build it.
# Compose writes "Pulling/Pulled" even when asked for --quiet: the output is kept and only shown if
# something fails (the registry down, no network): then the script ends with an error (set -e) and
# the shop keeps running with what it has, untouched.
if ! output="$("${compose[@]}" pull --quiet api 2>&1)"; then
echo "$output" >&2
log "could not download $image: the shop keeps the image that is running" >&2
exit 1
fi
new="$(docker image inspect --format '{{.Id}}' "$image")"
# Nothing new: silence.
if [ "$new" = "$running" ]; then
exit 0
fi

It compares the image ID, its HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, because main always has the same name. With nothing new, it ends without writing anything. pull only downloads the Layer (of an image)Each of the read-only pieces that make up a Docker image. It holds the files that one step of the image’s recipe added, changed or deleted, and the layers stack up to form the container’s files. It’s named by the fingerprint of its content, so several images share the layers that are identical and they’re stored only once.Go to definition it doesn’t have: it’s the wait of every deployment that Phase 7 told you about. With a new image, first the backup and the migrations:

deployment/deploy.sh
# The backup, before touching the schema. Going back changes the code, not the data: a bad migration
# is only undone with this backup, by hand. If the backup fails, the script stops here (set -e):
# without a backup it doesn't migrate, and as nothing has been touched, the next attempt starts
# over.
log "backup before migrating"
deployment/backup.sh
# The migrations, with the new image (migrate uses IMAGE, which already points to it). The API that
# is running stays up meanwhile. If they fail, the API is not touched.
log "migrations"
if ! "${compose[@]}" run --rm migrate; then
fail "the migrations failed: the API stays on the previous image"
fi

The MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition run with the new image while the old API keeps serving; if they fail, the API isn’t touched. Then, the new API:

deployment/deploy.sh
# Compose removes the old container before starting the new one: if up fails (the image won't
# start), the API may be down. That's why a failed up takes the same path as an API that doesn't get
# healthy: going back to the previous image.
healthy=no
if "${compose[@]}" up -d --no-build --no-deps api; then
log "waiting for /health (up to 60 s)"
if wait_for_health; then
healthy=yes
fi
fi
if [ "$healthy" = yes ]; then
rm -f .deploy-failed
log "done: the API is running $(short "$new")"
exit 0
fi
  • --no-build: the server never builds; it uses the downloaded image.
  • --no-deps: only the API. PostgreSQL and Redis have to be running already, as you left them in lesson 3.
  • wait_for_health asks Docker every 2 seconds, for up to 60, whether Phase 7’s healthcheck considers it healthy.

Every deploy leaves the old image on disk, and nothing deletes it: docker image prune frees the ones that no longer have a name (without -a, so it doesn’t take :previous), and a full disk takes PostgreSQL down.

If the new version doesn’t get healthy, it goes back on its own

Section titled “If the new version doesn’t get healthy, it goes back on its own”

If the new API isn’t healthy within 60 seconds, the script goes back to :previous:

deployment/deploy.sh
# It didn't start or never got healthy: back to the previous image (the one kept as :previous).
# IMAGE in the environment overrides the one in .env for this command only, and --no-deps avoids
# running the migrations again with the old code.
if ! docker image inspect "$previous" > /dev/null 2>&1; then
fail "the new image didn't start or never got healthy, and there is no previous image to go back to"
fi
back="$(docker image inspect --format '{{.Id}}' "$previous")"
log "the new image didn't start or didn't get healthy: going back to $(short "$back")" >&2
if IMAGE="$previous" "${compose[@]}" up -d --no-build --no-deps api && wait_for_health; then
fail "back done: the API is running $(short "$back") again. The new image's migrations are still applied"
fi
fail "the previous image is not healthy either: look at docker compose logs api"

fail writes the image down in .deploy-failed, and the following runs don’t repeat it:

deployment/deploy.sh
# An image that already failed is not tried again every two minutes (every attempt is seconds
# without an API): it waits for main to point to another one. The file holds the ID of the last one
# that failed.
if [ -f .deploy-failed ] && [ "$(cat .deploy-failed)" = "$new" ]; then
log "image $(short "$new") already failed: waiting for a new one (to retry it: rm $PWD/.deploy-failed)" >&2
exit 1
fi
log "new image: $(short "${running:-none}") -> $(short "$new") (the one running is kept as $previous)"

This is how it looked on our VM, with a version we prepared for the test (in a test registry, localhost:5000, without going through GitHub; it’s from an earlier test: its IDs and times aren’t the ones in “Try it”): it required a new variable, NOTIFICATIONS_EMAIL, that the server’s .env didn’t have (we trimmed lines, …):

$ journalctl -u shop-deploy --since 02:43 --no-pager
Oct 18 02:43:34 course systemd[1]: Starting shop-deploy.service - Deploys the shop's new image, if there is one...
Oct 18 02:43:34 course deploy.sh[55030]: deploy: new image: 06012f0dc592 -> be6d411ce72c (the one running is kept as localhost:5000/shop-api:previous)
…
Oct 18 02:43:36 course deploy.sh[55030]: deploy: waiting for /health (up to 60 s)
Oct 18 02:44:38 course deploy.sh[55030]: deploy: the new image didn't start or didn't get healthy: going back to 06012f0dc592
…
Oct 18 02:44:49 course deploy.sh[55030]: deploy: back done: the API is running 06012f0dc592 again. The new image's migrations are still applied
Oct 18 02:44:49 course systemd[1]: shop-deploy.service: Main process exited, code=exited, status=1/FAILURE
…
Oct 18 02:45:34 course systemd[1]: Starting shop-deploy.service - Deploys the shop's new image, if there is one...
Oct 18 02:45:34 course deploy.sh[62734]: deploy: image be6d411ce72c already failed: waiting for a new one (to retry it: rm /opt/shop/.deploy-failed)
…

While it waited, docker compose -f compose.production.yaml logs api kept repeating why: Configuration: NOTIFICATIONS_EMAIL: NOTIFICATIONS_EMAIL is missing, or it is not an email. Look at the logs while it waits: after the rollback, that container no longer exists. The image isn’t retried on its own, because every attempt is a minute without an API:

  • If the fault is the server’s, fix it and delete the file. We added NOTIFICATIONS_EMAIL to .env and ran rm .deploy-failed: on the next run, done.
  • If it’s the code’s, don’t delete anything: fix it and push. The new image will have another ID.

To switch images, Compose stops the old container and starts the new one. In between, nginx answers 502, as in lesson 4. This is how one deployment looked, asking /health every 0.2 seconds:

02:41:55 200
02:42:00 502
02:42:02 200
02:42:05 502
02:42:09 200
…

Two windows: the moment with no container and, after it, a few seconds in which nginx keeps setting aside the copies that failed: after a failure, it sets them aside for 10 seconds (lesson 4), and each nginx process keeps its own count.

In our tests, a few seconds without answering per deployment (between 1 and 11); a failed one, more than a minute. For a small shop that’s acceptable; deploying without interruptions (two copies that take turns, or blue-green) is a topic for Phase 9.

A rollback brings back the code, not the schema

Section titled “A rollback brings back the code, not the schema”

A Deployment rollbackPutting the previous version of a program back to work when the new one fails. It brings back the code, not the data or the database schema, because what the new version’s migrations changed stays changed. It is not a transaction’s ROLLBACK, which does undo the changes.Go to definition changes the image, but the new version’s migrations stay applied: as in Phase 5, they only go forward. A bad migration can only be undone by hand, with the backup from before migrating. It isn’t a Phase 5 transaction’s ROLLBACK: here nothing in the database is undone.

The rule that makes rollbacks safe is called expand and contract. Imagine you want to rename the name column of products to title:

  1. Expand: a migration that only adds title, copying what’s in name, and code that writes to both and reads the new one. The old code keeps working, because name is still there.
  2. Contract: days later, when you’re no longer going to go back to the old version, another migration drops name.

Many tutorials do the opposite, the push model: an Actions job keeps an SSH Private keyThe half of a key pair that only its owner knows. It decrypts what was encrypted with its public key and signs messages anyone can check with the public key. If it leaks, it must be replaced.Go to definition in the repository’s secrets, logs in to the server and runs docker compose pull and up. Kamal, for example, deploys that way. If you use it, limit that key: in Phase 1’s authorized_keys, it can carry a forced command in front:

command="/opt/shop/deployment/deploy.sh",restrict ssh-ed25519 AAAAC3Nz… github-actions

Whoever logs in with it can only launch the deployment: restrict takes away the terminal, the tunnels and everything else.

The server asks (pull) GitHub comes in (push)
Server with no public IP (your VM) Works Can’t reach it
A key to the server on GitHub No Yes, limited with command=
When the change arrives Up to 2 or 3 minutes later As soon as the workflow ends
Several servers Each one asks on its own The workflow goes into all of them
Seeing the deployment on GitHub No: in the server’s journal Yes, in the same run

Pull fits a server nobody can reach from the internet, or if you don’t want keys outside. Push, if you want to see the deployment on GitHub or chain more steps after it.

This website: GitHub Actions checks, Cloudflare deploys

Section titled “This website: GitHub Actions checks, Cloudflare deploys”

This website’s workflow, .github/workflows/ci.yml, is triggered like this:

on:
push:
branches: [main]
pull_request:
workflow_dispatch:
# Once a week, everything, even if nothing changed: what changes outside the repository (a new
# Node 26 release, a package removed from npm) shows up here, not in the next unrelated PR.
schedule:
- cron: '17 5 * * 1'

The same push to main and pull_request, plus a button (workflow_dispatch) and Mondays at 5:17 UTC (schedule). It checks the website and the guided projects. It doesn’t deploy.

Cloudflare deploys, with Workers Builds: with every push to main, GitHub tells it, and Cloudflare downloads the commit, builds the website and publishes it. It’s the diagram from Phase 1. Cloudflare doesn’t wait for Actions: what reaches main already passed the checks in its pull request, because main requires them to pass. Here, too, GitHub keeps nobody’s key: it’s Cloudflare that has permission to read the repository.

The goal: get a change from a git push to your server without logging in to it; keep a broken one on GitHub; and go back to the previous version on purpose.

You need a GitHub account, your SSH key on it (from Phase 1) and the shop running on your server, as you left it in lesson 5.

The outputs come from two places. GitHub’s, from our practice repository, backendfromscratch/shop-practice. The server’s, from lesson 3’s VM, which downloads from ghcr.io. Our images carry our username, backendfromscratch; yours, yours. Your IDs, SHAs, times and durations will be different.

On GitHub’s website, create an empty repository, shop-api, without a README. Public, so you don’t use up minutes. On your computer:

Ventana de terminal
curl -O https://backenddesdecero.com/practicas/shop-api/36-deployment.tar.gz
tar -xzf 36-deployment.tar.gz
cd 36-deployment
git init -b main
git add .
git commit -m "The shop, ready to be published"
git remote add origin git@github.com:ana/shop-api.git
git push -u origin main

Change ana to your username. On Windows, type them in WSL, as in the earlier phases: creating the repository doesn’t need the VM. The step ends up at the root, with .github/workflows/publish.yml next to package.json, where GitHub looks for it. In your repository’s Actions tab you’ll see the Publish run. Ours, with GitHub’s gh command:

$ gh run view 39124680707 -R backendfromscratch/shop-practice
✓ main Publish · 39124680707
Triggered via push about 3 minutes ago
JOBS
✓ check in 1m34s (ID 117667203758)
✓ publish in 1m43s (ID 117667506988)
…

The two ✓ marks: check passed the tests and publish uploaded the image. If one comes out red, its log says which step failed.

Now make the image public: on your GitHub profile, Packages → shop-api → Package settings → Change visibility → Public.

Copy the step’s deployment/ folder to the server, which brings the script and the timer. From your computer, with your user and your server’s IP:

Ventana de terminal
rsync -av 36-deployment/deployment ubuntu@192.168.5.15:/opt/shop/

On Windows, from PowerShell as in lesson 3, with the step downloaded there (curl.exe -O and tar -xzf): scp -r instead of rsync -av. Only that folder: you’ve changed the rest of /opt/shop in lessons 3 to 5, and you don’t want to overwrite it.

Inside the server, in /opt/shop, make the scripts executable (the download doesn’t bring that permission, and copying may have taken it away from the backup script) and tell it which image to follow, with your username, in lowercase:

Ventana de terminal
cd /opt/shop
chmod +x deployment/*.sh
echo "IMAGE=ghcr.io/ana/shop-api:main" >> .env

Launch the first deployment by hand:

1. The first deployment

Ventana de terminal
deployment/deploy.sh

What you will see:

deploy: new image: cfb554da465a -> 0a2cfede5bc0 (the one running is kept as ghcr.io/backendfromscratch/shop-api:previous)
deploy: backup before migrating
Backup made: backups/shop-2026-10-18-135136.sql.gz (4.0K)
deploy: migrations
…
No new migrations: the database is up to date
No practice accounts: they are not loaded (--no-accounts)
The database already has products: the sample ones are not loaded again
deploy: starting the API with the new image
…
Container shop-api-1 Recreate
Container shop-api-1 Recreated
Container shop-api-1 Starting
Container shop-api-1 Started
deploy: waiting for /health (up to 60 s)
deploy: done: the API is running 0a2cfede5bc0

The first line swaps the image you built on the server (cfb5…) for the one GitHub published (0a2c…), and keeps the old one as :previous. Then come the script’s steps, up to done. We trimmed lines (…). If it says unauthorized, the image is still private; if it says Permission denied, the chmod is missing.

And now, the timer:

2. Every two minutes

Ventana de terminal
sudo cp deployment/shop-deploy.service deployment/shop-deploy.timer /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now shop-deploy.timer
systemctl list-timers shop-deploy.timer

What you will see:

Created symlink '/etc/systemd/system/timers.target.wants/shop-deploy.timer' → '/etc/systemd/system/shop-deploy.timer'.
NEXT LEFT LAST PASSED UNIT ACTIVATES
- - Sun 2026-10-18 13:51:54 CEST 6ms ago shop-deploy.timer shop-deploy.service
…

When it’s turned on, the timer launches the first run: LAST is right now, and NEXT shows - while it lasts. A few seconds later, NEXT will say the next one, two minutes later. If your user or your folder aren’t ubuntu and /opt/shop, change the .service before copying it.

On your computer, in a new branch, change the shop’s title in src/shop.ts: the two lines Ana and Luis's shop become Ana and Luis's shop (version 2). Push it and open a pull request:

Ventana de terminal
git switch -c title-change
git commit -am "The shop says it's version 2"
git push -u origin title-change

GitHub gives you the link to create the pull request. In it, the checks say this:

$ gh pr checks 3 -R backendfromscratch/shop-practice
publish skipping 0 https://github.com/backendfromscratch/shop-practice/actions/runs/39083247371/job/117544690156
…
check pass 1m33s https://github.com/backendfromscratch/shop-practice/actions/runs/39083247371/job/117544400939

check passes, and publish is skipped (skipping): it’s a pull request.

Before accepting it, get a measurement ready: how long will the shop go without answering? In another terminal on your computer, leave this running:

3. The seconds without a shop

Ventana de terminal
while true; do echo "$(date +%T) $(curl -s -o /dev/null -w '%{http_code}' --cacert ~/ca/ca.crt https://shop.example/health)"; sleep 0.2; done | uniq -f1

What you will see:

13:52:06 200
13:56:28 502
13:56:39 200

Every 0.2 seconds it asks /health and writes the time and the code. uniq -f1 skips the first column, the time, and only lets a line through when the code changes: at first you’ll see a single 200, and the others arrive with the deployment. Here, about eleven seconds of 502. Stop it with Ctrl + C.

Put your name from lesson 5 and your ca.crt (with Let’s Encrypt, without --cacert). We measured it on the server itself; from your computer it comes out the same. On Windows, in WSL; if WSL can’t reach your VM, skip the measurement.

Now accept the pull request with Merge pull request. The push to main launches the workflow again, this time with publishing:

$ gh run view 39124970379 -R backendfromscratch/shop-practice --log | grep 'pushing manifest'
publish Run docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc 2026-10-18T11:55:33.2719654Z #27 pushing manifest for ghcr.io/backendfromscratch/shop-api:main@sha256:c4160dfa995813805af864b6c353de84e7e886e8a0bddeb5282fe5f9932bce63
…
publish Run docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc 2026-10-18T11:55:35.9178495Z #27 pushing manifest for ghcr.io/backendfromscratch/shop-api:sha-3ace67e@sha256:c4160dfa995813805af864b6c353de84e7e886e8a0bddeb5282fe5f9932bce63
…

The same digest, c416…, with both tags: main and sha-3ace67e, the new commit on main. Don’t log in to the server: wait a few minutes and look at its journal.

4. The server deploys it on its own

Ventana de terminal
journalctl -u shop-deploy --since 13:55 --no-pager

What you will see:

Oct 18 13:56:22 course systemd[1]: Starting shop-deploy.service - Deploys the shop's new image, if there is one...
Oct 18 13:56:25 course deploy.sh[62801]: deploy: new image: 0a2cfede5bc0 -> c4160dfa9958 (the one running is kept as ghcr.io/backendfromscratch/shop-api:previous)
Oct 18 13:56:25 course deploy.sh[62801]: deploy: backup before migrating
Oct 18 13:56:25 course deploy.sh[63039]: Backup made: backups/shop-2026-10-18-135625.sql.gz (4.0K)
Oct 18 13:56:25 course deploy.sh[62801]: deploy: migrations
…
Oct 18 13:56:27 course deploy.sh[62801]: deploy: starting the API with the new image
…
Oct 18 13:56:28 course deploy.sh[62801]: deploy: waiting for /health (up to 60 s)
Oct 18 13:56:38 course deploy.sh[62801]: deploy: done: the API is running c4160dfa9958
Oct 18 13:56:38 course systemd[1]: shop-deploy.service: Deactivated successfully.
Oct 18 13:56:38 course systemd[1]: Finished shop-deploy.service - Deploys the shop's new image, if there is one.

Put your time in --since. The timer saw a new image and deployed it in 16 seconds, with nobody logging in; the measurement’s 502 started at 13:56:28, when the new API was starting. From the push to main to done, 4 min 28 s. If you don’t see anything, wait for another run and check that publish finished.

5. Has it arrived?

Ventana de terminal
curl -s --cacert ~/ca/ca.crt https://shop.example/shop | grep h1

What you will see:

<h1>Ana and Luis's shop (version 2)</h1>

With your name and your ca.crt, as in the measurement. Or open it in the browser: /shop says it’s version 2.

Now break something on purpose, in another branch: in src/app.ts, make /health answer { status: 'fine' } instead of 'ok'. Push it and open another pull request. This time:

$ gh pr checks 4 -R backendfromscratch/shop-practice
check fail 1m34s https://github.com/backendfromscratch/shop-practice/actions/runs/39083261157/job/117544441908
publish skipping 0 https://github.com/backendfromscratch/shop-practice/actions/runs/39083261157/job/117544734565
…

check fails. The log says which test and why:

$ gh run view 39083261157 -R backendfromscratch/shop-practice --log-failed | grep -E 'not ok|ℹ (tests|pass|fail)|expected|actual|\+ |\- |Process completed' | cut -c1-200 | head -30
…
check tests 2026-10-18T00:36:02.5657869Z ℹ tests 230
check tests 2026-10-18T00:36:02.5658500Z ℹ pass 225
check tests 2026-10-18T00:36:02.5658722Z ℹ fail 1
check tests 2026-10-18T00:36:02.5668922Z + actual - expected
check tests 2026-10-18T00:36:02.5669523Z + status: 'fine'
check tests 2026-10-18T00:36:02.5669746Z - status: 'ok'
…
check tests 2026-10-18T00:36:02.5798586Z ##[error]Process completed with exit code 1.

A test expected ok (expected) and got fine (actual). Don’t accept it. No image has been published, so the server has nothing to do:

6. The server, silent

Ventana de terminal
journalctl -u shop-deploy -n 3 --no-pager

What you will see:

Oct 18 13:58:22 course systemd[1]: Starting shop-deploy.service - Deploys the shop's new image, if there is one...
Oct 18 13:58:23 course systemd[1]: shop-deploy.service: Deactivated successfully.
Oct 18 13:58:23 course systemd[1]: Finished shop-deploy.service - Deploys the shop's new image, if there is one.

It starts, asks and ends within a second, without writing a line of its own: main hasn’t changed. Close the pull request.

GitHub lets you accept a pull request with the checks in red. To prevent it, protect main, like this website’s repository: in your repository’s Settings → Rules, a rule that requires check to pass before merging.

Imagine version 2 isn’t well liked. Go back to the first one by its tag, sha- and the first 7 letters of your first commit (git log --oneline). On the server:

7. To the previous version

Ventana de terminal
sed -i "s|^IMAGE=.*|IMAGE=ghcr.io/ana/shop-api:sha-5f108c1|" .env
deployment/deploy.sh
curl -s --cacert ~/ca/ca.crt https://shop.example/shop | grep h1

What you will see:

deploy: new image: c4160dfa9958 -> 0a2cfede5bc0 (the one running is kept as ghcr.io/backendfromscratch/shop-api:previous)
deploy: backup before migrating
…
deploy: starting the API with the new image
…
deploy: waiting for /health (up to 60 s)
deploy: done: the API is running 0a2cfede5bc0
<h1>Ana and Luis's shop</h1>

sed changes the IMAGE line in .env. Look at 0a2c…, the ID of the first deployment. While IMAGE names a sha-, the server doesn’t follow main. If the timer beats you to it, deploy.sh writes nothing: look at the journal.

To follow main again, put the line back:

8. With main again

Ventana de terminal
sed -i "s|^IMAGE=.*|IMAGE=ghcr.io/ana/shop-api:main|" .env
deployment/deploy.sh

What you will see:

deploy: new image: 0a2cfede5bc0 -> c4160dfa9958 (the one running is kept as ghcr.io/backendfromscratch/shop-api:previous)
…
deploy: done: the API is running c4160dfa9958

c416… is version 2 again. This rollback was safe because the change only touched the code. With a migration, think first about “A rollback brings back the code, not the schema.”

  • The apps on your phone. They update on their own at night: the phone asks the app store whether there’s a new version, as your server asks ghcr.io.
  • The green check or the red cross next to a commit on GitHub. They’re the checks of that project’s continuous integration.
  • Forgetting to make the image public. The server says unauthorized every two minutes and the shop stays on the old version.
  • packages: write for the whole workflow. The code of a pull request, or of an npm package, could publish an image in your name.
  • Actions by tag, @v4. Whoever moves that tag runs code in your CI: pin them by SHA and let Dependabot propose the new ones.
  • Renaming or dropping a column in the same deployment as the code. If you roll back, the old code can’t find what it’s looking for: expand first, contract later.
  • Deleting .deploy-failed without fixing anything. The server tries the same image again, with another minute without a shop.
  • Running deploy.sh with sudo. The lock and the backups end up belonging to root, and the timer, which runs as ubuntu, can no longer use them.
  • Continuous integration checks every change before it’s merged; continuous deployment takes each one that passes to production on its own.
  • publish.yml runs the tests with a PostgreSQL on every pull request and, on main, publishes an image for amd64 and arm64 to ghcr.io, with the sha-… and main tags. Actions pinned by SHA, and packages: write only where it publishes.
  • The server asks every two minutes with a systemd timer: backup, migrations, the new API and, if it doesn’t get healthy within 60 seconds, back to the previous one. GitHub has no key to the server.
  • Every deployment leaves the shop a few seconds without answering; without interruptions, in Phase 9.
  • A rollback brings back the code, not the schema: migrations that only add, and the old parts dropped in another deployment.
You open a pull request and check comes out red, with publish skipping. What happens on your server?

Your first push to main publishes the image without errors, but the server’s journal says unauthorized every two minutes. What’s missing?

A version renames the name column of products to title, and its code uses the new name. It doesn’t get healthy and the script rolls back. How is the shop left?

A teammate suggests putting permissions: packages: write at the top of the workflow, so it isn’t repeated. What do you tell them?

Your server is the VM on your laptop. You read a tutorial in which an Actions job logs in over SSH to deploy. Does it work for you?

At three in the morning, the journal says “back done” and, since then, “already failed: waiting for a new one.” The logs say a variable is missing from the .env. What do you do?

phase-8 · lesson 6/8