Auto-Deploy a PHP Site from GitHub with Docker + Webhook

Docker GitHub PHP Security Open Source

Git Push → Live: Auto-Deploy a PHP Website with Docker and a Signed GitHub Webhook

Apache that updates itself on every push to main — no FTP, no CI platform, no docker.sock. A verified webhook, a read-only deploy key and atomic releases, tested end to end with real pushes.

📅 October 2026 👤 Sajjad Hanifa ⏱ ~17 min read 🏢 S&H Software Solutions
Cover: Auto-deploy a PHP site. No FTP. No CI platform. git push to live in 1.4 seconds — with the real terminal run and the browser screenshot of the APEX Note Demo Site, Version 2

Next to every Oracle APEX application I build there is a small PHP website: a landing page, the custom-domain redirect from my June post, the public front end of our Store Locator. For years they were deployed the same way — open the FTP client, drag files over, hope you did not forget one. No history, no rollback, and the one file you forgot is the one that breaks the page while a customer is looking at it.

What I wanted was simple: push to main on GitHub, and the Apache container updates itself. No Jenkins, no GitHub Actions runner with SSH access to my server, no SaaS. My first three attempts did exactly that in about thirty lines of docker-compose.yml — and they were also an open door: the GitHub token sat in a URL that Apache happily served, anybody who knew the port could trigger a deploy, one container had root on the host through docker.sock, and the FTP variant had its password in the compose file.

This post is the version I run now. Every file is complete and in this post, and every screenshot comes from a real run in my APEX Note Lab: real git push, real webhook deliveries, real Chromium screenshots. Who it is for: anyone who hosts small PHP sites in Docker and wants Git-based deployments without a CI platform. What you have at the end: push → live in about 1.5 seconds, signed webhooks only, a read-only deploy key, no .git on the web server, atomic releases with rollback — and a fallback when you cannot use Git at all.

Free and open source. Complete code in this post — copy it from Steps 4–7. MIT licensed. Files: hook.py, sync.sh, three small Dockerfiles, Apache and Caddy config, docker-compose.yml, plus hook.php for the single-container variant. Originally developed by S&H Software Solutions – first published on APEX Note (October 2026).

TL;DR — what the setup does:

  • Verifies every webhook — HMAC-SHA256 over the raw body (X-Hub-Signature-256), compared in constant time; wrong or missing signature → 401
  • Reacts only to pushes on main of one repository — other branches, other events and branch deletions are logged and ignored
  • Treats the webhook as a doorbell — it never deploys what the payload says; git-sync always fetches the branch itself
  • Read-only deploy key (or a fine-grained token from a secret file) — never a token in a URL
  • No .git in the document root — releases are exported with git archive, and Apache denies every dotfile anyway
  • Atomic releases — one rename() of a symlink; 2,061 requests during 20 switches, zero broken pages
  • No docker.sock, read-only containers, dropped capabilities, separate networks, HTTPS via Caddy
  • Self-healing — health checks, a fallback sync every 5 minutes for lost webhooks, rollback and unpin

My First Three Attempts — and What Was Wrong With Them

I am showing these on purpose, because every one of them "worked", and every one of them is still a common answer on forums:

AttemptHow it workedWhat was wrong
1 · All in onephp:8.2-apache, apt-get install git at every start, git clone https://TOKEN@github.com/… into /var/www/html, a while true; nc -l -p 9001 loop as "webhook"Any request to port 9001 triggered a deploy. The token was written into /var/www/html/.git/config — served by Apache. git reset --hard rewrote files while visitors loaded them. If the loop died, nobody noticed.
2 · Three containersApache, an alpine/git container that pulls once, and a docker:cli container with /var/run/docker.sock that runs docker start git on every requestBetter separation — but the internet-facing container controlled the Docker daemon. docker.sock is root on the host. Same unsigned trigger, same .git in the document root.
3 · FTPdelfer/alpine-ftp-server next to Apache, user and password in the environment: block, passive ports 21100–21110Credentials in plain text in the compose file and on the wire, eleven open ports, file-by-file uploads (half-updated site), no history.

I rebuilt attempt 1 in the lab to check how bad it really is. The answer is one curl:

Terminal: curl against the naive setup returns HTTP 200 and the full .git/config including the remote URL with a token (redacted in the command); against the hardened setup /.git/config, /.git/HEAD, /.env and /.gitattributes return 403, README.md 404, index.php 200, and the release folder holds only index.php and version.php.
Real runFigure 1 — Top: my first attempt, rebuilt in the lab — /.git/config answers 200, remote URL with token included (redacted by the sed in the command). Bottom: the setup from this post — 403 for every dotfile, 404 for the export-ignored README, two PHP files in the release.

Tools like git-dumper turn a reachable .git folder into your complete source code and history in a few seconds. With the token in the remote URL, they also get read access to your GitHub repository. Everything below is designed so that this cannot happen — not by one rule, but by three independent ones.


One Container or Three? Variant A vs. Variant B

Both variants use the same deploy logic (sync.sh), the same Apache configuration and the same webhook rules. The difference is packaging — and that decides what an attacker gets if one piece is compromised:

Variant B architecture: GitHub, Caddy, hook, web, two volumes and git-sync GitHub sends a signed push event through Caddy to the hook container, which only writes a request file to the signal volume. The git-sync container reads that file, fetches the branch from GitHub over SSH with a read-only deploy key, exports a release into the site volume and switches the current symlink. The web container serves the site volume read-only; visitors reach it through Caddy over HTTPS. GitHub repository · webhook with secret Visitors https://www.example.com ① signed push event HTTPS proxy · Caddy only ports 80 + 443 are public · automatic HTTPS · one exact path to the hook POST /_hooks/github all other requests hook · hook.py checks the HMAC signature no git, no keys, no site access web · Apache + PHP 8.2 DocumentRoot → current denies /.git, /.env, dotfiles ② doorbell read-only mount volume: signal one small request file volume: site repo.git · releases/ · current → read-only mount ④ release + switch git-sync · sync.sh holds the read-only deploy key · writes the site · no published port, own network ③ git fetch over SSH · read-only deploy key
Figure 2 — Diagram: Variant B, who may do what. The internet-facing listener can only ring the doorbell; the container with the deploy key has no public port.
Variant A · one containerVariant B · web / hook / git-sync (recommended)
SimplicityOne image, one service, one port. Webhook is a PHP file inside Apache.Three small images, one compose file, Caddy in front.
SecurityThe PHP process that receives the webhook runs in the same container as the deploy key.The internet-facing listener has no git, no key, no site access — it can write one file. The container with the key has no published port.
Restart behaviourentrypoint.sh watches both processes; if one dies, the container exits and restarts (tested: restarts=1, site briefly down).Each service restarts on its own (tested: hook killed → restarted, site answered 200 throughout).
Blast radiusA bug in the webhook code = deploy key + site files.A bug in hook.py = at most a spurious "please sync" — which only re-deploys main.
Image size (compressed)≈ 190 MBweb 176 MB · hook 20.6 MB · git-sync 37.5 MB
Choose it whenA hobby site on a host that only runs this one thing.Anything with customers, secrets in the repo history, or other services on the host.

The steps below build Variant B. Variant A follows in its own section and reuses everything except the listener.

Tested on 7 October 2026 with Docker 29.6 and Compose 5.3, php:8.2-apache (PHP 8.2.34, Apache 2.4.68), python:3.12-alpine, alpine/git:2.54.0, Caddy 2.11 and atmoz/sftp:alpine. How I tested without exposing my server: a local Gitea 1.24 plays GitHub. It hosts the repository apexnote/demo-site, holds the read-only deploy key and sends the webhook — with the same X-GitHub-Event, X-GitHub-Delivery and X-Hub-Signature-256 headers GitHub sends. The edge cases (wrong secret, other branch, ping) were sent with curl, signed exactly like GitHub signs (Step 9). www.example.com pointed to the lab host and Caddy used its local CA. What I could not test here is GitHub's own UI and Let's Encrypt — those settings are described from GitHub's and Caddy's documentation.

Step-by-Step: From Repository to Auto-Deploy

01
Step one

Project Layout on the Server

one folder · 11 files · nothing of it lives in your website repository

The deployment stack is its own small project on the Docker host — your website repository stays a plain PHP project. Create this layout (e.g. in ~/site):

