Skip to content

Source: docs/research/deploy-tooling.md. Edit it there; this page is generated at build time.

Deployer or a hand-rolled deploy script ​

Research for issue 18, under the release map. Everything below was checked against Deployer's source at the v8.0.5 tag, php.net, nginx.org, and the Laravel framework source already vendored in this repo, rather than against write-ups about them.

There was no docs/research/ before this file. It is the obvious neighbour to docs/adr/ — ADRs record what we decided, this records the reading a decision rested on.

Recommendation ​

Use Deployer 8.x, driven from the self-hosted runner with localhost() and update_code_strategy = 'local_archive'. Do not hand-roll the release lifecycle.

The localhost question — the one the ticket flagged as the unusual bit — turns out to be the strongest argument for Deployer rather than against it. localhost() is not a degraded mode or a documented workaround; run() branches on it explicitly and dispatches to a local process runner, so no ssh process is spawned at all. And Deployer 8 added an update_code_strategy called local_archive that builds the release from the machine's own git checkout instead of re-cloning from a remote. Between them, the two settings describe precisely the situation this map has: the code is already on the box, in the runner's workspace, and the deploy target is the same machine. We would not be bending an SSH tool into a local shape. We would be using two first-class features that exist for this case.

The second argument is narrower and blunter. The release lifecycle is not the interesting part of this project, and it is the part where a subtle mistake is invisible until it is expensive. The atomic symlink swap is the clearest example: the naive ln -sfn that almost every hand-rolled script starts with is not atomic, and Deployer already gets this right, with feature detection, in a file we would otherwise be reinventing (see Where a hand-rolled script would go wrong).

The 2am-in-eighteen-months factor is the one place the hand-rolled option genuinely wins, and it deserves to be said plainly rather than argued away: a bash script is debuggable by reading it, and Deployer is not. The mitigation is that Deployer's failure surface is small and its recipes are readable PHP — but this is a real cost we are accepting, not one that isn't there. It is offset by dep deploy --plan and dep tree deploy, which print the resolved task list without running it, and by the fact that the thing most likely to be broken at 2am is the rollback, which is one symlink swap either way.

Deployer does not cover everything. It has no asset build in the Laravel recipe, no opcache handling in the default flow, and no auto-unlock on failure. What it leaves us is a genuinely short list, and it is written out at the end.

The comparison ​

Running on localhost is a supported path, not a workaround ​

Deployer's localhost() returns a Localhost, a trivial subclass of Host (src/Host/Localhost.php). The behaviour lives at the call sites. run() in src/functions.php branches on the type: a Localhost goes to ProcessRunner, which executes the command through bash -s as a Symfony Process; anything else goes to the SSH client, which literally assembles an argv starting ['ssh', …]. The same instanceof Localhost branch decides whether upload() and download() use local paths or user@host:path. The docs state it directly:

Run commands on the local machine with localhost() … run() then executes locally.

— docs/hosts.md at v8.0.5

This matters more than it sounds. The alternative naive setup — host('127.0.0.1') — would shell out to a real ssh binary connecting to the box from itself, which means an SSH daemon, a key, and a known_hosts entry for a connection that never leaves the machine. localhost() removes all of that. The map's "no inbound SSH from GitHub, no deploy key in GitHub secrets" constraint is satisfied without anything extra: there is no SSH anywhere in the path.

The deployphp/action GitHub Action is not what we would use — its whole job is setting up an SSH agent from a private-key secret, and its docs assume runs-on: ubuntu-latest. We would invoke dep directly as a shell step on the self-hosted runner. Deployer's own CI documentation has nothing to say about self-hosted runners or localhost targets, and a search of the issue tracker turned up no dedicated thread on "the runner is the target" either. That absence is worth naming honestly: this is a supported combination of supported features, but it is not a well-trodden documented recipe, and we will be assembling it ourselves.

local_archive is the piece that makes it fit ​

The default update_code_strategy is archive, which maintains a bare mirror under {{deploy_path}}/.dep/repo, runs git remote update, and pipes git archive into the release directory. Under a self-hosted runner that is pure waste — it re-fetches over the network code that actions/checkout already put on the disk — and it introduces a second, independent answer to "which commit is live", because the default target is the tip of the branch rather than the commit CI tested.

Deployer 8 documents a third strategy in recipe/deploy/update_code.php:

php
// Sets deploy:update_code strategy.
// Can be one of:
// - local_archive (copies the repository from local machine)
// - archive (default, fetches the code from the remote repository)
// - clone (if you need the origin repository `.git` dir in your {{release_path}}, clones from remote repository)
set('update_code_strategy', 'archive');

