Deploying a simple static site #
Right at the beginning of this course, in
Git and its ecosystem,
I promised you that we would “deploy a project on a real server, hands-free”. This is the chapter
where we do it. By the end of it you will type git push and a website will change.
We are going to deploy a static site — a pile of HTML, CSS, images and maybe a JavaScript file — and that is a deliberate choice, not a simplification we are embarrassed about. A static site is the perfect first deployment because its build output is just files. There is no process to restart, no database to migrate, no connection pool to drain. Every mechanism is visible and every step is comprehensible, which means we can build the whole thing ourselves out of Git parts we already own, and then look at the hosted services and understand exactly what they are doing for us.
Deployment from first principles: a bare repository on a server #
Here is the whole idea. We put a bare repository on a server. We add it as a remote. When we push to it, a hook wakes up, checks out the files, builds the site and points the web server at the result.
That is a complete deployment system, and it is about twenty lines of shell.
The bare repository #
On the server, over SSH:
mkdir -p /srv/mysite/releases
cd /srv/mysite
git init --bare site.git
A bare repository is one with no working directory — just the contents of .git, at the top
level. That is what you want on a server: nobody edits files there, so a working tree would only
be something to get out of sync. git init --bare is how every Git host in the world stores your
code.
On our laptop, add it as a remote and push:
git remote add production ssh://you@example.com/srv/mysite/site.git
git push production main
That already works — the repository receives our commits. It just does not do anything with them yet.
The hook #
Hooks are the scripts Git runs at particular moments; we met them in Making the command line yours. On the receiving side there are three that matter, and picking the right one matters:
pre-receiveruns once, before anything is written, for the whole push. Exiting non-zero rejects the entire push. This is where you enforce policy.updateruns once per ref, and can reject individual refs.post-receiveruns once, after all the refs have been updated, and cannot reject anything. This is where you deploy.
We want post-receive, not post-update, for one reason: post-receive gets the old and new
SHAs of every updated ref on standard input, whereas post-update only gets a list of ref
names as arguments. We want to know what moved and where from, so we take the one that tells
us.
Create /srv/mysite/site.git/hooks/post-receive:
#!/bin/sh
set -eu
DEPLOY_BRANCH=main
SOURCE_DIR=/srv/mysite/source
RELEASES_DIR=/srv/mysite/releases
CURRENT=/srv/mysite/current
while read -r oldrev newrev refname; do
if [ "$refname" != "refs/heads/$DEPLOY_BRANCH" ]; then
echo "hook: $refname is not the deploy branch, ignoring."
continue
fi
echo "hook: deploying $DEPLOY_BRANCH ($oldrev -> $newrev)"
mkdir -p "$SOURCE_DIR"
git --work-tree="$SOURCE_DIR" checkout -f "$DEPLOY_BRANCH"
release="$RELEASES_DIR/$(date -u +%Y%m%d%H%M%S)-$(git rev-parse --short "$newrev")"
mkdir -p "$release"
cp -R "$SOURCE_DIR"/. "$release"/
( cd "$release" && ./build.sh )
ln -sfn "$release/public" "$CURRENT.new"
mv -Tf "$CURRENT.new" "$CURRENT"
echo "hook: now serving $release/public"
ls -1 -t "$RELEASES_DIR" | tail -n +6 | while read -r old; do
rm -rf "$RELEASES_DIR/$old"
done
done
Then, and this is the step everybody forgets:
chmod +x /srv/mysite/site.git/hooks/post-receive
Let us go through it line by line, because every line is there for a reason.
#!/bin/sh and set -eu: plain POSIX shell, exit on any error, and treat unset variables as
errors. A deploy script that keeps going after a failed step is a deploy script that serves a
half-built site.
while read -r oldrev newrev refname; do: this is the interface. Git feeds post-receive one
line per updated ref on standard input, and each line is three whitespace-separated fields: the
SHA the ref pointed at before, the SHA it points at now, and the full ref name. One push can move
several refs, hence the loop. A brand-new branch arrives with oldrev as forty zeroes; a deleted
branch arrives with newrev as forty zeroes.
The refname test: we only deploy when refs/heads/main moves. Pushing a topic branch to
production should be free, not catastrophic.
git --work-tree="$SOURCE_DIR" checkout -f "$DEPLOY_BRANCH": the trick at the heart of the whole
chapter. The repository is bare, so it has no working tree — but we can lend it one.
--work-tree says “put the files there”, and checkout -f says “make that directory match this
branch, discarding anything in the way”. The hook runs with its working directory inside the bare
repository and GIT_DIR already set to it, so we do not need --git-dir.
ℹ️ We check out the branch name rather than
$newrev. Both work, but checking out a raw SHA puts the repository in a detached head state and Git prints its whole friendly speech about it into your push output. Checking out the branch prints a quietAlready on 'main'instead.
The release directory: a timestamp plus the short SHA of the commit we are deploying. Now every
build on the server is labelled with the commit that produced it, which is worth an enormous
amount at 3 a.m. We build into that directory rather than over the live site.
ln -sfn then mv -Tf: the swap, discussed below.
The last three lines keep the five most recent releases and delete the rest, because disks fill up.
What it looks like when we push #
Real output, from a real run of exactly this hook:
$ git push origin main
remote: hook: deploying main (cfc6b957e3b163124d2097192b6581832fb70509 -> b25b8e41f0d132ce25d8548cf5c7aff0458a9711)
remote: Already on 'main'
remote: hook: now serving /srv/mysite/releases/20260729213622-b25b8e4/public
To ssh://you@example.com/srv/mysite/site.git
cfc6b95..b25b8e4 main -> main
Everything the hook prints to standard output comes back to us over the wire, prefixed with
remote:. That is our deployment log, and it is free.
And when we push some other branch:
remote: hook: refs/heads/topic is not the deploy branch, ignoring.
Refusing a force-push to the deploy branch #
Our deploy branch is now a piece of production infrastructure, so it should behave like one: it
should only ever move forward. If somebody force-pushes a rewritten history, our releases
directory becomes fiction.
pre-receive is the hook that can say no. Create
/srv/mysite/site.git/hooks/pre-receive (and chmod +x it):
#!/bin/sh
DEPLOY_BRANCH=main
while read -r oldrev newrev refname; do
[ "$refname" = "refs/heads/$DEPLOY_BRANCH" ] || continue
# newrev is all zeroes when someone is deleting the branch.
if ! git rev-parse --quiet --verify "$newrev^{commit}" >/dev/null; then
echo "Refusing to delete $DEPLOY_BRANCH." >&2
exit 1
fi
# oldrev is all zeroes the very first time: nothing to compare against.
git rev-parse --quiet --verify "$oldrev^{commit}" >/dev/null || continue
# A fast-forward means the old tip is an ancestor of the new one.
if [ "$(git merge-base "$oldrev" "$newrev")" != "$oldrev" ]; then
echo "Refusing a non-fast-forward push to $DEPLOY_BRANCH." >&2
echo "The deploy branch only ever moves forward." >&2
exit 1
fi
done
The test in the middle is the definition of a fast-forward, spelled out: a push is a
fast-forward exactly when the old tip is an ancestor of the new one, and git merge-base is how
you ask. Try it and Git refuses the push, for real:
$ git push --force production main
remote: Refusing a non-fast-forward push to main.
remote: The deploy branch only ever moves forward.
To ssh://you@example.com/srv/mysite/site.git
! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'ssh://you@example.com/srv/mysite/site.git'
Zero-ish downtime: build somewhere else, then swap a symlink #
Notice that we never build into the directory the web server is serving. We build into
releases/<timestamp>-<sha>/, and then we move a symlink:
ln -sfn "$release/public" /srv/mysite/current.new
mv -Tf /srv/mysite/current.new /srv/mysite/current
Point nginx at /srv/mysite/current and it always serves a complete site. Without the swap,
there is a window — a second, ten seconds, a minute for a big Hugo site — during which visitors
get half a website.
ln -sfn creates the new link under a temporary name (-n so it does not follow an existing
symlink to a directory), and mv -T replaces the old link with it in one rename, which is
atomic on the filesystem.
⚠️
mv -Tis GNU coreutils, which is what you have on a Linux server. On a BSD or macOS hostmvhas no-Tand will helpfully move your new link inside the directory the old one points at, which is a genuinely baffling ten minutes of debugging. Test your swap once, by hand, before you trust it.
This “releases directory plus a current symlink” pattern is not something we invented; it is
what
Capistrano popularised for Ruby deployments in the
mid-2000s, and it is still the right shape. Its other gift is rollback: the previous release is
still sitting there, so going back is one ln -sfn away — no rebuild, no network, instant.
That is the whole thing. A bare repository, two hooks, a symlink. If you understand this, you understand every deployment product on the market, because they are all this with a nicer user interface.
Now the hosted options #
Of course, most of the time, we do not want to run a server. Here is what the hosted options actually do, and what each one’s catch is.
GitHub Pages #
Free static hosting attached to your repository, with two publishing models.
The branch model is the old one: whatever is on the gh-pages branch (or main, or a /docs
folder) gets served. External build tools “deploy” by committing the built site to that branch.
Its charm is that the deployment is a Git object you can inspect and revert.
The Actions model is the current one: a workflow builds the site and uploads it as a Pages artifact, and nothing is committed anywhere. This is what you want for a Hugo, Astro or Vite site, and we build one below.
Custom domains work: set the domain in the repository settings (which writes a CNAME file),
point a DNS CNAME at <user>.github.io, and enable HTTPS.
⚠️ The
.nojekyllgotcha. When publishing from a branch, GitHub Pages runs your files through Jekyll, and Jekyll ignores every file and directory whose name starts with_or.. So a site with_assets/app.css— perfectly normal output from many generators — loses its stylesheet, with no error anywhere. The fix is an empty file named.nojekyllat the root of the published output. Half the “why is my site unstyled on GitHub Pages” questions on the internet are this.
GitLab Pages #
Same idea, driven by a CI job whose artifact is a public/ directory:
# .gitlab-ci.yml
pages:
stage: deploy
script:
- hugo --minify
artifacts:
paths:
- public
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
Historically the job had to be named pages; modern GitLab instead lets any job opt in with
pages: true. The mechanism is worth noticing: the deployment is a CI artifact. Nothing new was
invented.
Cloudflare Pages, Netlify, Vercel #
Connect a repository, and they build and serve every push, on a global CDN, with preview URLs per branch and generous free tiers. They differ in flavour: Cloudflare Pages is the closest to “pure static plus edge functions”, Netlify has the deepest set of build plugins and redirect handling, Vercel is opinionated in the direction of Next.js.
The catch, in all three cases, is the same: the build configuration lives partly in their
dashboard, and your DNS and your invoice now belong to a vendor whose free tier is a business
decision. Keep the build reproducible locally — make build — and moving costs you an afternoon
instead of a quarter.
Plain object storage plus a CDN #
The boring, durable answer: build the site in CI, aws s3 sync ./public s3://my-bucket --delete,
and serve the bucket through CloudFront, or the R2 equivalent through Cloudflare. No platform, no
lock-in beyond the storage bill, and a mechanism so simple it will still work in ten years. This
is what a great many large sites actually do.
What “connect your repo and it deploys on push” is doing #
Now that we have built one by hand, the magic evaporates. When you connect a repository to a hosted service, it:
- registers a webhook on your repository;
- receives, on every push, the
<before>,<after>andreftriple — the same three values ourpost-receivehook read from standard input; - clones the repository (usually shallow) at that SHA;
- runs your build command in a container;
- uploads the output directory to a CDN and flips a pointer.
Steps 1 and 2 are our hook. Step 5 is our symlink. There is nothing else in the box.
Preview deployments #
The one genuinely new thing the hosted services brought, and it is a big one: a URL per branch, or per pull request.
The mechanism is exactly what you would now guess. Build every branch, not just the deploy
branch; publish each build under its own hostname
(my-feature--mysite.pages.dev, deploy-preview-42--mysite.netlify.app); route by hostname; and
garbage-collect when the branch is deleted. A comment with the link gets posted on the pull
request.
This changed code review for the better, and I do not say that lightly. Reviewing a front-end change by reading a diff is guesswork. Reviewing it by clicking a link and looking at it, on a real URL you can send to a designer who has never used Git, is a different activity. It is the strongest argument for the hosted options, and it is the reason I would not fight a team that chose one.
You can build previews yourself — our post-receive hook could check out every branch into
/srv/mysite/previews/<branch>/ and let nginx map <branch>.preview.example.com onto it, which
is maybe another fifteen lines — but you will also be doing certificates, cleanup and quotas. This
is the point where paying somebody is rational.
Concretely: this very site #
The course you are reading is a Hugo site in a Git repository: a hugo.toml, the chapters under
content/docs/, a vendored theme, and a Makefile whose make build target is the one command
that builds the whole thing. Here is a workflow that builds it and publishes it to GitHub Pages,
following the structure Hugo’s own documentation recommends:
# .github/workflows/pages.yml
name: Deploy Hugo site to Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write # allowed to publish a Pages deployment
id-token: write # OIDC token proving this workflow made it
concurrency:
group: pages
cancel-in-progress: false # never cancel a deploy half-way
jobs:
build:
runs-on: ubuntu-latest
env:
HUGO_VERSION: 0.164.0 # pin the generator, exactly as we pin an action
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # Hugo reads git dates for .Lastmod
# add "submodules: recursive" if your theme is a submodule
# rather than vendored into the repository
- id: pages
uses: actions/configure-pages@v6
- name: Install Hugo
run: |
curl -sSL -o hugo.deb \
"https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb"
sudo dpkg -i hugo.deb
- name: Build
# `make build` locally, the same command here — see the previous chapter
run: hugo --gc --minify --baseURL "${{ steps.pages.outputs.base_url }}"
- uses: actions/upload-pages-artifact@v5
with:
path: ./public
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
steps:
- id: deployment
uses: actions/deploy-pages@v5
Three notes, because I would rather you understand this than paste it.
fetch-depth: 0 again. Hugo can use each page’s Git commit date as its Lastmod, and in a
shallow clone there are no dates to use — the shallow-clone trap from
Continuous integration, in the wild.
HUGO_VERSION is pinned, and it should match whatever version you build with locally. A pinned
generator is the difference between a site that builds identically in three years and one that
mysteriously breaks when a runner image changes. (Hugo 0.164.0 is current as of this
writing; the official Hugo workflow also installs Dart Sass, which you need only if your theme
uses SCSS.)
Action versions move. The actions/* majors above — checkout@v7, configure-pages@v6,
upload-pages-artifact@v5, deploy-pages@v5 — are current in mid-2026, and for actions published
by GitHub itself a major tag is a reasonable compromise. For anybody else’s action, pin the
commit SHA, for the reason we gave in the previous chapter: tags move, hashes do not.
Summary git init --bare post-receive pre-receive git --work-tree
#
- A static site is the ideal first deployment: the build output is just files, so every step of the mechanism is visible.
git init --barecreates a repository with no working tree — what every server uses.- A
post-receivehook receives one line per updated ref on standard input:<oldrev> <newrev> <refname>. New branches arrive witholdrevall zeroes, deletions withnewrevall zeroes. - Prefer
post-receiveoverpost-updatebecause it tells you which SHAs moved; usepre-receivewhen you want the power to say no. git --work-tree=<dir> checkout -f <branch>lends a working tree to a bare repository — the trick that makes push-to-deploy work.- Deploy only when the deploy branch moves, and reject non-fast-forward pushes to it by comparing
git merge-base "$oldrev" "$newrev"with$oldrev. - Build into a fresh
releases/<timestamp>-<sha>/directory and swap acurrentsymlink atomically (ln -sfn+mv -Tf). Rollback becomes a symlink change. This is the Capistrano pattern. - Hosted options: GitHub Pages (branch or Actions, watch out for
.nojekyll), GitLab Pages (a job whose artifact ispublic/), Cloudflare Pages, Netlify, Vercel, or object storage plus a CDN withaws s3 syncfrom CI. - “Connect your repo and it deploys” = a webhook, a clone, a build, an upload, a pointer flip.
- Preview deployments — one URL per branch or pull request — are the strongest reason to use a hosted service.