Text~/site
~/site
├── .env                      # Step 1
├── docker-compose.yml        # Step 7
├── Caddyfile                 # Step 7
├── known_hosts               # Step 2
├── secrets/                  # never commit this folder
│   ├── deploy_key            # Step 2
│   └── webhook_secret        # Step 3
├── web/       Dockerfile  site.conf  php.ini     # Step 4
├── hook/      Dockerfile  hook.py                # Step 5
├── git-sync/  Dockerfile  sync.sh                # Step 6
└── tools/     send-test-webhook.sh               # Step 9
.env.env
# copy to .env and adjust
SITE_DOMAIN=www.example.com
REPO_URL=git@github.com:your-name/your-site.git
REPO_FULL_NAME=your-name/your-site
DEPLOY_BRANCH=main
02
Step two

A Read-Only Deploy Key — and a Pinned Host Key

ssh-keygen · GitHub → Settings → Deploy keys · 2 minutes

A deploy key is an SSH key that belongs to one repository. Unlike a personal token it cannot see your other repositories, and with "Allow write access" unchecked it cannot push. Generate it without a passphrase (the container has to use it unattended) and give the files to the user IDs that read them — Compose mounts file secrets with the host's permissions, so chmod 600 as root would lock the containers out:

Bashon the Docker host, in ~/site
mkdir -p secrets
ssh-keygen -t ed25519 -N "" -C "deploy@www.example.com" -f secrets/deploy_key
chown 1000:1000 secrets/deploy_key && chmod 400 secrets/deploy_key   # read by git-sync (UID 1000)
cat secrets/deploy_key.pub                                            # -> GitHub, read-only deploy key

ssh-keyscan -t ed25519 github.com > known_hosts
ssh-keygen -lf known_hosts   # compare with GitHub's published Ed25519 fingerprint

In GitHub: Repository → Settings → Deploy keys → Add deploy key, paste secrets/deploy_key.pub, leave "Allow write access" unchecked.

The second file is known_hosts. sync.sh runs SSH with StrictHostKeyChecking=yes, so it refuses any server whose key it does not know — no silent "trust on first use" inside a container. Compare the fingerprint with the one GitHub publishes in its documentation (GitHub's SSH key fingerprints); for Ed25519 it is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.

Prefer HTTPS? Create a fine-grained personal access token for this one repository with Contents: Read-only, store it in secrets/git_token, add it to git-sync as a Compose secret, and set REPO_URL=https://github.com/your-name/your-site.git GIT_TOKEN_FILE=/run/secrets/git_token and GIT_USERNAME=your-github-user. sync.sh then acts as its own GIT_ASKPASS helper and hands the token to Git on request — it never appears in a URL, in .git/config or in ps.
03
Step three

Webhook Secret and GitHub Webhook

openssl rand · GitHub → Settings → Webhooks

The secret is the only thing that separates GitHub from everybody else on the internet. GitHub uses it to compute an HMAC-SHA256 over the request body and sends the result as X-Hub-Signature-256: sha256=<hex>. 32 random bytes are plenty:

Bashon the Docker host, in ~/site
openssl rand -hex 32 > secrets/webhook_secret
chown 1001:1001 secrets/webhook_secret && chmod 400 secrets/webhook_secret   # read by hook (UID 1001)
cat secrets/webhook_secret   # paste into GitHub (Step 3), then clear the terminal

Then Repository → Settings → Webhooks → Add webhook:

FieldValueWhy
Payload URLhttps://www.example.com/_hooks/githubSame domain as the site; Caddy routes only this path to the listener
Content typeapplication/jsonThe listener also accepts the form-encoded variant — the signature covers the raw body either way
Secretthe content of secrets/webhook_secretWithout it, every request is rejected with 401
SSL verificationEnabledCaddy has a real certificate
EventsJust the push eventThe listener ignores everything else, but there is no reason to receive it

GitHub sends a ping event right after you save. Once the stack runs (Step 7), Recent Deliveries shows it with a green 200 pong — and the Redeliver button there is your best friend for debugging.

04
Step four

The Web Container: Apache That Cannot Change Its Own Files

web/Dockerfile · site.conf · php.ini

The web container gets the site volume read-only. Apache serves /srv/site/current — a symlink that git-sync switches to the newest release. Three details matter: the LocationMatch rule that denies every path segment starting with a dot (except .well-known), RemoteIP so your logs show visitors and not Caddy, and one PHP setting that I only found because the first real test failed — more on that in How it works inside.

Dockerfileweb/Dockerfilecomplete · 9 lines
FROM php:8.2-apache
COPY site.conf /etc/apache2/sites-available/000-default.conf
COPY php.ini /usr/local/etc/php/conf.d/zz-deploy.ini
RUN a2enmod headers remoteip \
 && printf 'ServerName localhost\nServerTokens Prod\nServerSignature Off\n' > /etc/apache2/conf-available/zz-hardening.conf \
 && a2enconf zz-hardening \
 && mkdir -p /srv/site && chown 1000:1000 /srv/site
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s \
  CMD curl -fsS -o /dev/null http://127.0.0.1/ || exit 1
Apacheweb/site.confcomplete · 26 lines
<VirtualHost *:80>
    ServerName www.example.com
    # "current" is a symlink that git-sync swaps atomically to the new release
    DocumentRoot /srv/site/current

    <Directory /srv/site>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Never serve VCS data or dotfiles (.git, .env, .htpasswd ...) - except .well-known
    <LocationMatch "/\.(?!well-known/)">
        Require all denied
    </LocationMatch>

    # Real client IP from the reverse proxy (Caddy) in the Docker network
    RemoteIPHeader X-Forwarded-For
    RemoteIPInternalProxy 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16

    Header always set X-Content-Type-Options "nosniff"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
INIweb/php.inicomplete · 8 lines
expose_php = Off

; Symlink deploys: every Apache worker caches the resolved path of "current"
; (-> releases/<old commit>) for realpath_cache_ttl seconds - 120 by default,
; so visitors keep getting the OLD release for up to two minutes.
; 1 second keeps the cache useful and makes the switch effectively instant.
; (0 does NOT disable it - with 0 the entries never expire.)
realpath_cache_ttl = 1
05
Step five

The Webhook Listener: hook.py

Python standard library only · ~140 lines · runs as UID 1001

I looked at adnanh/webhook first — a good tool, and if you already use it, its payload-hmac-sha256 rule does the same check. I chose a small Python listener for three reasons: zero dependencies (the official python:3.12-alpine image is enough, no apk add), exact HTTP status codes that make GitHub's delivery log readable (401 for a bad signature, 202 for "ignored"), and every line that matters for security fits on one screen. Read the three numbered blocks in handle_delivery — that is the whole security model:

Pythonhook/hook.pycomplete · 142 lines
#!/usr/bin/env python3
"""hook.py - a tiny GitHub webhook listener (Python standard library only).

It checks the X-Hub-Signature-256 HMAC, accepts push events for one branch
and then only "rings the doorbell": it writes a small request file that
sync.sh watches. It never runs git and never trusts the payload for WHAT to
deploy - sync.sh always fetches the branch from the repository itself.

Originally developed by S&H Software Solutions - first published on
APEX Note (www.apexnote.de), October 2026. MIT licence.
"""
import hashlib
import hmac
import json
import os
import signal
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs

PORT = int(os.environ.get("HOOK_PORT", "9000"))
HOOK_PATH = os.environ.get("HOOK_PATH", "/hooks/github")
BRANCH = os.environ.get("DEPLOY_BRANCH", "main")
REPO = os.environ.get("REPO_FULL_NAME", "")          # optional: "owner/repo"
REQUEST_FILE = os.environ.get("REQUEST_FILE", "/signal/request")
MAX_BODY = int(os.environ.get("MAX_BODY_BYTES", str(5 * 1024 * 1024)))
SECRET_FILE = os.environ.get("WEBHOOK_SECRET_FILE", "/run/secrets/webhook_secret")


def log(msg):
    print(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "hook", msg, flush=True)


try:
    with open(SECRET_FILE, "rb") as f:
        SECRET = f.read().strip()            # "echo secret > file" adds a newline
except OSError as e:
    sys.exit(f"hook: cannot read webhook secret: {e}")
if len(SECRET) < 16:
    sys.exit("hook: webhook secret is empty or shorter than 16 characters")


def ring_doorbell(after, delivery):
    """Atomically replace the request file - sync.sh never reads half a file."""
    tmp = f"{REQUEST_FILE}.{os.getpid()}.{threading.get_ident()}.tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump({"after": after, "delivery": delivery, "at": int(time.time())}, f)
    os.replace(tmp, REQUEST_FILE)


class Hook(BaseHTTPRequestHandler):
    server_version = "hook"
    sys_version = ""
    timeout = 10                             # slow or stuck clients are dropped

    def log_message(self, *args):            # one line per delivery is enough
        pass

    def reply(self, code, text):
        body = (text + "\n").encode()
        self.send_response(code)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/healthz":
            self.reply(200, "ok")
        else:
            self.reply(404, "not found")

    def do_POST(self):
        delivery = self.headers.get("X-GitHub-Delivery", "-")[:64]
        event = self.headers.get("X-GitHub-Event", "-")[:64]
        try:
            code, text = self.handle_delivery(event, delivery)
        except Exception as e:               # never leak a traceback to the caller
            log(f"internal error: {e!r}")
            code, text = 500, "internal error"
        log(f"{code} event={event} delivery={delivery} {text}")
        self.reply(code, text)

    def handle_delivery(self, event, delivery):
        if self.path.split("?", 1)[0] != HOOK_PATH:
            return 404, "not found"
        try:
            length = int(self.headers.get("Content-Length", ""))
        except ValueError:
            return 411, "length required"
        if length < 0 or length > MAX_BODY:
            return 413, "payload too large"
        body = self.rfile.read(length)

        # 1. Authenticity: HMAC-SHA256 over the RAW body, compared in constant time
        expected = "sha256=" + hmac.new(SECRET, body, hashlib.sha256).hexdigest()
        received = self.headers.get("X-Hub-Signature-256", "")
        if not hmac.compare_digest(expected.encode(), received.encode("utf-8", "replace")):
            return 401, "bad signature"

        # 2. Only push events for the deploy branch
        if event == "ping":
            return 200, "pong"
        if event != "push":
            return 202, f"ignored event {event}"
        try:
            if self.headers.get("Content-Type", "").startswith("application/x-www-form-urlencoded"):
                body = parse_qs(body.decode("utf-8"))["payload"][0]
            data = json.loads(body)
        except (ValueError, KeyError, IndexError):
            return 400, "invalid payload"
        if not isinstance(data, dict):
            return 400, "invalid payload"
        repo = (data.get("repository") or {}).get("full_name", "")
        if REPO and repo != REPO:
            return 403, f"wrong repository {repo}"
        ref = str(data.get("ref", ""))
        if ref != f"refs/heads/{BRANCH}":
            return 202, f"ignored {ref[:80]}"
        if data.get("deleted"):
            return 202, "ignored branch deletion"

        # 3. Ring the doorbell - the actual deploy runs in sync.sh
        after = str(data.get("after", ""))[:40]
        ring_doorbell(after, delivery)
        return 202, f"deploy queued for {after[:7]}"


def main():
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
    os.umask(0o022)
    server = ThreadingHTTPServer(("0.0.0.0", PORT), Hook)
    server.daemon_threads = True
    log(f"listening on :{PORT}{HOOK_PATH} - branch {BRANCH}"
        + (f", repository {REPO}" if REPO else ""))
    server.serve_forever()


if __name__ == "__main__":
    main()
Dockerfilehook/Dockerfilecomplete · 7 lines
# Internet-facing listener: Python standard library only - no git, no ssh, no shell tools needed
FROM python:3.12-alpine
RUN adduser -D -H -u 1001 hook && mkdir /signal && chown hook:hook /signal
COPY --chmod=755 hook.py /usr/local/bin/hook.py
USER hook
EXPOSE 9000
ENTRYPOINT ["hook.py"]

Two details are easy to get wrong. The HMAC is computed over the raw bytes as received — never over re-serialised JSON — and compared with hmac.compare_digest, which takes the same time no matter where the first difference is. And the listener answers within milliseconds: GitHub gives up after 10 seconds, so a listener that runs git before answering will eventually show red deliveries for deployments that actually worked.

06
Step six

git-sync: Fetch, Export, Switch

sync.sh · POSIX sh · runs as UID 1000 · no published port

sync.sh is the only part that touches Git and the site. It keeps a bare clone outside the document root, exports each commit into its own releases/<commit> folder and switches current with a single rename(). It deploys at start, whenever the request file changes, and every 5 minutes as a fallback. It also has status, rollback and unpin commands:

Shellgit-sync/sync.shcomplete · 143 lines
#!/bin/sh
# sync.sh - fetch the deploy branch and switch the website atomically.
#
#   sync.sh            watch loop: deploy at start, on every doorbell from
#                      hook.py and every FALLBACK_INTERVAL seconds
#   sync.sh once       deploy once and exit
#   sync.sh status     show the live release and the kept ones
#   sync.sh rollback   switch back to the previous release and pin it
#   sync.sh unpin      remove the pin and deploy the branch again
#
# Layout under $SITE_DIR (only "current" is visible to Apache):
#   repo.git/              bare clone - the .git data never reaches the docroot
#   releases/<commit>/     one exported tree per deployed commit
#   current -> releases/<commit>   swapped with a single rename()
#
# Originally developed by S&H Software Solutions - first published on
# APEX Note (www.apexnote.de), October 2026. MIT licence.

# git calls this script again as GIT_ASKPASS when GIT_TOKEN_FILE is used
case "${1:-}" in
  Username*) printf '%s\n' "${GIT_USERNAME:-x-access-token}"; exit 0 ;;
  Password*) cat "$GIT_TOKEN_FILE"; exit 0 ;;