and implements it as:

php
if ($strategy === 'local_archive') {
    $gitRoot = runLocally("git rev-parse --show-toplevel");
    runLocally("git -C " . quote($gitRoot) . " archive $targetWithDir -o archive.tar");
    upload("$gitRoot/archive.tar", '{{release_path}}/archive.tar');
    run("tar -xf {{release_path}}/archive.tar -C {{release_path}}");
    run("rm {{release_path}}/archive.tar");
    unlink("$gitRoot/archive.tar");

    $rev = quote(runLocally("git rev-list $target -1"));
}

With a localhost() host this never touches the network: runLocally and run are the same machine, and upload() degrades to a local copy. No repository setting is required at all — the ConfigurationException("Missing 'repository' configuration.") is inside the else branch. The release is built from exactly the tree the runner checked out, and Deployer writes the resolved SHA into a REVISION file in the release directory, which is a free piece of the "visible deployment history" the map asks for.

This is a version-sensitive finding and sources disagree because of it. Deployer 7.x has no local_archive; on 7.x the documented answer to "the code is already here" was to disable deploy:update_code and splice in the contrib/rsync.php recipe, a pattern the maintainer endorsed in issue #2889 but never merged as a first-class strategy. Anything written about Deployer and CI before 8.x will describe that older, clumsier workaround. We should read 8.x docs and 8.x source only.

Version compatibility is clean: Deployer 8.0.5 (released 2026-05-18) requires php: ^8.3, and this repo's composer.json requires php: ^8.3. It can be a --dev Composer dependency, a global install, a phive install, or a standalone phar. As a dev dependency it would be pinned in composer.lock like everything else, which is the option that ages best.

Coverage of the release lifecycle ​

Deployer's Laravel recipe at recipe/laravel.php defines its default deploy as:

php
task('deploy', [
    'deploy:prepare',
    'deploy:vendors',
    'artisan:storage:link',
    'artisan:optimize',
    'artisan:migrate',
    'deploy:publish',
    'artisan:reload',
]);

artisan:optimize covers the config:cache/route:cache/view:cache trio (and event cache) in one command. artisan:migrate runs migrate --force. deploy:publish is the symlink flip plus unlock plus cleanup. And artisan:reload is worth spelling out, because it is new enough that most writing about Deployer predates it and at least one source I read described it wrongly. php artisan reload was added in Laravel 12.41; the recipe guards it with ['min' => '12.41']. Reading the command actually vendored in this repo — vendor/laravel/framework/src/Illuminate/Foundation/Console/ReloadCommand.php at Laravel 13.30.1 — its task list is:

php
return [
    'queue' => 'queue:restart',
    'schedule' => 'schedule:interrupt',
    ...ServiceProvider::$reloadCommands,
];

So the queue-worker restart the ticket lists as a required deploy step is already in the default Laravel recipe on Deployer 8 + Laravel 13. On Deployer 7 it was not — artisan:queue:restart existed as a task but sat outside the default list. This is the second place where a 7.x-era source will mislead us.

Note also that artisan:migrate runs before deploy:publish, i.e. migrations are applied against the database while the old release is still the one being served. That ordering is a deliberate design decision with real consequences, and it belongs to issue 17, not this ticket. Flagging it here only so the two tickets do not each assume the other settled it.

What the recipe does not cover: there is no npm, vite, mix, or pnpm reference anywhere in recipe/laravel.php. Given /public/build is gitignored, asset compilation is mandatory for us and entirely absent from the default flow. It is not, however, absent from Deployer — contrib/npm.php defines exactly two tasks:

php
task('npm:install', function () {
    run('cd {{release_path}} && {{bin/npm}} ci');
});
task('npm:build', function () {
    run('cd {{release_path}} && {{bin/npm}} run build');
});

npm ci and npm run build, which is verbatim what this repo needs. It has to be required and hooked in by hand, but it is not something we write.

The contrib directory is in fact broader than this ticket needs to care about, and is worth a glance from the tickets it does concern: alongside npm.php and cachetool.php there are crontab.php and telegram.php, which overlap with issue 24 (cron and queue provisioning) and issue 26 (Telegram notifications). Whether they are the right answer there is those tickets' call.

What happens when a deploy fails halfway ​

This is where Deployer's behaviour is good but not as good as its reputation suggests, and the gaps are worth knowing before we rely on it.

