GitHub Actions for an existing Laravel app · Part 3 of 3
Deploying on every merge, and the team's practice
A key that can only deploy, the server scripts for Docker and for a classic server, the first deploy, a rollback by commit, then branch rules, required checks, secrets, migrations, and the failures with what each one means.
By Abhishek Fouzdar · Updated
Parts 1 and 2 left a workflow that checks main and builds a release, then fails at the last job because there is no server to talk to. This part gives it one. By the end, a merge to main is live on the server two minutes later without anyone touching it, a rollback is a form with one field, and the team has rules that make the whole thing hold.
Both paths are here: Docker first, then the classic server. The key, the secrets and the rollback are the same for both.
The one idea to hold on to
The runner gets to run exactly one command on the server, and that command deploys. Not a shell, not rsync to wherever it likes, not sudo. An SSH key that can only deploy is a key you can afford to have stolen, and it is the difference between "CI has access to production" being a sentence that worries people and one that does not.
SSH has had this feature for decades. In authorized_keys, a key can carry command="...", and then whatever the client asks to run, the server runs that script instead, with the client's request available to the script as $SSH_ORIGINAL_COMMAND. The script decides what to do with it.
The deploy key
On your own machine, make a key for this purpose alone, with no passphrase, because a machine will use it:
ssh-keygen -t ed25519 -f deploy_key -N "" -C "github-actions app"
On the server, add the public key to ~/.ssh/authorized_keys of the user the app runs as, on one line, with the restrictions in front of it:
command="/home/deploy/apps/app/deploy.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAAA...rest of deploy_key.pub... github-actions app
command= names the script. The other four refuse everything else SSH could be asked to do with this key. The script comes next.
The Docker path
The server
The server needs Docker Engine, a folder for the stack, and a user in the docker group. In that folder, ~/apps/app/ here, three files:
compose.prod.yamlfrom part 2, copied as is;.env, the production environment, written by hand once:APP_KEYfromphp artisan key:generate --show, the database name, user and password that thedbcontainer will create on its first start,APP_IMAGEandWEB_IMAGEwith any tag for now,APP_HOST_PORTfor the port the server's own web server will proxy to, and the usual drivers (redisfor session, cache and queue;MAIL_*for your mail provider);deploy.sh, the forced command.
deploy/deploy.sh in the repository, copied to ~/apps/app/deploy.sh on the server and made executable:
#!/usr/bin/env bash
# The only thing the deploy key is allowed to run: the command= in authorized_keys points
# here, and the arguments arrive in SSH_ORIGINAL_COMMAND, so a stolen key can still only
# deploy. Lives at ~/apps/<app>/deploy.sh next to compose.prod.yaml and the production .env.
#
# deploy <token> <sha> Docker: pull the images tagged <sha>, restart the stack, migrate
# release <sha> classic: a new release arrives as a tarball on stdin
# switch <sha> classic: point `current` at a release already on the server
# status what is running
set -euo pipefail
cd "$(dirname "$0")"
read -r action arg1 arg2 <<<"${SSH_ORIGINAL_COMMAND:-}"
case "$action" in
deploy)
token="${arg1:-}"; sha="${arg2:-}"
[ -n "$token" ] && [ -n "$sha" ] || { echo 'deploy: usage: deploy <token> <sha>' >&2; exit 1; }
[[ "$sha" =~ ^[0-9a-f]{7,40}$ ]] || { echo "deploy: '$sha' is not a commit sha" >&2; exit 1; }
# Pin the images to this commit. `latest` is a moving target: Compose cannot see that
# it moved, so it would leave the old containers running, and a rollback would have
# nothing to point at. The tag in .env is what `docker compose ps` shows afterwards.
sed -i -E "s#^(APP_IMAGE=.*):[^:]+\$#\1:$sha#; s#^(WEB_IMAGE=.*):[^:]+\$#\1:$sha#" .env
echo "$token" | docker login ghcr.io -u github-actions --password-stdin >/dev/null
docker compose -f compose.prod.yaml pull --quiet
docker compose -f compose.prod.yaml up -d --remove-orphans --wait
docker compose -f compose.prod.yaml exec -T app php artisan migrate --force --no-interaction
docker logout ghcr.io >/dev/null
# Images no container uses any more: the previous release's. A rollback pulls again.
docker image prune -af >/dev/null
echo "deploy: $sha is live"
;;
release) exec "$HOME/apps/app-classic/release.sh" "${arg1:-}" ;;
switch) exec "$HOME/apps/app-classic/release.sh" switch "${arg1:-}" ;;
status) docker compose -f compose.prod.yaml ps ;;
*) echo "deploy: unknown action '$action'" >&2; exit 1 ;;
esac
It reads the request as words. deploy <token> <sha> is what the workflow sends: the run's GITHUB_TOKEN, so the server can pull the private images for the length of the run, and the sha the build tagged them with. The script pins both image lines in .env to that tag, logs in, pulls, brings the stack up, migrates, logs out, and removes the images no container uses any more.
The pinning is the point of the sha tags from part 2, and the reason the deploy never uses latest. The first version of this script pulled latest, and on the second deploy Compose looked at the running containers, decided nothing had changed, and left them running the old image while latest on disk was the new one. Compose compares the configuration it is given; a tag that silently moves is the same configuration. A tag that changes with every commit is not, so every deploy recreates the app containers, and a rollback has a tag to point at.
--wait makes up block until the containers report healthy, so a migration never runs against a database that is still starting. migrate --force is the production form; without --force artisan asks for confirmation and the deploy hangs.
Test the key from your machine before involving GitHub:
$ ssh -i deploy_key deploy@your-server status
NAME IMAGE SERVICE STATUS PORTS
app-app-1 ghcr.io/you/app/app:4b50da00c5f2 app Up 40 seconds (healthy) 9000/tcp
app-db-1 mysql:8.4 db Up 13 hours (healthy) 3306/tcp, 33060/tcp
app-queue-1 ghcr.io/you/app/app:4b50da00c5f2 queue Up 41 seconds 9000/tcp
app-redis-1 redis:7-alpine redis Up 13 hours (healthy) 6379/tcp
app-scheduler-1 ghcr.io/you/app/app:4b50da00c5f2 scheduler Up 40 seconds 9000/tcp
app-web-1 ghcr.io/you/app/web:4b50da00c5f2 web Up 40 seconds 127.0.0.1:8080->80/tcp
$ ssh -i deploy_key deploy@your-server bash
deploy: unknown action 'bash'
The second command is the one to remember: the key cannot open a shell.
What GitHub needs to know
Four variables and one secret, in the repository's settings under Secrets and variables, Actions, or with the gh CLI:
gh variable set DEPLOY_HOST --body "203.0.113.10"
gh variable set DEPLOY_PORT --body "22"
gh variable set DEPLOY_USER --body "deploy"
gh variable set DEPLOY_KNOWN_HOSTS --body "$(ssh-keyscan -t ed25519 203.0.113.10 2>/dev/null)"
gh secret set DEPLOY_SSH_KEY < deploy_key
Variables are visible in the UI and in logs; secrets are masked wherever they appear and cannot be read back. The private key is the only secret.
DEPLOY_KNOWN_HOSTS is the server's host key, so the runner refuses to talk to anything that is not your server. Mind the 2>/dev/null: ssh-keyscan prints a comment line with the server's version on standard error, and if that lands in the variable, SSH on the runner fails with Host key verification failed, which is what happened on the first deploy here. The variable should hold one line that starts with the address.
The deploy job also names an environment: production. GitHub creates it on first use. It is a label on the run, a place to put secrets that only this job can read, and the hook for protection rules later.
The first deploy
Merge something, or run the Deploy workflow by hand from the Actions tab with the sha field empty. The run shows the three checks, then the build, then the deploy. The deploy job's log ends with:
deploy: 4b50da00c5f2 is live
On the server, docker compose -f compose.prod.yaml ps shows the app, queue, scheduler and web containers on that tag, and curl -s http://127.0.0.1:8080/ returns the page. Point the server's nginx or Caddy at that port with TLS and the app is public.
Total time for the example app, from push to live: about two minutes. Checks 57 seconds, build 52 seconds, deploy 9 seconds.
The classic path
The server
A server that runs PHP natively needs PHP 8.4 with the extensions the app uses (pdo_mysql, mbstring, xml, curl, intl, bcmath, zip, gd, and redis if sessions or the queue use it), MySQL with a database and a user for the app, nginx with php-fpm, and the deploy user. The first attempt here failed on the first of those: the server's PHP had no SQLite driver, because nobody installs it, and the shared/.env on the server still pointed at SQLite, copied from a laptop. Production is MySQL; the environment file on the server should say so before the first release.
The layout, under ~/apps/app-classic/:
release.sh the script below
shared/.env the production environment, written once by hand
shared/storage/ created by the first release; uploads, logs, caches live here
releases/<sha>/ one folder per deploy, the last five kept
current -> releases/<sha> the symlink everything else points at
The forced command is the same deploy.sh as the Docker path. Its release and switch actions hand over to this script, deploy/release.sh in the repository, copied to ~/apps/app-classic/release.sh. On a classic server deploy.sh itself still lives at ~/apps/app/deploy.sh, as the command= line says; only its release and switch actions apply there, since status needs Docker:
#!/usr/bin/env bash
# The classic (no Docker) deploy on the server. Called by deploy.sh with the forced-command
# key; never run by hand except to debug. Lives at ~/apps/<app>-classic/release.sh.
#
# release.sh <sha> a new release arrives as a tarball on stdin
# release.sh switch <sha> point `current` at a release that is already here (rollback)
#
# releases/<sha>/ one directory per deploy, the last five kept
# shared/.env the production environment, never in a release
# shared/storage/ uploads, logs, caches: survives releases
# current -> releases/<sha> the symlink the web server and the workers follow
set -euo pipefail
BASE="$(cd "$(dirname "$0")" && pwd)"
switch_to() {
local rel="$BASE/releases/$1"
[ -d "$rel" ] || { echo "release: no release $1 here; have: $(ls -1 "$BASE/releases" | tr '\n' ' ')" >&2; exit 1; }
# Caches are rebuilt first: the .env may have changed since this release was built.
(cd "$rel" && php artisan optimize --no-interaction >/dev/null)
# The switch. A symlink rename is atomic: no request ever sees a half-deployed tree.
ln -sfn "$rel" "$BASE/current.new"
mv -T "$BASE/current.new" "$BASE/current"
# Workers finish their current job and exit; the process manager starts fresh ones on
# the new code. php-fpm keeps old files in OPcache until reloaded.
(cd "$rel" && php artisan queue:restart --no-interaction >/dev/null)
if sudo -n systemctl reload php8.4-fpm 2>/dev/null; then
echo "release: php-fpm reloaded"
else
echo "release: php-fpm not reloaded (no sudo rule); OPcache serves the old files until it is"
fi
echo "release: $1 is live"
}
if [ "${1:-}" = switch ]; then
switch_to "${2:?release: switch needs a sha}"
exit 0
fi
sha="${1:?release: missing sha}"
rel="$BASE/releases/$sha"
mkdir -p "$rel"
tar -xzf - -C "$rel"
# Shared state. The first release seeds shared/storage with the app's own skeleton.
if [ ! -d "$BASE/shared/storage" ]; then mv "$rel/storage" "$BASE/shared/storage"; fi
rm -rf "$rel/storage"
ln -s "$BASE/shared/storage" "$rel/storage"
ln -sfn "$BASE/shared/.env" "$rel/.env"
# Migrate before the switch: if this fails, `current` still points at the old release.
(cd "$rel" && php artisan migrate --force --no-interaction)
switch_to "$sha"
# Keep the last five releases for a quick rollback (`switch <sha>`).
ls -1dt "$BASE/releases"/*/ | tail -n +6 | xargs -r rm -rf
A release arrives as a tarball on standard input, is unpacked into its own folder, gets the shared storage/ and .env linked in, is migrated, has its caches built, and becomes current in one rename. mv -T onto a symlink is atomic: at no moment does current point nowhere or at a half-written tree. Then the workers are told to finish their current job and exit, and php-fpm is reloaded.
That reload needs root, and the deploy user does not have it. Give it exactly that one command, nothing else, in /etc/sudoers.d/app:
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload php8.4-fpm
Without it the script says so and carries on, and php-fpm keeps serving the old files from OPcache until someone reloads it, which with opcache.validate_timestamps=0 could be forever. With it, the switch is complete when the script ends.
nginx, the workers, the scheduler
The nginx server block for the app, with the one line that makes symlink releases work:
server {
listen 80;
server_name app.example.com;
# `current` is a symlink; $realpath_root resolves it per request, so a release switch
# takes effect immediately and no request mixes files from two releases.
root /home/deploy/apps/app-classic/current/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
include fastcgi_params;
}
location ~ /\.(?!well-known) {
deny all;
}
}
$realpath_root makes nginx resolve the current symlink on every request and hand php-fpm the real path. Without it, php-fpm gets current/... and OPcache keys the compiled files by that path, so a reload after a switch can keep serving the previous release.
The queue worker runs under systemd, which restarts it when queue:restart makes it exit. /etc/systemd/system/[email protected]:
[Unit]
Description=Queue worker %i for app
After=network.target mysql.service redis-server.service
[Service]
User=deploy
WorkingDirectory=/home/deploy/apps/app-classic/current
ExecStart=/usr/bin/php artisan queue:work --tries=3 --max-time=3600 --sleep=3
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
systemctl enable --now app-queue@1 app-queue@2 runs two workers. WorkingDirectory is current, so a restarted worker is on the new release. The scheduler is one cron line for the deploy user:
* * * * * cd /home/deploy/apps/app-classic/current && php artisan schedule:run >> /dev/null 2>&1
The first release
Run the Deploy (classic) workflow, or merge. The release job builds, packs and streams; the server's script prints its progress into the job's log:
INFO Running migrations.
0001_01_01_000000_create_users_table .......................... 91.34ms DONE
...
release: php-fpm reloaded
release: 4b50da00c5f2 is live
Total time for the example app: about 90 seconds, of which the release job is 26.
Rolling back
Both deploy workflows take an optional sha when run by hand: Actions, the workflow, Run workflow, one field. With a sha, the checks and the build are skipped, and the server is told to switch.
For Docker that is deploy <token> <sha> again, with the sha of an earlier deploy. The registry still has the images under that tag, so it is a pull and a restart, the same path as a deploy, which is why it can be trusted: it is not a special case that only runs when something is already wrong.
For the classic server it is switch <sha>, which points current at one of the five releases still on disk, rebuilds its caches, restarts the workers and reloads php-fpm. No build, no transfer.
Both were tried on the example app by rolling back one commit and forward again. The Docker rollback took 36 seconds from clicking the button to deploy: 8b8d62a88ace is live, most of it the pull; the classic one took 10 seconds. The checks and build jobs show as skipped on the run, which is the visible proof that nothing was rebuilt.
What a rollback does not do is reverse migrations. If the release you are leaving added a column, the column stays, and the release you are going back to does not know about it, which is harmless. If it dropped or renamed one, going back breaks, and no tool fixes that. The rule that makes rollbacks safe is in the next section.
The concurrency group in each workflow means a rollback queues behind a deploy that is still running rather than racing it.
The team's practice
The pipeline works without anything in this section. These are the rules that keep it working when there are five people and a Friday.
main is protected
GitHub's rulesets, under the repository's Settings, Rules, Rulesets, put rules on a branch. For main, four:
- Restrict deletions and Block force pushes, both on by default when you create a ruleset.
- Require a pull request before merging. Zero required approvals is a legitimate setting for a two-person team; the rule still forces every change through a pull request, which is where the checks run.
- Require status checks to pass before merging, with the three job names from part 1 added as required checks:
Style and analysis,Tests,Frontend build. The name GitHub matches is the job'sname:, so renaming a job silently un-requires it. Tick "Require branches to be up to date before merging": a branch that is behindmainmust mergemainin and pass again, so the checks ran on what is actually about to land.
Together these mean nothing reaches main, and so nothing reaches the server, without the checks having passed on exactly that code. The same ruleset through the API, for a repository that is created with a script:
gh api -X POST repos/OWNER/REPO/rulesets --input - <<'EOF'
{
"name": "main",
"target": "branch",
"enforcement": "active",
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{ "type": "pull_request", "parameters": {
"required_approving_review_count": 0,
"dismiss_stale_reviews_on_push": true,
"require_code_owner_review": false,
"require_last_push_approval": false,
"required_review_thread_resolution": false } },
{ "type": "required_status_checks", "parameters": {
"strict_required_status_checks_policy": true,
"required_status_checks": [
{ "context": "Style and analysis" },
{ "context": "Tests" },
{ "context": "Frontend build" } ] } }
]
}
EOF
One limit to know about: on GitHub's free plan, rulesets and branch protection are available for public repositories only. The API says so plainly for a private one: "Upgrade to GitHub Pro or make this repository public to enable this feature." Organisations on the Team plan have them on every repository.
Who may deploy
With rulesets, the answer is "whoever can merge to main", which is the right answer: a deploy is a merge. For a team that wants a second pair of eyes between the merge and the server, the production environment can require reviewers: Settings, Environments, production, Required reviewers. The deploy job then pauses until one of them approves, and the checks and the build have already run, so the approver is looking at a release that is ready. On the Free, Pro and Team plans this is for public repositories only; private repositories need Enterprise.
Secrets
Three rules.
The private key is the only secret the pipeline has, and it is a secret only GitHub holds; the matching public key on the server can only run one script. If the key leaks, delete the line from authorized_keys and make a new pair. Nothing else needs to change.
GITHUB_TOKEN is created per run, scoped by the permissions block, and gone when the run ends. Keep the block minimal: contents: read plus packages: write is everything the deploy needs.
Never echo a secret, even to debug. GitHub masks known secret values in logs, but it cannot mask a value that has been transformed, split or base64-encoded, and logs are visible to everyone with read access to the repository.
Migrations
A deploy runs migrate before the switch, so a migration that fails leaves the old release in place. The rule that keeps rollbacks safe is expand, then contract: a release may add tables and columns, but it may not remove or rename anything that the previous release reads. The removal goes in a later release, once the previous one is no longer something you would roll back to. Written down, it is two sentences; followed, it is the difference between a rollback that takes seconds and one that takes a restore from backup.
Every merge deploys
The pipeline deploys every merge to main, and the team's habit should match it: small pull requests, merged when green, one at a time. A merge that sits on main for two days before someone "does a deploy" is a merge that will go out alongside three others, and when something breaks nobody knows which one. If a change is not ready to be live, it is not ready to be merged; a feature flag, or a branch, holds it until it is.
Failures, and what each one means
Host key verification failed on the deploy step. DEPLOY_KNOWN_HOSTS is wrong, usually because ssh-keyscan's comment line got in. The variable should be one line starting with the server address.
Permission denied (publickey). The public key is not in the deploy user's authorized_keys, the line got wrapped, or the secret holds the public key instead of the private one.
deploy: unknown action 'bash' or similar, when you try the key by hand. That is the forced command doing its job; use status.
deploy: usage: deploy <token> <sha> or a pull that says denied. The workflow called the script without the token, or permissions lacks packages: write. The images in a private repository need the token to pull.
The deploy says it is live, the server runs the old code. The image tag did not change. Check .env on the server has the sha tag in APP_IMAGE, not latest.
could not find driver in the classic release's migration. The server's PHP lacks the extension for the database in shared/.env. php -m on the server lists what is there.
php-fpm not reloaded (no sudo rule) in the release log, and the site shows the previous release after a switch. Add the sudoers line.
Checks run twice on every push. The CI workflow lists both push and pull_request. Keep pull_request.
A required check is "Expected" forever and the pull request cannot merge. The job was renamed, or the branch has no pull request run because the workflow file itself changed on the branch and the base does not have it yet. Check the names in the ruleset against the jobs' name:.
Test directory "tests/Unit" not found. The last unit test was deleted and Git does not keep empty directories. Put a test back.
The job hangs on migrate. Missing --force. Artisan is waiting for a yes nobody can type.
Unknown database 'testing' in CI. The MYSQL_DATABASE of the service container and DB_DATABASE in the step's environment disagree.
Connection refused on the first test, and the run passes when re-run. No health check on the service container; the tests started before MySQL did.
Checkpoint
You should have:
- a deploy key whose only ability is to run
deploy.sh, andssh -i deploy_key deploy@server statusworking from your machine; - the four variables and one secret in the repository;
- for Docker:
~/apps/app/withcompose.prod.yaml,.envanddeploy.sh, and a run of the Deploy workflow that ends indeploy: <sha> is live; - for a classic server:
~/apps/app-classic/withrelease.sh,shared/.env, the nginx block, the worker units, the cron line, the sudoers line, and a run that ends inrelease: <sha> is live; - a ruleset on
mainrequiring the three checks, if your plan allows it.
What you have
An app that existed before any of this, unchanged in its code, that a machine now checks on every pull request and puts on the server on every merge, in about two minutes, by a path that cannot do anything else. Going back is choosing an earlier commit. The team's part is three habits: work goes through pull requests, migrations expand before they contract, and merges are small and go out as they land.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
3 / 3- OverviewGitHub Actions for an existing Laravel app
- Part 1Checks on every pull request
- Part 2Building the release
- Part 3Deploying on every merge, and the team's practice