esac

set -eu
umask 022

REPO_URL=${REPO_URL:?set REPO_URL, e.g. git@github.com:owner/site.git}
BRANCH=${DEPLOY_BRANCH:-main}
SITE=${SITE_DIR:-/srv/site}
REQUEST_FILE=${REQUEST_FILE:-/signal/request}
KEEP=${KEEP_RELEASES:-5}
FALLBACK=${FALLBACK_INTERVAL:-300}
REQUIRED_FILE=${REQUIRED_FILE:-index.php}
KEY=${DEPLOY_KEY_FILE:-/run/secrets/deploy_key}
KNOWN_HOSTS=${KNOWN_HOSTS_FILE:-/etc/deploy/known_hosts}

SELF=$(readlink -f "$0")
MIRROR=$SITE/repo.git
REL=$SITE/releases

export GIT_TERMINAL_PROMPT=0
if [ -n "${GIT_TOKEN_FILE:-}" ]; then          # HTTPS + fine-grained token
  export GIT_ASKPASS="$SELF"
else                                           # SSH + read-only deploy key
  export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o BatchMode=yes \
-o StrictHostKeyChecking=yes -o UserKnownHostsFile=$KNOWN_HOSTS"
fi

log() { printf '%s sync %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; }

switch_to() {                                  # atomic: one rename() of a symlink
  ln -sfn "releases/$1" "$SITE/.current.new"
  mv -Tf "$SITE/.current.new" "$SITE/current"
}

deploy() {
  if [ -f "$SITE/pinned" ]; then
    log "pinned to $(cat "$SITE/pinned") - not deploying (run: sync.sh unpin)"
    return 0
  fi
  started=$(date +%s)
  if [ ! -d "$MIRROR" ]; then
    log "first run: cloning branch $BRANCH"
    rm -rf "$MIRROR.tmp"
    git clone --quiet --bare --single-branch --branch "$BRANCH" "$REPO_URL" "$MIRROR.tmp"
    mv "$MIRROR.tmp" "$MIRROR"
  fi
  git -C "$MIRROR" fetch --quiet --prune origin "+refs/heads/$BRANCH:refs/heads/$BRANCH"
  sha=$(git -C "$MIRROR" rev-parse --verify "refs/heads/$BRANCH^{commit}")
  short=$(git -C "$MIRROR" rev-parse --short "$sha")
  date +%s > "$SITE/last_ok"                   # read by the health check

  if [ "$(readlink "$SITE/current" 2>/dev/null || true)" = "releases/$sha" ]; then
    log "already live: $short"
    return 0
  fi

  mkdir -p "$REL"
  if [ ! -d "$REL/$sha" ]; then
    tmp=$(mktemp -d "$REL/.tmp-XXXXXX")
    git -C "$MIRROR" archive --format=tar --output="$tmp.tar" "$sha"
    tar -x -f "$tmp.tar" -C "$tmp"
    rm -f "$tmp.tar"
    chmod 755 "$tmp"                           # mktemp -d creates mode 700
    if [ ! -e "$tmp/$REQUIRED_FILE" ]; then
      rm -rf "$tmp"
      log "ERROR: $short has no $REQUIRED_FILE - refusing to deploy it"
      return 1
    fi
    mv "$tmp" "$REL/$sha"
  fi
  switch_to "$sha"
  log "live: $short \"$(git -C "$MIRROR" log -1 --format=%s "$sha")\" in $(( $(date +%s) - started ))s"

  # keep the newest $KEEP releases, never the live one
  ls -1t "$REL" | tail -n +"$((KEEP + 1))" | while read -r old; do
    [ "$old" = "$sha" ] || rm -rf "${REL:?}/$old"
  done
}

watch() {
  rm -rf "$REL"/.tmp-* 2>/dev/null || true
  log "watching $REQUEST_FILE - branch $BRANCH, fallback sync every ${FALLBACK}s"
  last=""
  next=0
  while :; do
    req=$(cat "$REQUEST_FILE" 2>/dev/null || true)
    now=$(date +%s)
    if [ "$req" != "$last" ] || [ "$now" -ge "$next" ]; then
      [ "$req" != "$last" ] && log "doorbell: $req"
      last=$req
      next=$((now + FALLBACK))
      # a child process, so "set -e" really stops a failed deploy halfway
      "$SELF" once || log "ERROR: deploy failed - site unchanged, next try in ${FALLBACK}s"
    fi
    sleep 1
  done
}

case "${1:-watch}" in
  watch) watch ;;
  once) deploy ;;
  status)
    live=$(readlink "$SITE/current" 2>/dev/null || echo none)
    echo "live:     $live"
    [ -f "$SITE/pinned" ] && echo "pinned:   yes (sync.sh unpin)"
    for r in $(ls -1t "$REL" 2>/dev/null); do
      mark=" "; [ "releases/$r" = "$live" ] && mark="*"
      echo "$mark $(git -C "$MIRROR" log -1 --format='%h  %ci  %s' "$r")"
    done ;;
  rollback)
    live=$(readlink "$SITE/current")
    prev=$(ls -1t "$REL" | sed -n "/^${live#releases/}\$/{n;p;q}")    # next older one
    [ -n "$prev" ] || { log "no previous release to roll back to"; exit 1; }
    switch_to "$prev"
    echo "$prev" > "$SITE/pinned"
    log "rolled back to $(git -C "$MIRROR" rev-parse --short "$prev") and pinned - run 'sync.sh unpin' to deploy $BRANCH again" ;;
  unpin)
    rm -f "$SITE/pinned"
    deploy ;;
  *) echo "usage: sync.sh [watch|once|status|rollback|unpin]" >&2; exit 2 ;;