The good part is structural and is the whole reason for atomic releases: everything up to and including artisan:migrate happens inside releases/<n>, which nothing is serving. If any task exits non-zero, deploy:publish never runs, the current symlink never moves, and the previous release keeps serving traffic. This is the same guarantee Forge describes for its own zero-downtime mode — "If any step in the deployment process fails, your site will continue to use the previous release" (Forge deployments) — and that Envoyer states as "if a deployment hook exits with a non-zero status code, the entire deployment will be cancelled" (Envoyer deployment hooks).

Three sharper edges:

  1. The deploy lock is not released on failure. deploy:lock runs early inside deploy:prepare and writes .dep/deploy.lock; deploy:unlock runs inside deploy:publish, i.e. only on the success path. fail('deploy', 'deploy:failed') is registered in recipe/common.php, but deploy:failed is defined as an empty no-op. So a deploy that dies in the middle leaves the lock behind, and the next deploy aborts with Deploy locked by $user. This is arguably correct — it forces a human to look before redeploying over a mess — but it is a surprise the first time, and it is a one-line fix if we decide we want the other behaviour.
  2. The half-built release directory is left on disk. Nothing marks it bad; BAD_RELEASE markers are written by rollback, not by a crash. It lingers until deploy:cleanup prunes past keep_releases (default 10).
  3. dep rollback never touches the database. It reads current, picks the newest non-BAD_RELEASE candidate below it, swaps the symlink, and writes a BAD_RELEASE marker into the release it just abandoned. That is all. Which is honest and correct behaviour, and is exactly the limitation issue 17 exists to reason about.

A hand-rolled script would have the same first guarantee, for free, from the same layout — this is a property of atomic releases, not of Deployer. Where it would differ is that we would have to build the locking, the candidate selection, the bad-release marking and the pruning ourselves, and each of those is a small amount of code with a nasty failure mode.

Where a hand-rolled script would go wrong ​

The single best illustration is the symlink swap, because it is the one line everybody writes and most people write incorrectly.

ln -sfn new current is not atomic. It unlinks current and then creates it, and between those two syscalls the path resolves to nothing — a request landing in that window gets a 404 or a 502. The atomic form is to create the new link beside the old one and rename(2) it over the top. Linux's rename(2) guarantees exactly this:

If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing.

and, for our case specifically:

If newpath refers to a symbolic link, the link will be overwritten.

Deployer's recipe/deploy/symlink.php does this, and goes a step further: it feature-detects whether the platform's mv supports --no-target-directory (the -T that makes mv replace a symlink rather than move into the directory it points at), uses mv -T when available, and falls back to the two-step form when not. That is not a line of bash we would have thought to write, and the consequence of getting it wrong is an intermittent error under load during every deploy — the kind of bug that is never reproduced because it lasts a few milliseconds a fortnight.

The same shape of argument applies to release pruning that must never delete current, to set -euo pipefail discipline so a failed composer install does not sail on into the symlink flip, and to shared-path symlinking that must be idempotent. None of these is hard. All of them are already written, and already exercised by more installations than ours will ever be.

The honest counterweight: a hand-rolled script has no version to upgrade, no recipe layering to reason about, and no dep binary to be missing. Deployer's release cadence means we will eventually have to move across a major version. That is a real ongoing cost, and 8.x's divergence from 7.x — documented above in two places where the behaviour genuinely changed — is a preview of what that feels like.

This is the part that decides whether either option works, and it is worth understanding the mechanism rather than just copying a mitigation, because the mitigations are not equivalent.

Two caches sit between the flipped symlink and the code PHP actually runs.

The realpath cache memoises the resolution of a path to its real location. Per php.net's core ini directives, realpath_cache_ttl defaults to 120 seconds — "Duration of time (in seconds) for which to cache realpath information for a given file or directory" — and realpath_cache_size defaults to 4M. So for up to two minutes after the flip, a worker that had already resolved /var/www/app/current/public/index.php continues to believe it points at the old release.

Opcache then caches the compiled opcodes. Its default settings are actually helpful here — opcache.validate_timestamps defaults to 1 and opcache.revalidate_freq to 2 seconds, per the opcache configuration page — so opcache would notice a changed file. The problem is that it is not looking at a changed file. Deployer's own documentation states the mechanism in one sentence:

PHP Opcodes get cached. And if SCRIPT_FILENAME contains current symlink, on new deploy nothing updates.

— Avoid PHP-FPM reloading