esac
Dockerfilegit-sync/Dockerfilecomplete · 7 lines
# Has the deploy key and write access to the site - but no published port
FROM alpine/git:2.54.0
RUN adduser -D -H -u 1000 deploy && mkdir -p /srv/site /etc/deploy && chown deploy:deploy /srv/site
COPY --chmod=755 sync.sh /usr/local/bin/sync.sh
USER deploy
ENV HOME=/tmp
ENTRYPOINT ["sync.sh"]
07
Step seven

docker-compose.yml and Caddy — Then Start It

4 services · 2 networks · only 80/443 public

Every service gets only what it needs: hook mounts the signal volume and the webhook secret; git-sync mounts the site volume, the deploy key and known_hosts, and sits alone on its own network; both run with a read-only root filesystem, cap_drop: [ALL] and no-new-privileges. Caddy gets a certificate from Let's Encrypt automatically and forwards exactly one method and path to the listener:

YAMLdocker-compose.ymlcomplete · 85 lines
# Variant B - separated containers: web / git-sync / hook (+ Caddy for HTTPS)
name: site

services:
  proxy:
    image: caddy:2.11-alpine
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp"
    environment:
      SITE_DOMAIN: ${SITE_DOMAIN:?set SITE_DOMAIN in .env}
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    networks: [front]

  web:
    build: ./web
    restart: unless-stopped
    volumes:
      - site:/srv/site:ro                    # Apache can read the site, never change it
    networks: [front]

  hook:
    build: ./hook
    init: true
    restart: unless-stopped
    environment:
      HOOK_PATH: /_hooks/github
      DEPLOY_BRANCH: ${DEPLOY_BRANCH:-main}
      REPO_FULL_NAME: ${REPO_FULL_NAME:-}
    secrets: [webhook_secret]
    volumes:
      - signal:/signal                       # the only thing it can write to
    read_only: true
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    healthcheck:
      test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:9000/healthz', timeout=2)"]
      interval: 30s
      timeout: 3s
    networks: [front]

  git-sync:
    build: ./git-sync
    init: true
    restart: unless-stopped
    environment:
      REPO_URL: ${REPO_URL:?set REPO_URL in .env}
      DEPLOY_BRANCH: ${DEPLOY_BRANCH:-main}
      FALLBACK_INTERVAL: "300"
      KEEP_RELEASES: "5"
    secrets: [deploy_key]
    volumes:
      - site:/srv/site
      - signal:/signal:ro
      - ./known_hosts:/etc/deploy/known_hosts:ro
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    healthcheck:
      test: ["CMD-SHELL", "test -L /srv/site/current && find /srv/site/last_ok -mmin -15 | grep -q ."]
      interval: 60s
      timeout: 5s
    networks: [sync]                         # no route to web, hook or proxy

secrets:
  webhook_secret:
    file: ./secrets/webhook_secret
  deploy_key:
    file: ./secrets/deploy_key

volumes:
  site:
  signal:
  caddy_data:
  caddy_config:

networks:
  front:
  sync:
CaddyfileCaddyfilecomplete · 21 lines
{$SITE_DOMAIN} {
	encode zstd gzip

	# Only POST to this one path reaches the webhook listener
	@hook {
		method POST
		path /_hooks/github
	}
	handle @hook {
		request_body {
			max_size 5MB
		}
		reverse_proxy hook:9000
	}

	handle {
		reverse_proxy web:80
	}

	log
}
Bashon the Docker host, in ~/site
cp .env.example .env && nano .env        # SITE_DOMAIN, REPO_URL, REPO_FULL_NAME
docker compose up -d --build
docker compose logs -f git-sync hook     # first clone, then: sync live: <commit> ...
Outputdocker compose psreal run · lab adds Gitea
$ docker compose ps --format "table {{.Service}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
SERVICE    IMAGE              STATUS                    PORTS
git-sync   blog2-git-sync     Up 3 minutes (healthy)    
gitea      gitea/gitea:1.24   Up 3 minutes              22/tcp, 127.0.0.1:3000->3000/tcp
hook       blog2-hook         Up 39 seconds (healthy)   9000/tcp
proxy      caddy:2-alpine     Up 3 minutes              127.0.0.1:80->80/tcp, 127.0.0.1:443->443/tcp, 443/udp, 2019/tcp
web        blog2-web          Up 3 minutes (healthy)    80/tcp

hook and web show only their internal ports — nothing but Caddy is reachable from outside. If you already run Traefik or nginx, drop the proxy service and route /_hooks/github (POST only) to hook:9000 and everything else to web:80.

08
Step eight

The First Push

git commit · git push · measured: 1,381 ms

On first start, git-sync clones the branch and deploys it — this is Version 1 of the demo site. The page shows the commit, the deploy time and the release folder it was served from:

Chromium showing https://www.example.com: the APEX Note Demo Site, Version 1, commit 3cbd351 'Version 1: first page', deployed 2026-10-07 19:45:00 UTC from releases/3cbd351..., PHP 8.2.34.
Real runFigure 3 — Before the push: Version 1 in Chromium, served by Caddy over HTTPS. Commit, deploy time and release folder come from the deployment itself.

The commit hash comes from Git without a .git folder on the server: version.php contains placeholders like $Format:%h$, and git archive fills them in because .gitattributes marks the file with export-subst. The same file keeps README.md and tests away from the server with export-ignore:

Textsite-example/.gitattributescomplete · 6 lines
# git archive fills in $Format:...$ placeholders in this file
version.php export-subst
# files that stay in Git but never reach the web server
.gitattributes export-ignore
README.md      export-ignore
tests/         export-ignore
PHPsite-example/version.phpcomplete · 7 lines
<?php
// Filled in by "git archive" (see .gitattributes) - no .git folder needed on the server
return [
    'commit' => '$Format:%h$',
    'date'   => '$Format:%cI$',
    'title'  => '$Format:%s$',
];
PHPsite-example/index.phpcomplete · 56 lines
<?php
$v = require __DIR__ . '/version.php';           // filled in by "git archive"
$version = 'Version 1';
$release = substr(basename(__DIR__), 0, 12);     // releases/<commit> this request was served from
$deployed = gmdate('Y-m-d H:i:s', filemtime(__DIR__)) . ' UTC';
$h = fn($s) => htmlspecialchars((string) $s, ENT_QUOTES);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>APEX Note Demo Site</title>
  <style>
    :root { --k: #111; --r: #fd3a13; --y: #ffbd2e; --g: #28c840; }
    * { box-sizing: border-box; }
    body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px;
           font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; background: #f2f2f0; color: var(--k); }
    .card { width: min(620px, 100%); background: #fff; border-radius: 14px; overflow: hidden;
            box-shadow: 0 14px 40px rgba(0,0,0,.12); }
    .stripe { display: flex; height: 8px; } .stripe i { flex: 1; }
    .stripe i:nth-child(1) { background: var(--r); } .stripe i:nth-child(2) { background: var(--y); }
    .stripe i:nth-child(3) { background: var(--g); }
    header { background: var(--k); color: #fff; padding: 18px 30px; display: flex; align-items: center;
             justify-content: space-between; }
    .brand { font-weight: 800; letter-spacing: .5px; } .brand b { color: var(--r); }
    .ver { font: 700 13px ui-monospace, monospace; padding: 4px 12px; border-radius: 99px;
           background: var(--y); color: var(--k); }
    main { padding: 28px 30px 30px; }
    h1 { margin: 0 0 6px; font-size: 30px; line-height: 1.15; }
    .lead { margin: 0 0 22px; color: #555; }
    dl { display: grid; grid-template-columns: 110px 1fr; gap: 8px 14px; margin: 0; font-size: 14px;
         border-top: 1px solid #eee; padding-top: 18px; }
    dt { color: #777; } dd { margin: 0; font-family: ui-monospace, "JetBrains Mono", monospace; word-break: break-word; }
    .ok { color: #1a8f32; font-weight: 700; }
  </style>
</head>
<body>
  <div class="card">
    <div class="stripe"><i></i><i></i><i></i></div>
    <header><span class="brand"><b>APEX</b> Note &middot; Lab</span><span class="ver"><?= $h($version) ?></span></header>
    <main>
      <h1>APEX Note Demo Site</h1>
      <p class="lead">A plain PHP site that deploys itself on every <code>git push</code>.</p>
      <dl>
        <dt>Status</dt><dd class="ok">&#10003; live</dd>
        <dt>Commit</dt><dd><?= $h($v['commit']) ?> &middot; <?= $h($v['title']) ?></dd>
        <dt>Committed</dt><dd><?= $h($v['date']) ?></dd>
        <dt>Deployed</dt><dd><?= $h($deployed) ?></dd>
        <dt>Release</dt><dd>releases/<?= $h($release) ?>&hellip;</dd>
        <dt>PHP</dt><dd><?= PHP_VERSION ?></dd>
      </dl>
    </main>
  </div>
</body>
</html>

Now change the intro text, commit, push — and measure how long it takes until the page shows the new version:

Terminal: git commit 'Version 2: new intro text', git push, and a curl loop that reports the new version live 1381 ms after git push; below, the hook log shows 202 deploy queued and the git-sync log shows doorbell and live 4414865 in 1s.
Real runFigure 4 — The real push: commit, push and a curl loop that waits for the new page — live after 1,381 ms. Below, the logs of hook and git-sync for the same delivery.

1.4 seconds from git push to the new page, including Gitea's delivery, Caddy, the signature check, the fetch over SSH and the export. The log at the bottom is worth reading too: when the stack started, Gitea was still booting, the first clone failed with Connection refused — and the next doorbell fixed it without anybody touching anything.

Chromium showing https://www.example.com after the push: Version 2 badge, new intro text, commit 4414865 'Version 2: new intro text', new release folder releases/4414865....
Real runFigure 5 — After the push: Version 2, commit 4414865, a new release folder — no FTP involved.
09
Step nine

Verify the Security — Send Webhooks Like GitHub Does

tools/send-test-webhook.sh · openssl + curl

You should not trust a webhook listener you have only seen succeed. This script builds a push payload, signs it with openssl dgst -sha256 -hmac exactly as GitHub does and sends GitHub's headers — so you can test every rule without pushing anything:

Bashtools/send-test-webhook.shcomplete · 18 lines
#!/usr/bin/env bash
# Send a push event signed exactly like GitHub signs it (X-Hub-Signature-256).
#   usage: send-test-webhook.sh URL SECRET_FILE [branch] [event]
#   extra curl options via CURL_OPTS, e.g. CURL_OPTS="--cacert root.crt"
set -euo pipefail
url=$1 secret_file=$2 branch=${3:-main} event=${4:-push}

payload=$(printf '{"ref":"refs/heads/%s","after":"%s","deleted":false,"repository":{"full_name":"%s"}}' \
  "$branch" "$(openssl rand -hex 20)" "${REPO_FULL_NAME:-your-name/your-site}")
sig=$(printf '%s' "$payload" | openssl dgst -sha256 -hmac "$(cat "$secret_file")" | sed 's/^.*= //')

curl -sS ${CURL_OPTS:-} -X POST "$url" -w '  [HTTP %{http_code}]\n' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: GitHub-Hookshot/send-test-webhook' \
  -H "X-GitHub-Event: $event" \
  -H "X-GitHub-Delivery: $(cat /proc/sys/kernel/random/uuid)" \
  -H "X-Hub-Signature-256: sha256=$sig" \
  --data-binary "$payload"
Terminal: send-test-webhook.sh with the correct secret returns 202 deploy queued; with a wrong secret and without signature 401 bad signature; push to feature/login 202 ignored; ping 200 pong; the logs show git-sync answering already live.
Real runFigure 6 — Signed like GitHub signs: valid → 202, wrong secret → 401, no signature → 401, other branch → ignored, ping → pong.

Read the last block from the bottom up: the valid push to main carried a made-up commit (fbbb05c) — and git-sync answered already live: 4414865, because it never deploys what a payload claims. Then check that nothing private is reachable — the second half of the .git screenshot at the top shows the result for this setup: 403 for /.git/config, /.git/HEAD, /.env and /.gitattributes, 404 for the export-ignored README.md, and the release folder contains only index.php and version.php.


Variant A: Everything in One Container

If you really want one container: Apache and PHP already run, so the listener becomes a PHP file served by Apache itself — hook.php follows the same rules as hook.py with hash_hmac and hash_equals. It lives in /opt/hook, outside the deployed site, and is mapped to the webhook path with an Alias. sync.sh runs next to Apache as user deploy; Apache's www-data can write the request file and nothing else. The build context is the project root, so the files from Steps 4 and 6 are reused unchanged:

Dockerfilesingle/Dockerfilecomplete · 21 lines
# Variant A - one container: Apache + PHP (site and webhook) + sync.sh
# build context is the project root (see single/docker-compose.yml)
FROM php:8.2-apache
RUN apt-get update \
 && apt-get install -y --no-install-recommends git openssh-client \
 && rm -rf /var/lib/apt/lists/* \
 && groupadd -g 1000 deploy \
 && useradd -u 1000 -g deploy -M -d /nonexistent -s /usr/sbin/nologin deploy \
 && mkdir -p /srv/site /signal /etc/deploy /opt/hook \
 && chown deploy:deploy /srv/site && chown www-data:www-data /signal \
 && a2enmod headers remoteip \
 && printf 'ServerName localhost\nServerTokens Prod\nServerSignature Off\n' > /etc/apache2/conf-available/zz-hardening.conf \
 && a2enconf zz-hardening
COPY web/site.conf /etc/apache2/sites-available/000-default.conf
COPY web/php.ini /usr/local/etc/php/conf.d/zz-deploy.ini
COPY single/hook.conf /etc/apache2/conf-enabled/hook.conf
COPY single/hook.php /opt/hook/hook.php
COPY --chmod=755 git-sync/sync.sh single/entrypoint.sh /usr/local/bin/
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s \
  CMD curl -fsS -o /dev/null http://127.0.0.1/ || exit 1
ENTRYPOINT ["entrypoint.sh"]
Bashsingle/entrypoint.shcomplete · 13 lines
#!/bin/bash
# Variant A: Apache and sync.sh in one container. If either of them dies, the
# container exits and Docker's restart policy starts both again - no silent death.
set -euo pipefail

HOME=/nonexistent setpriv --reuid=deploy --regid=deploy --clear-groups sync.sh &
apache2-foreground &

trap 'kill -TERM $(jobs -p) 2>/dev/null; wait; exit 0' TERM INT
wait -n
echo "entrypoint: a process exited - stopping the container so Docker restarts it" >&2
kill -TERM $(jobs -p) 2>/dev/null || true
exit 1
PHPsingle/hook.phpcomplete · 77 lines
<?php
// hook.php - GitHub webhook listener for Variant A, served by Apache/PHP itself.
// Same rules as hook.py: verify X-Hub-Signature-256, accept only push events for
// one branch, then ring the doorbell for sync.sh. It never runs git.
// Originally developed by S&H Software Solutions - first published on APEX Note
// (www.apexnote.de), October 2026. MIT licence.
declare(strict_types=1);

const MAX_BODY = 5 * 1024 * 1024;

function done(int $code, string $text): never
{
    error_log(sprintf('hook %d event=%s delivery=%s %s', $code,
        substr($_SERVER['HTTP_X_GITHUB_EVENT'] ?? '-', 0, 64),
        substr($_SERVER['HTTP_X_GITHUB_DELIVERY'] ?? '-', 0, 64), $text));
    http_response_code($code);
    header('Content-Type: text/plain; charset=utf-8');
    exit($text . "\n");
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    done(405, 'method not allowed');
}
$secret = trim((string) @file_get_contents(getenv('WEBHOOK_SECRET_FILE') ?: '/run/secrets/webhook_secret'));
if (strlen($secret) < 16) {
    done(500, 'webhook secret missing or too short');
}
$body = (string) file_get_contents('php://input', false, null, 0, MAX_BODY + 1);
if (strlen($body) > MAX_BODY) {
    done(413, 'payload too large');
}

// 1. Authenticity: HMAC-SHA256 over the raw body, constant-time comparison
$expected = 'sha256=' . hash_hmac('sha256', $body, $secret);
if (!hash_equals($expected, (string) ($_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? ''))) {
    done(401, 'bad signature');
}

// 2. Only push events for the deploy branch
$event = $_SERVER['HTTP_X_GITHUB_EVENT'] ?? '-';
if ($event === 'ping') {
    done(200, 'pong');
}
if ($event !== 'push') {
    done(202, 'ignored event ' . substr($event, 0, 64));
}
if (str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'application/x-www-form-urlencoded')) {
    parse_str($body, $form);
    $body = (string) ($form['payload'] ?? '');
}
$data = json_decode($body, true);
if (!is_array($data)) {
    done(400, 'invalid payload');
}
$repo = (string) ($data['repository']['full_name'] ?? '');
$want = getenv('REPO_FULL_NAME') ?: '';
if ($want !== '' && $repo !== $want) {
    done(403, 'wrong repository ' . $repo);
}
$branch = getenv('DEPLOY_BRANCH') ?: 'main';
$ref = (string) ($data['ref'] ?? '');
if ($ref !== 'refs/heads/' . $branch) {
    done(202, 'ignored ' . substr($ref, 0, 80));
}
if (!empty($data['deleted'])) {
    done(202, 'ignored branch deletion');
}

// 3. Ring the doorbell: write a temp file, then rename() it into place
$after = substr((string) ($data['after'] ?? ''), 0, 40);
$file = getenv('REQUEST_FILE') ?: '/signal/request';
$tmp = $file . '.' . getmypid() . '.tmp';
$json = json_encode(['after' => $after, 'delivery' => $_SERVER['HTTP_X_GITHUB_DELIVERY'] ?? '-', 'at' => time()]);
if (file_put_contents($tmp, $json) === false || !rename($tmp, $file)) {
    done(500, 'cannot write request file');
}
done(202, 'deploy queued for ' . substr($after, 0, 7));
Apachesingle/hook.confcomplete · 6 lines
# The webhook URL is served by hook.php - outside the deployed site
Alias "/_hooks/github" "/opt/hook/hook.php"
<Directory "/opt/hook">
    Require all granted
    LimitRequestBody 5242880
</Directory>
YAMLsingle/docker-compose.ymlcomplete · 29 lines
# Variant A - one container (Apache + PHP webhook + git sync)
name: site-single

services:
  site:
    build:
      context: ..
      dockerfile: single/Dockerfile
    init: true
    restart: unless-stopped
    ports:
      - "8080:80"                            # put Caddy/Traefik/nginx with HTTPS in front
    environment:
      REPO_URL: ${REPO_URL:?set REPO_URL in .env}
      REPO_FULL_NAME: ${REPO_FULL_NAME:-}
      DEPLOY_BRANCH: ${DEPLOY_BRANCH:-main}
    secrets: [webhook_secret, deploy_key]
    volumes:
      - site:/srv/site
      - ../known_hosts:/etc/deploy/known_hosts:ro

secrets:
  webhook_secret:
    file: ../secrets/webhook_secret
  deploy_key:
    file: ../secrets/deploy_key

volumes:
  site:
Lab note: the Debian package mirrors were not reachable from my lab, so the apt-get install git openssh-client line could not run there. For the test, git and ssh were copied from a Debian 13 image of the same release (buildpack-deps:trixie-scm); every other line of the Dockerfile and all scripts ran unchanged.
OutputVariant A in the labreal run · port 8088 in the lab
$ export REPO_FULL_NAME=apexnote/demo-site HOOK=http://localhost:8088/_hooks/github
$ tools/send-test-webhook.sh $HOOK secrets/webhook_secret
deploy queued for 297a288
  [HTTP 202]
$ tools/send-test-webhook.sh $HOOK /tmp/wrong-secret
bad signature
  [HTTP 401]
$ curl -s -o /dev/null -w "%{http_code}  GET /_hooks/github\n" $HOOK; curl -s -o /dev/null -w "%{http_code}  /.git/config\n" http://localhost:8088/.git/config
405  GET /_hooks/github
403  /.git/config
$ docker logs --since 15s blog2-single 2>&1 | grep -E "hook|sync"
[Wed Oct 07 19:50:46.285060 2026] [php:notice] [pid 35:tid 35] [client 172.18.0.1:53478] hook 202 event=push delivery=d0f6e183-1640-4908-9d6e-e321d594c62e deploy queued for 297a288
172.18.0.1 - - [07/Oct/2026:19:50:46 +0000] "POST /_hooks/github HTTP/1.1" 202 248 "-" "GitHub-Hookshot/send-test-webhook"
[Wed Oct 07 19:50:46.309987 2026] [php:notice] [pid 36:tid 36] [client 172.18.0.1:53494] hook 401 event=push delivery=4962ad9b-91b2-451f-94c4-533c1250ec9a bad signature
172.18.0.1 - - [07/Oct/2026:19:50:46 +0000] "POST /_hooks/github HTTP/1.1" 401 240 "-" "GitHub-Hookshot/send-test-webhook"
2026-10-07T19:50:46Z sync doorbell: {"after":"297a28863be22cf29af2b4136c704ab093e208d4","delivery":"d0f6e183-1640-4908-9d6e-e321d594c62e","at":1791402646}
[Wed Oct 07 19:50:46.320326 2026] [php:notice] [pid 37:tid 37] [client 172.18.0.1:53504] hook 405 event=- delivery=- method not allowed
172.18.0.1 - - [07/Oct/2026:19:50:46 +0000] "GET /_hooks/github HTTP/1.1" 405 251 "-" "curl/8.5.0"
# restart behaviour: kill the sync loop inside the single container
$ docker exec blog2-single pkill -f "sync.sh"; sleep 4; docker inspect -f "{{.State.Status}}  restarts={{.RestartCount}}" blog2-single; docker logs --tail 30 blog2-single 2>&1 | grep -E "entrypoint|sync (watching|live|already)"
running  restarts=1
2026-10-07T19:50:29Z sync watching /signal/request - branch main, fallback sync every 300s
2026-10-07T19:50:30Z sync live: 9db746e "Version 3: pushed while the hook was down" in 1s
2026-10-07T19:50:47Z sync watching /signal/request - branch main, fallback sync every 300s
2026-10-07T19:50:47Z sync already live: 9db746e

Note the last block: killing sync.sh stops the whole container (restarts=1), and Docker brings both processes back. That is the honest price of Variant A — and still far better than the while true loop of my first attempt, which could die silently while Apache kept serving an old version forever.


Bonus: No Git? Use SFTP — Never Plain FTP

Sometimes the files do not come from Git: a designer delivers a folder, a customer's agency builds a static export. My old answer was an FTP container. Here is why I stopped:

  • FTP sends the password in clear text — every hop between you and the server can read it (and mine was also sitting in docker-compose.yml)
  • Passive mode needs a port range and the public IP in the configuration — eleven open ports for one upload
  • No integrity, no atomicity — a dropped connection leaves half a website online

SFTP runs over SSH: one port, key authentication, encrypted. atmoz/sftp gives you a chrooted user in one line, and with the same releases/ + current layout the switch is atomic here as well: upload into a new folder, create a symlink, and rename it over current. OpenSSH's sftp uses the posix-rename extension for that, which replaces the old link in one step. The web container is the one from Step 4, unchanged:

YAMLsftp/docker-compose.ymlcomplete · 26 lines
# Bonus - no Git? Upload releases with SFTP (key only) - never plain FTP
name: site-sftp

services:
  web:
    build: ../web                            # same Apache image: DocumentRoot /srv/site/current
    restart: unless-stopped
    ports:
      - "8080:80"                            # HTTPS: put Caddy in front, as in Variant B
    volumes:
      - site:/srv/site:ro

  sftp:
    image: atmoz/sftp:alpine
    restart: unless-stopped
    command: ["deploy::1000:1000"]           # user:password:uid:gid - empty password = key only
    ports:
      - "2222:22"                            # firewall: allow only your own IPs
    volumes:
      - site:/home/deploy/site
      - ./keys/deploy.pub:/home/deploy/.ssh/keys/deploy.pub:ro
      - ./host_keys/ssh_host_ed25519_key:/etc/ssh/ssh_host_ed25519_key:ro
      - ./host_keys/ssh_host_rsa_key:/etc/ssh/ssh_host_rsa_key:ro

volumes:
  site:
Shellsftp/sftp-release.shcomplete · 16 lines
#!/bin/sh
# Upload ./public as a new release over SFTP and switch "current" atomically.
#   usage: sftp-release.sh deploy@www.example.com [port] [local_dir]
set -eu
target=$1 port=${2:-2222} dir=${3:-public}
rel=$(date -u +%Y%m%d-%H%M%S)

sftp -b - -P "$port" -i ~/.ssh/sftp_deploy "$target" <<SFTP
-mkdir site/releases
mkdir site/releases/$rel
put -r $dir/. site/releases/$rel
-rm site/current.new
symlink releases/$rel site/current.new
rename site/current.new site/current
SFTP
echo "live: releases/$rel"
Terminal: sftp-release.sh uploads public/ into site/releases/20261007-195212, creates the symlink current.new and renames it to current; the page shows SFTP upload 1; a second run switches to SFTP upload 2; the releases folder lists both releases.
Real runFigure 7 — Two uploads with sftp-release.sh: each goes into its own folder, rename swaps current in one step.

Persist the SSH host keys as shown — atmoz/sftp otherwise generates new ones for every new container, and every client will (rightly) refuse to connect after the next docker compose pull. The chmod … Read-only file system warning at startup comes from the read-only mount and is harmless. Old releases are not pruned here; delete them with sftp rm or a cron job.


How It Works Inside

1. The webhook is a doorbell, not a delivery

The payload says which commit was pushed — and sync.sh ignores that. The listener writes a request file; sync.sh notices the change and fetches the branch from the repository with its own credentials. That one decision removes a whole class of problems: a replayed delivery (GitHub signatures have no timestamp) just re-deploys what is already live; five pushes during one deploy collapse into one more fetch; a lost delivery is caught by the 5-minute fallback. I tested that: with the hook container stopped, a push went live 113 seconds later, exactly when the fallback timer ran out.

Outputhook stopped, then git pushreal run
Container blog2-hook Stopping 
 Container blog2-hook Stopped 
19:49:25 pushed 9db746e Version 3: pushed while the hook was down with hook container stopped
19:51:17 Version 3 live after 113 s (fallback sync)
2026-10-07T19:46:13Z sync doorbell: {"after": "fbbb05ce568760fd287e51e65a7ee9ee07063628", "delivery": "719a852b-ddd6-46e9-92c4-d55952c77396", "at": 1791402372}
2026-10-07T19:46:13Z sync already live: 4414865
2026-10-07T19:51:13Z sync live: 9db746e "Version 3: pushed while the hook was down" in 0s
 Container blog2-hook Starting 
 Container blog2-hook Started

2. git archive instead of a working copy

The usual approach — a clone in the document root plus git reset --hard — has two flaws: the .git folder is inside the web root, and files are replaced one by one while visitors request them. sync.sh keeps a bare clone in /srv/site/repo.git (Apache only sees /srv/site/current) and exports each commit with git archive into a fresh folder. The export contains exactly what is committed — no .git, no stale files from older versions, nothing marked export-ignore. A release without index.php (an empty branch, the wrong repository) is refused before the switch.

3. One rename() = one atomic switch

ln -sfn alone is not atomic — it deletes the old link and creates a new one, and a request can fall into the gap. sync.sh creates .current.new and moves it over current with mv -T, which is a single rename(2) system call: every request sees either the old or the new release, never a mix. I hammered the site with four parallel clients while switching releases 20 times:

Output4 clients · 25 s · 20 switchesreal run
$ ./stress-switch.sh    # 4 clients for 25 s, 20 release switches
   1466 ok Version 1
    595 ok Version 2

4. The 60-second mystery: PHP's realpath cache

My first real push took 60 seconds to show up, although git-sync had logged live after one. The symlink was correct; Apache was serving the old page anyway:

Terminal: git-sync logs live 6ae029f Version 2 at 19:44:05, but six curl requests every three seconds still return Version 1 until 19:44:28.
Real runFigure 8 — Before the fix: git-sync switched to Version 2 at 19:44:05 — and every request still got Version 1 for more than 25 seconds.

The cause is PHP, not Apache. Each Apache worker keeps a realpath cache that remembers what /srv/site/current/index.php resolved to — releases/<old commit>/index.php — for realpath_cache_ttl seconds, 120 by default. Every worker has its own copy, so during those two minutes visitors get old and new versions at random. Deployment tools solve this with an Apache reload or nginx's $realpath_root; a reload would need docker.sock again. The fix in web/php.ini is one line: realpath_cache_ttl = 1. Careful — 0 does not disable the cache, it makes entries live forever. After the fix:

Outputafter realpath_cache_ttl = 1real run
$ docker compose exec web php -r "echo ini_get(\"realpath_cache_ttl\"), PHP_EOL;"
1
$ docker compose exec git-sync sync.sh rollback
2026-10-07T19:48:29Z sync rolled back to 3cbd351 and pinned - run 'sync.sh unpin' to deploy main again
$ for i in 1 2 3; do printf "%s  " "$(date +%T)"; for n in 1 2 3 4 5 6; do curl -s https://www.example.com/ | grep -o "Version [0-9]" | head -1 | tr "\n" " "; done; echo; sleep 1; done
19:48:29  Version 1 Version 1 Version 1 Version 1 Version 1 Version 1 
19:48:31  Version 1 Version 1 Version 1 Version 1 Version 1 Version 1 
19:48:32  Version 1 Version 1 Version 1 Version 1 Version 1 Version 1 
$ docker compose exec git-sync sync.sh unpin
2026-10-07T19:48:33Z sync live: 4414865 "Version 2: new intro text" in 0s
$ for i in 1 2 3; do printf "%s  " "$(date +%T)"; for n in 1 2 3 4 5 6; do curl -s https://www.example.com/ | grep -o "Version [0-9]" | head -1 | tr "\n" " "; done; echo; sleep 1; done
19:48:33  Version 1 Version 1 Version 1 Version 1 Version 1 Version 1 
19:48:35  Version 2 Version 2 Version 2 Version 2 Version 2 Version 2 
19:48:36  Version 2 Version 2 Version 2 Version 2 Version 2 Version 2 

5. Small things that make it robust

  • set -e really stops a broken deploy — inside a function called with ||, POSIX shells silently disable set -e. The watch loop therefore runs every deploy as a child process ("$SELF" once), where it applies again
  • mktemp -d creates mode 700 — Apache (www-data) would get 403 on every release; sync.sh sets 755 before the switch
  • +refs/heads/main:refs/heads/main — the leading + means a force-push on GitHub is followed, not rejected
  • Pinned rollback — rollback switches to the previous release and writes a pinned file, otherwise the fallback sync would undo it within 5 minutes. unpin deploys main again
Outputsync.sh status / rollback / unpinreal run
$ docker compose exec git-sync sync.sh status
live:     releases/4414865e53e888b64dbca7a8c83580178aec9906
* 4414865  2026-10-07 19:45:18 +0000  Version 2: new intro text
  3cbd351  2026-10-07 19:44:58 +0000  Version 1: first page
$ docker compose exec git-sync sync.sh rollback
2026-10-07T19:48:16Z sync rolled back to 3cbd351 and pinned - run 'sync.sh unpin' to deploy main again
$ sleep 2; curl -s https://www.example.com/ | grep -o "Version [0-9]" | head -1
Version 1
$ docker compose exec git-sync sync.sh unpin
2026-10-07T19:48:19Z sync live: 4414865 "Version 2: new intro text" in 1s
$ sleep 2; curl -s https://www.example.com/ | grep -o "Version [0-9]" | head -1
Version 2

Security & Edge Cases

RiskWhat this setup does
Anyone triggers deploysHMAC-SHA256 with a 32-byte secret, constant-time compare, 401 without a valid signature; optional repository check (REPO_FULL_NAME) in case a secret is reused
Forged payload deploys foreign codeImpossible by design: only main of the configured REPO_URL is ever fetched
docker.sock in a containerNot used anywhere. Whoever controls the socket can start a privileged container that mounts / — that is root on the host. The request file replaces it
Token leaksRead-only deploy key or token from a file via GIT_ASKPASS; never in URLs, .git/config or logs. Secrets are Compose secrets, not environment variables (those show up in docker inspect)
Source and history exposedNo .git in releases + Apache denies dotfiles + bare repo outside the document root
Port 9001 open to the worldThe listener is never published; only Caddy's 80/443. Note: ports published by Docker bypass ufw/firewalld rules — bind test ports to 127.0.0.1 or filter in the DOCKER-USER chain
Container escape / lateral movementNon-root users, read-only root filesystems, cap_drop: [ALL], no-new-privileges, git-sync on its own network
Oversized or slow requests5 MB limit in Caddy and in the listener, 10-second socket timeout

Edge cases you should know before you rely on it:

  • User uploads — releases are immutable and replaced on every deploy. Files that visitors upload must live in a separate volume, mounted into the web container (e.g. /srv/uploads) and linked from your code — never inside a release
  • Build steps — this deploys what is committed. If you need composer install or a JS build, run it in a CI job that pushes to a deploy branch, or commit vendor/; I did not add a build step to keep git-sync small
  • Submodules and Git LFS — git archive includes neither. Use plain files, or replace the export with a checkout into the release folder
  • Database migrations — out of scope; deploying code and changing a schema in one step needs its own plan
  • Secrets in the repository — .env is blocked by Apache, but the right place for secrets is a Compose secret or the server, not Git

Troubleshooting: Real Errors and Their Fixes

Every message in this section was reproduced in the lab. Three of the Git errors in one screenshot:

Terminal: sync.sh once fails with git@git.example.com: Permission denied (publickey); with an empty known_hosts it fails with Host key verification failed; git pull as www-data on a root-owned clone fails with fatal: detected dubious ownership in repository at /var/www/html.
Real runFigure 9 — Three real Git errors: deploy key removed (publickey), empty known_hosts, and Git as www-data on a clone made by root (dubious ownership).

git@github.com: Permission denied (publickey)

The server does not accept the key. In the lab I removed the deploy key from the repository to get this. Check that deploy_key.pub is added to this repository (a deploy key can be used by only one repository), that REPO_URL uses the SSH form git@github.com:owner/repo.git, and that the key file is readable by UID 1000. If the file is readable by others, SSH refuses it with UNPROTECTED PRIVATE KEY FILE — keep it at 400.

Host key verification failed

known_hosts is missing, empty or not mounted at /etc/deploy/known_hosts. Re-run the ssh-keyscan line from Step 2 and compare the fingerprint. Do not "fix" it with StrictHostKeyChecking=no — that is exactly the check that protects your deploy key from a man in the middle.

fatal: detected dubious ownership in repository

Since Git 2.35.2, Git refuses to work in a repository owned by another user. My first attempt hit it the moment Git ran as www-data on a clone made by root, and the usual advice is git config --global --add safe.directory …. With this setup it cannot happen: only git-sync (UID 1000) ever touches repo.git, and the web server has no Git at all. If you see it in your own setup, fix the ownership instead of adding exceptions.

401 bad signature (Recent Deliveries shows a red ✗)

The secret in GitHub and in secrets/webhook_secret differ. The listener strips a trailing newline (as written by echo), so that is not the cause. Copy the secret again, save the webhook, click Redeliver. If it still fails, something between GitHub and the listener changes the body — a proxy or WAF that re-encodes JSON. The signature is over the exact bytes, so the body must arrive unchanged.

Page stays on the old version for up to two minutes

PHP's realpath cache — see How it works inside, point 4. Check with docker compose exec web php -r 'echo ini_get("realpath_cache_ttl");'; it must print 1.

hook restarts in a loop / Bind … port is already allocated

Outputsecret permissions · port in usereal run
$ ls -ln secrets/webhook_secret
-rw------- 1 0 0 65 Oct  7 19:39 secrets/webhook_secret
$ docker compose up -d --force-recreate hook >/dev/null 2>&1; sleep 4; docker compose logs --no-log-prefix --tail 2 hook; docker compose ps hook --format "{{.Name}}  {{.Status}}"
hook: cannot read webhook secret: [Errno 13] Permission denied: '/run/secrets/webhook_secret'
hook: cannot read webhook secret: [Errno 13] Permission denied: '/run/secrets/webhook_secret'
blog2-hook  Up Less than a second (health: starting)
$ chown 1001:1001 secrets/webhook_secret && chmod 400 secrets/webhook_secret && docker compose up -d --force-recreate hook >/dev/null 2>&1; sleep 3; docker compose logs --no-log-prefix --tail 1 hook
2026-10-07T19:47:37Z hook listening on :9000/_hooks/github - branch main, repository apexnote/demo-site
$ docker run --rm -p 127.0.0.1:443:443 caddy:2-alpine
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint unruffled_cohen (69b6bd2c6ff7f9ae836e3bd95191090ff1073f07162f6e587ff52b91928dc294): Bind for 127.0.0.1:443 failed: port is already allocated

Run 'docker run --help' for more information

Permission denied on the secret: Compose (without Swarm) bind-mounts secret files with their host owner and mode — chown 1001:1001 for the hook secret, chown 1000:1000 for the deploy key, then chmod 400. For Variant A the webhook secret belongs to www-data (UID 33). Port already allocated: another container or service holds 80/443 — find it with docker ps --format '{{.Names}} {{.Ports}}' or ss -ltnp and stop it, or put this stack behind the existing proxy.

AH00112: Warning: DocumentRoot [/srv/site/current] does not exist

Printed once on the very first start, before git-sync has created the first release — harmless. If it persists, run docker compose logs git-sync: the first clone failed, usually for one of the SSH reasons above.

📋 Copy the code
hook.py + sync.sh + docker-compose.yml

Complete code in this post — copy it from Steps 4–7 (Variant B), the Variant A section and the SFTP bonus; every code box has a Copy button. MIT licensed and free for personal and commercial projects. Originally developed by S&H Software Solutions – first published on APEX Note (October 2026).

Questions? Leave a comment below.


Final Thoughts

My first version of this was thirty lines of YAML and it deployed in two seconds. The version in this post deploys in 1.4 — and the difference is everything you do not see: a signature check, a key that can only read, a document root without .git, and a switch that no visitor can catch halfway. None of it needs a CI platform. Most of it is one decision: the internet-facing part may ring the bell, but only the part without a public port may open the door.

The most valuable bug was the one I did not expect: sixty seconds of "why is it still the old page?", caused by a PHP cache that every symlink-based deployment runs into sooner or later. That is why I test these posts for real before I publish them.

If you run this behind Traefik, on Podman, or with a build step, and something does not fit — leave a comment below. I read all of them.

SH
Sajjad Hanifa
Software Developer · S&H Software Solutions · Oracle APEX, PL/SQL, Docker
Docker GitHub Webhook PHP Apache Continuous Deployment HMAC Caddy SFTP Security

 {fullWidth}

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

نموذج الاتصال