That is the crux. If nginx hands FPM a SCRIPT_FILENAME containing current, the requested path is byte-identical across releases, so the cache key does not change and the timestamp being revalidated is whichever file the stale realpath cache says it is. Opcache keys entries both by a fast key derived from the requested filename and by the fully-resolved real path (this is visible in php-src's ZendAccelerator.c, in accel_make_persistent_key() and the revalidate_path branch of persistent_compile_file()), which is why making the real path differ per release is the lever that works.

The mitigations, and what each actually costs ​

Resolve the symlink in nginx ($realpath_root) — recommended. nginx defines the variable as:

$realpath_root — an absolute pathname corresponding to the root or alias directive's value for the current request, with all symbolic links resolved to real paths

— ngx_http_core_module

Used as the SCRIPT_FILENAME prefix, every release becomes a distinct real path and therefore a distinct opcache entry, so a flipped symlink serves new code on the very next request with no cache to invalidate and no process to signal. Deployer documents exactly this config:

nginx
location ~ \.php$ {
  include fastcgi_params;
  fastcgi_pass unix:/var/run/php/php-fpm.sock;
  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
  fastcgi_param DOCUMENT_ROOT $realpath_root;
}

Two costs, both real and both acceptable here. Opcache memory now grows with the number of distinct releases resolved since the last FPM restart rather than staying flat, so opcache.memory_consumption (default 128MB) and opcache.max_accelerated_files (default 10000) want a glance — for a site deploying a handful of times a week and pruning to a handful of releases, this is not close to a problem, but it is why the trick is not free. And __DIR__ / __FILE__ inside the application now report /…/releases/42/… rather than /…/current/…, which shows up in logs and in any code that reasons about its own path. Laravel does not, so this is cosmetic for us.

I could not find a statement on nginx.org quantifying the per-request cost of resolving symlinks for $realpath_root. It must involve filesystem calls, but no primary source I found puts a number on it, and I am not going to invent one.

Reload PHP-FPM — works, but Deployer explicitly argues against it. systemctl reload php8.4-fpm sends SIGUSR2, which php-fpm's own man page (sapi/fpm/php-fpm.8.in in php-src) documents as "graceful reload of all workers + reload of fpm conf/binary". Fresh workers start with an empty realpath cache, so this does fix the symptom. Deployer's contrib recipe for it opens with a caution against using it at all:

Do not reload php-fpm. Some user requests could fail or not complete in the process of reloading.

— contrib/php-fpm.php

and the task itself emits warning('Avoid reloading php-fpm …') at runtime before doing it. Note that "graceful" in the man page and "some user requests could fail" in Deployer's caution are in tension, and I did not find a primary source that resolves it — php-src says only "graceful" and does not elaborate. Separately, it requires the deploy user to hold sudo rights on systemctl, which is a privilege we would rather not grant an account whose whole job is to run code that arrived from GitHub.

opcache_reset() from the CLI — does not work, and this is the trap. The official description is "This function resets the entire opcode cache", which reads as though php -r 'opcache_reset();' in a deploy script would do the job. It does not: opcache's shared memory is attached per SAPI, so the CLI process resets the CLI's cache and the FPM master keeps its own. php.net's official prose does not say this; the clearest statement of it is in a user note on the opcache_reset() page —

In some (most?) systems PHP's CLI has a separate opcode cache to the one used by the web server or PHP-FPM process, which means running opcache_reset() in the CLI won't reset the webserver/fpm opcode cache, and vice-versa.

— which is consistent with how opcache attaches shared memory, but the source is a user note, not documentation. Worth flagging because the failure mode is that the command succeeds, returns true, and changes nothing.

cachetool — the correct way to reset FPM's cache from a script.cachetool sidesteps the SAPI problem by speaking FastCGI to the FPM socket directly: "It will connect to a FastCGI server (like PHP-FPM) and operate on its cache." Deployer ships contrib/cachetool.php, defining cachetool:clear:opcache (opcache:reset), cachetool:clear:apcu, and cachetool:clear:stat (which clears the realpath cache too) — and it is opt-in, not in the default flow; the docs tell you to wire it yourself with after('deploy:symlink', 'cachetool:clear:opcache'). Its cost is that the deploy user needs access to the FPM socket, which is a narrower grant than sudo-on-systemctl, and that it is another downloaded phar with its own PHP compatibility matrix (9.x requires PHP ≥ 8.1).

Tuning realpath_cache_ttl down — do not bother. It addresses half the problem (realpath, not opcache keying) and costs performance on every request forever to fix something that happens for two minutes after a deploy. I found no primary source quantifying that cost; everything specific I could find was blog benchmarks, so I will not put a number on it. It is the wrong lever regardless.

Configure nginx with $realpath_root and do nothing else. No FPM reload, no cachetool, no opcache task in the deploy flow. Each release is a distinct real path, so there is nothing stale to invalidate, and there is no privileged operation anywhere in the deploy.

This is what Deployer recommends, it is what Forge does — Forge's docs state, of its own zero-downtime mode, "it is unnecessary to reload the PHP-FPM service because every deployment is deployed to a new, uncached directory" — and it is the only mitigation that is a property of the configuration rather than an action taken on every deploy. That distinction is the whole argument: a config-level fix cannot be forgotten, cannot fail silently, and cannot be skipped by a deploy that took a different path through the script. Every other option is a step that has to run, and run after the flip, and be noticed when it doesn't.

The tradeoffs we are accepting: opcache entries accumulate per release (watch opcache.memory_consumption if release count ever grows), and __DIR__ reports real release paths. Keep cachetool in mind as the escape hatch if we ever hit a case $realpath_root doesn't cover, but do not wire it in pre-emptively.

This belongs to the nginx vhost ticket (issue 23), not to the deploy script. That is the point. If the vhost is written without $realpath_root, deploys will appear to succeed and serve stale code, and the deploy tooling — Deployer or bash — will be blamed for it. Worth a line in that ticket saying why the fastcgi_param lines are what they are, because they look like boilerplate and are not.

What choosing Deployer leaves for us to write ​

Deployer covers the release lifecycle. It does not cover this application. The list is short but none of it is optional:

  • A deploy.php declaring localhost(), deploy_path, update_code_strategy => 'local_archive', keep_releases, and the shared files and dirs (.env, storage).
  • The asset build. Require contrib/npm.php and hook npm:install and npm:build in after deploy:vendors and before deploy:publish. /public/build is gitignored, so a release without this serves an unstyled site — the failure the repo has already written down once, in ticket 004.
  • Env decryption. Nothing in Deployer knows about env:decrypt. The command takes --path and --filename and reads LARAVEL_ENV_ENCRYPTION_KEY from the environment when --key is not passed (verified in EnvironmentDecryptCommand.php in this repo's vendor tree), so the natural shape is a task that sources the root-only key file on the box and decrypts into the shared path before artisan:optimize runs. Ordering matters: config caching reads the env. How the key file is produced and rotated is issue 21.
  • Pinning the deployed commit. local_archive archives {{target}}, which defaults to HEAD. On a tag-triggered workflow the runner's checkout is already at the tag, so HEAD is correct — but passing --revision=$GITHUB_SHA explicitly makes that guarantee rather than inheriting it, and costs nothing.
  • The pre-migration database dump. Deployer's rollback does not touch the database and never will. Whatever issue 17 concludes becomes a task hooked before artisan:migrate.
  • Auto-unlock on failure, if we want it. One fail('deploy', …) hook. Decide deliberately; the default of leaving the lock is defensible.
  • The nginx $realpath_root config — belongs to issue 23, listed here so it is not lost.
  • The rollback-without-GitHub path. The map wants a script on the box that works when GitHub doesn't. dep rollback is that script, provided dep and deploy.php live on the box rather than only in the runner's workspace. Worth being explicit about, because local_archive otherwise creates no reason for the deploy definition to persist outside a job's checkout.

Notably absent from that list: release directories, the shared-path symlinking, the atomic flip, release pruning, locking, rollback candidate selection, and the REVISION file. Those are the parts a hand-rolled script would own, and they are the parts with the sharp edges.

Where the evidence is thin ​

Stated plainly, so nobody later mistakes confidence for verification:

  • No primary source documents the "self-hosted runner is the deploy target" pattern. Every component is documented and supported; the combination is assembled by us. There was no issue or discussion on it in Deployer's tracker.
  • opcache_reset()'s CLI limitation rests on a php.net user note, not official prose. It is consistent with the architecture and universally repeated, but it is not documented.
  • The cost of $realpath_root per request is unquantified by nginx.org.
  • The cost of lowering realpath_cache_ttl has no primary source at all.
  • "Graceful" FPM reload versus Deployer's "some user requests could fail" is an unresolved disagreement between two sources, and php-src does not elaborate past the word "graceful".
  • Deployer 7.x and 8.x behave differently in two places that matter here (local_archive, and artisan:reload in the default Laravel flow). Anything written before Deployer 8 should be treated as describing a different tool.