Runtime-Only Container Images for Self-Upgrading Agent Software
Executive Summary
There are two ways to put a long-lived Node.js application into a container.
- Baked image. The application version is part of the image. You upgrade by pulling a new image and recreating the container; state lives in volumes. This is the model assumed by the twelve-factor methodology and Kubernetes guidance, and, as of 2026-12-03, by the Docker documentation of the two open-source AI agent projects I checked (OpenClaw and Hermes Agent).
- Runtime-only image. The image carries OS packages, a pinned Node.js and a few CLI tools. The application is installed into a persistent volume on first start and upgraded in place by its own upgrade command.
The second model is not exotic. WordPress documents that after the initial install the application "becomes self-managing within the /var/www/html/ data volume." Jenkins keeps plugins and configuration in JENKINS_HOME, Node-RED keeps user-installed nodes in /data, Discourse upgrades application code from a web page inside the container, and Nextcloud's entrypoint copies code into the volume and upgrades when versions differ.
What the evidence shows:
- Pure forms are rare; hybrids dominate. Almost every project that keeps code in a volume still ships a new image for the runtime layer, and says so. Discourse's maintenance guide says those updates "are not picked up in
admin/upgrade." - The core hazard is three-way version skew between the image, the application in the volume, and the data. Nextcloud's entrypoint takes a lock, compares the code version in the volume with the code version in the image, and refuses to start when the volume's code is newer. Its
version.phprecords only that code was synced: it is copied before the install orocc upgraderuns, and the database schema is never read. A design that must survive failed migrations needs its own state record and must read the actual schema. - Native modules tie the app in the volume to the runtime in the image. Node's ABI guide says an addon built for one major loads on any minor or patch of it, and the app must be "recompiled, reinstalled, and redeployed" on a new major. Platform, CPU architecture, libc and linked system libraries matter too, so the check has to cover more than the Node major.
- Restart policies do not stop a failing start from looping. On Docker Engine 29.2.1, an entrypoint exiting at once with code 78 was restarted 8 times in about 15 seconds under
--restart on-failure, andunless-stoppedrestarts even clean exits. A failed migration therefore has to be recorded on the volume so that the next start goes straight to a maintenance state instead of migrating again. - Rarely republished images drift from security fixes. Node 24.x entered Maintenance LTS on 2026-10-20, and the Node project pre-announced a security release for 2026-12-09 covering 26.x, 24.x and 22.x. Under "republish only when the Docker files change," that release would not reach users automatically. This is the main structural weakness of the chosen policy (section 5.11).
- For AI agents the trade is sharper. Both agent projects I read chose image-owned, read-only application code and put memory, skills and config on the data volume. A runtime-only design makes the application tree writable and persistent, which is a trust-boundary change (section 6).
Recommendations in one paragraph: a bootstrap in the image that never loads the app tree; a validated state record on the volume; a boot gate that checks phase, runtime, native modules and every database before starting anything; installs, rebuilds and upgrades as journaled transactions with a durable recovery point; failures persisted as a maintenance state that keeps the container up; two locks; refusal of volumes with data but no record; and a release rule for Node security fixes.
Evidence labels: Verified means read in the cited source. Tested means I ran it locally; the transcripts are summarized where used. Inference is my reasoning from those sources. Unverified means I could not confirm it; I flag it or leave it out.
1. Scope, Method and Caveats
The context is a small self-hosted agent platform: a Node.js CLI, PM2-managed services, SQLite databases, and a per-user home directory with configuration, memory and component installs, plus its own upgrade command and component installer. The team's decision, taken as given: image is runtime only (Node 24.x pinned); the whole home directory is one volume; the app installs on first start; upgrades run inside the container; the image is republished as latest only when the Docker files change at a release; older image-based instances are not migrated.
Sources were fetched as raw files or pages on 2026-12-03 and quotations were checked word for word against the fetched text. Community images of other projects are labeled as third-party. Docker and PM2 behavior described as tested was run on a local Docker Engine 29.2.1 with throwaway containers; the samples in section 5 were run against temporary directories, including their failure paths.
2. The Two Models, Precisely
2.1 Baked image (immutable release artifact)
The twelve-factor text states the principle most cleanly. It separates build, release and run, and says "it is impossible to make changes to the code at runtime." A release "cannot be mutated once it is created" and "any change must create a new release" (12factor: Build, release, run).
Kubernetes documentation applies the same idea to image references. It advises avoiding :latest in production because it is "harder to track which version of the image is running and more difficult to roll back properly," notes that "tags can be moved to point to different images, but digests are fixed," and describes digest pinning as pinning "the code that you run" (Kubernetes: Images).
In this model the upgrade unit is the image. Rolling back means running the previous image, plus restoring state if the data was migrated. The container is cattle; the volume is the only pet.
2.2 Runtime-only image with the app in a volume
Here the image is closer to a base operating environment. The application is a mutable tree on the volume, installed once and upgraded by the application's own tooling. The three parts of the system then have independent versions: the image (OS packages, Node, tools), the application tree, and the data (databases, memory files, configuration).
This is a deliberate trade. You give up the "release is a single immutable artifact" property. In return you get upgrades that do not need a registry pull, do not need access to the container runtime (no Docker socket, no orchestrator), and use the same upgrade command that non-container users run. A self-hosted platform that already has an upgrade command and a component installer avoids a second upgrade path, but it takes on the state handling in section 5.
2.3 It is a spectrum, not a binary
Between the pure forms sit patterns I verified: copy-on-start from image to volume (Nextcloud, WordPress's first start); image-seeded defaults the volume may override (Jenkins); an in-app updater plus image rebuild for the runtime layer (Discourse); an in-system supervisor that swaps images (Home Assistant OS); and update-on-every-start in community packaging of one agent project (section 6). The design questions are the same everywhere: what is the source of truth for "which version is installed," who may change it, and what happens when the layers disagree.
3. Who Uses Which: A Source-Checked Survey
Summary first, evidence below. Each entry gives where the application code lives at runtime, how upgrades happen according to the project's documentation, and the closest model.
- Nextcloud (official Docker image). Code is copied into the
/var/www/htmlvolume. Upgrade: pull a new image and recreate the container; the entrypoint compares code versions and upgrades. Model: hybrid; the image carries the code and the volume holds the running copy. - WordPress (official image). Code is copied into
/var/www/htmlon first start only. Upgrade: "self-managing" inside the volume by default; the entrypoint never compares core versions. Model: app in the volume after first start. - Jenkins (official image). Jenkins itself is in the image; plugins and configuration are in
JENKINS_HOME. Upgrade: pull a new image (named volume); image-supplied plugins upgrade only if they were not upgraded manually. Model: hybrid with marker files. - Node-RED (official image). Node-RED is in the image; user-installed nodes are in
/data. Upgrade: pull a new image, keep the volume. Model: hybrid. - n8n (official image). n8n is in the image; credentials, database and keys are in
~/.n8n. Upgrade: pull and recreate. Model: baked. - GitLab (Omnibus image). Code is in the image. Upgrade: pull a new tag and recreate with the same volumes; GitLab reconfigures and upgrades on first run. Model: baked.
- Discourse (standard install). The container is built by
launcher; the web updater changes code inside it. Upgrade: web UI for routine releases,./launcher rebuild appfor the base image and libraries. Model: hybrid by design. - Home Assistant OS. Core runs as a container managed by a Supervisor, which updates Core and rolls back on a failed start. Model: baked images orchestrated by the system.
- Home Assistant Container. Code is in the image; users "manually handle updates." Model: baked.
- Ghost (new Docker tooling). Code is in the image. Upgrade:
git pull,docker compose pull,docker compose up -d. Model: baked. - code-server. Image, with an install script as an alternative. The Docker section gives no upgrade steps. Model: not determinable from the page.
3.1 Nextcloud
Nextcloud's Docker README says the installation and all non-database data live in the /var/www/html volume, describes updating as "pulling the new image, throwing away the old container and starting the new one," and says the startup script "will check for the version in your volume and the installed docker version" and upgrades on a mismatch. Only one major version can be upgraded at a time, and data in the main folder "will be overridden/removed during installation and upgrades" except for paths in an exclude list (README).
The entrypoint, in the order it runs (entrypoint):
- Initialization runs in a subshell under
flockonnextcloud-init-sync.lockin the volume. A process that cannot get the lock at once prints "Another process is initializing Nextcloud. Waiting..." and then blocks. The lock is released when the subshell ends, before the finalexec "$@". - The installed version is read from
version.phpin the volume (0.0.0.0if absent) and compared with the image'sversion.php. Both sides are the$OC_Versionof the code; the database is not consulted. - If the volume's code version is higher, startup exits with a message that "downgrading is not supported." If the image is more than one major ahead, startup exits too. Equal versions skip the whole block.
- Code is synced with
rsync --deleteand the exclude file;config,data,custom_appsandthemesare seeded only if missing or empty; thenversion.phpis copied. - Only after that: a fresh install runs
occ maintenance:install, with a first attempt plus up to 10 retries 10 seconds apart; an upgrade runs pre-upgrade hooks,occ upgrade, prints the apps the upgrade disabled, and runs post-upgrade hooks.
So version.php marks a finished code sync, not a finished install or migration. If occ upgrade fails, the script exits; on the next start the two code versions are equal and the entrypoint does not run occ upgrade again (inference from the code: the comparison is the only trigger). The admin manual independently says "Downgrading is not supported and risks corrupting your data" and "Skipping major versions is not supported," and says nothing about Docker (admin manual).
What carries over is the lock scoped to a subshell, the explicit comparison with a refusal when the volume is ahead, and the one-major rule. What does not carry over is the marker: a design that wants "the marker says ready only after migration succeeded" has to write a separate record after migration and check the database itself (section 5).
3.2 WordPress
The WordPress image README says the initial install comes from the image and "after that it becomes self-managing within the /var/www/html/ data volume," with automatic updates enabled by default. It offers a static alternative: build a custom image, run it read-only and deploy new containers, with a note to "rebuild and redeploy regularly to ensure you get all the latest WordPress security updates" (WordPress image README).
The entrypoint copies the bundled source into the working directory only when both index.php and wp-includes/version.php are missing, and it never compares versions or replaces core files once they exist. During that copy it skips any wp-content plugin or theme already in the destination, with a comment describing a downgrade scenario: a persisted wp-content, an updated plugin, a recreated container, and the plugin being downgraded by the older bundled copy (entrypoint).
This is the closest official example of "image seeds the app once, the volume owns it afterwards," and it shows the specific bug the model invites: an older bundled copy overwriting a newer in-volume copy. A runtime-only image avoids that class of bug by not bundling the app at all, but it inherits the opposite risk: nothing in the image knows what version should be there.
3.3 Jenkins
The Jenkins Docker README says "All Jenkins data lives in there - including plugins and configuration," recommends a named volume, and says that with a named volume "the upgrade consists of docker pull and nothing more." Reference content in the image is copied into JENKINS_HOME at startup if required, and "It will not override such files," so plugins upgraded through the UI stay upgraded. Image-supplied plugins are upgraded on image updates only if they were not manually upgraded and the image version is newer, with a marker file tracking this. PLUGINS_FORCE_UPGRADE=true overrides manual upgrades, and TRY_UPGRADE_IF_NO_MARKER=true upgrades plugins on volumes written by images that predate the markers (the default is to leave them in place) (Jenkins docker README).
Jenkins is the best-documented example of reconciling two writers of the same files (the image and the running application) with a marker and an explicit override switch. The need for TRY_UPGRADE_IF_NO_MARKER is also a small real-world confession: once you add a marker, you must decide what to do with volumes that predate it.
3.4 Node-RED
The Node-RED Docker page keeps user configuration in /data, shows installing extra nodes with npm install from a shell inside a running container, and shows a Dockerfile pattern that copies a package.json into /data and runs npm install. It says that copy-in approach is "NOT suitable if you want to mount the /data volume externally." Updating is docker pull plus recreate with the same volume. The page itself does not say what happens to modules already installed in /data when the image's Node version changes. It does say the images are built on Alpine, which "removes standard dependencies that are required for native module compilation," and that a Debian-based image exists since v3.1.0 for nodes with native components (Node-RED Docker docs).
Node-RED is therefore a direct, widely used precedent for npm-installed code living in a volume next to a changing Node runtime in the image. I did not find a statement in that page about rebuilding native modules after an image update, and I do not assert one exists.
3.5 n8n
n8n documents n8nio/n8n with a volume at /home/node/.n8n, which by default holds the SQLite database; with PostgreSQL it still holds "encryption keys, instance logs, and source control feature assets." Updating is pull and recreate; the page shows pulling the latest stable version, an exact version, or next, which it labels unstable, and the page is marked outdated in favor of the Compose guide (n8n Docker docs). Community nodes install from npm through the GUI for Owner or Admin users; that page says nothing about Docker or persistence (community nodes). So n8n is a baked image whose users can still install npm packages at runtime; where they land is not stated on the pages I read.
3.6 GitLab Omnibus in Docker
GitLab's Docker upgrade page prescribes a backup, then stop and remove the container, pull the new tag (<version>-ee.0 or -ce.0), and recreate with the same volumes; "On the first run, GitLab reconfigures and upgrades itself." It defers the upgrade path to a planning page and downgrades to a rolling-back page, neither of which I read (upgrade, rollback index). It is a baked image where start-up migration is accepted, with an explicit backup step first.
3.7 Discourse
The standard Discourse install uses a launcher script around Docker; rebuild is "destroy old, bootstrap, start new." The install guide lists the browser upgrade at /admin/upgrade as the recommended way to upgrade, gives ./launcher rebuild app as the command-line alternative, and uses the same command after configuration edits (install guide).
The community maintenance guide is explicit about the split: self-hosters occasionally need a command-line update "to get the latest security releases and newest libraries," and "These updates are not picked up in admin/upgrade." A commenter writes that when Discourse advises updating the image, "it is not possible to upgrade from the UI." The guide suggests the web updater twice a month, the container every two months and the OS every six, and recommends automatic host security updates (manual update guide).
Discourse is the most relevant production precedent: an in-container app upgrader for routine releases, a rebuild path for the runtime layer, and a coupling where an image that is too old blocks the in-app upgrade. I verified that coupling only through a forum commenter, so treat the exact rule as reported behavior.
3.8 Home Assistant
Home Assistant offers two installation types: Home Assistant OS (recommended, supports apps) and Container, where you "manually handle updates" and, in the page's words, "Home Assistant Container installations don’t have access to apps" (installation). The Container update is pull, stop, remove, run again (Container install). The 2025-05-22 announcement deprecated the Core (Python environment) and Supervised methods, saying they "are not only complex for users to install and maintain — they’re also challenging for the Home Assistant team to support," and that their complexity "places a disproportionate burden on our community-driven support system." Support continued until release 2025.12; users may keep running them, and the migration advice is backup and restore across methods (HA blog).
On Home Assistant OS the Supervisor is a container that runs and updates Core as another container, and "When an update fails to start, it rolls back" (Supervisor docs). That is a third pattern: baked images upgraded from inside the system by a privileged supervisor with rollback; the page does not describe the mechanics. Two lessons carry over: HA handled its unsupported shapes by announcing, giving a window and recommending backup and restore rather than an in-place converter, and it cut supported shapes to reduce support burden (relevant to section 5.13).
3.9 Ghost, code-server and dev containers
Ghost's Docker setup, a preview introduced with the launch of Ghost 6.0, is Compose-based (Ghost, Caddy, MySQL) and updates with git pull && docker compose pull && docker compose up -d (Ghost Docker docs): baked. code-server's install page shows codercom/code-server:latest with bind mounts for ~/.local and ~/.config but no upgrade steps (code-server install), so I make no claim about its model.
Dev containers split provisioning into lifecycle steps: onCreateCommand, updateContentCommand and postCreateCommand finalize setup when the container is created, postStartCommand runs "each time the container is successfully started," and if one lifecycle script fails, later ones are not executed (Dev Containers reference). The failure rule, stop the chain, is the opposite of a crash loop.
4. Failure Modes
For each failure mode I note how the baked model, the runtime-only model, and the hybrids fare. Evidence is cited where I have it; the rest is marked as inference.
4.1 Version skew between image and volume
Baked image. Skew is between the image and the data. The typical guards are a refusal to start when the volume is ahead of the image (Nextcloud compares code versions for this), or an explicit migration step on start, as GitLab and the AI agent projects below do.
Runtime-only. Skew now has three sides. The image says "Node 24.x on this OS and architecture"; the app tree says "app 2.3, built against that runtime"; the data says "schema N" per database. Any pair can be out of step:
- A newer image (new Node major, new Debian release) over an older app tree: native modules built for the old runtime may fail to load.
- An older image over a newer app tree: the app may need a newer Node than the image provides.
- A newer app over older data: needs a migration.
- An older app over newer data (rollback, or a migration that advanced the schema before the app's state record was updated): the dangerous case; many migrations are forward-only.
Inference: each side needs its own check against what is actually there. The runtime is read from the running Node; the app's requirements come from the installed release's manifest; the schema is read from each database, not from a marker, because a marker can lag behind a migration that already ran. Section 5.3 gives the order of these checks and what each failure leads to.
4.2 Downgrade by pulling an older image
In the baked model, running an older image over newer data is the classic downgrade accident. Nextcloud's entrypoint blocks the code-level version of it, and its admin manual says downgrading "is not supported and risks corrupting your data" (entrypoint, admin manual). The OpenClaw Docker documentation states the rollback rule: "a rollback must restore the matching state as well as the old image" (OpenClaw Docker docs).
In the runtime-only model, pulling an older image does not downgrade the app, because the app lives in the volume. The remaining risk is a runtime the installed app does not support, such as an older Node major (section 4.5). Inference: rolling back the app needs its own backup and restore, so "undo an upgrade" becomes a platform feature rather than something image tags give you for free.
4.3 First-start install failures
A runtime-only image moves the dependency download from build time to first start, so the first start now depends on the network, registry availability, proxies and disk space on the user's machine. In the baked model these fail in CI, where someone sees them.
What the sources let me say:
- npm has retry and timeout settings:
fetch-retriesdefaults to 2,fetch-retry-mintimeoutto 10 seconds,fetch-timeoutto 5 minutes. Proxies are honored via configuration or the usual environment variables, andregistry,cache,offlineandprefer-offlineare configurable (npm config). npm cirequires a lockfile, errors when the lockfile andpackage.jsondisagree, never writes to either, and removes an existingnode_modulesbefore installing (npm ci). That makes each attempt start from a cleannode_modules, but onlynode_modules.- Nextcloud makes a first install attempt plus up to 10 retries 10 seconds apart (entrypoint). Hermes Agent caps the installation of default plugins before services start at 300 seconds (Hermes Docker docs).
- The dev container specification stops the lifecycle chain when one script fails (Dev Containers).
Inference: a clean node_modules, a temporary directory and an atomic rename each fix one piece of state. None of them covers a first start that already created databases or configuration before it failed, or a crash between the rename and the record that says "installed." The next start then sees a volume that has data but no "ready" record, which looks the same as a volume from an older image. Section 5.5 resolves this with an install record written before anything else, so the entrypoint can tell its own leftovers from unknown data.
4.4 Partial upgrades and crash loops
Three mechanisms can turn a failed upgrade into a loop:
- Docker restart policy. The values are
no,on-failure[:max-retries],alwaysandunless-stopped. The page says: "A restart policy only takes effect after a container starts successfully. In this case, starting successfully means that the container is up for at least 10 seconds and Docker has started monitoring it. This prevents a container which doesn't start at all from going into a restart loop." (restart policies). That sentence does not mean a fast exit escapes the policy. In Moby's restart manager (v26.1.2), a run of 10 seconds or more resets the restart back-off; a shorter run doubles it, and the policy still decides whether to restart (restartmanager.go). Tested on Docker Engine 29.2.1: an entrypoint that exits 78 at once was restarted 8 times in about 15 seconds underon-failure, with growing gaps; underon-failure:2it stopped after 2 restarts; underunless-stoppeda container that exits 0 at once was also restarted. No exit code stopsalwaysorunless-stopped. - PM2 inside the container. PM2 restarts crashed children by design, so while it keeps restarting them the container stays up and Docker sees it running. By default
pm2-runtimealso exits (code 2) once no application has been online for a few consecutive checks, which hands the container to the restart policy;--no-auto-exitturns that off (section 5.8, tested). - Automatic migration on start. OpenClaw's entrypoint migrates state in place. Before advancing database schemas it saves verified SQLite copies as
<database>.pre-startup-migration-<id>.bak; fully declared table migrations may instead use.scoped.bakarchives, and only those are restored withopenclaw database restore-migration-backup, never by replacing the database file. Retries with the same candidate build, database files and target schemas reuse the first completed backup group. "Startup exits with code 78 when required state cannot be migrated safely," the page says, and it adds: "With a restart policy, Docker, Podman, or Kubernetes may show the Gateway container restarting." The documented recovery is to run the same image once withopenclaw doctor --fixon the same mounts, then restart the Gateway (OpenClaw docs). Hermes writes timestamped backups ofconfig.yamland.envbefore a configuration migration and offersHERMES_SKIP_CONFIG_MIGRATION=1for manual inspection (Hermes docs).
The team's incident fits this pattern. The sources agree on backing up before migrating, stopping on a failed migration and giving the operator a repair command; point 1 adds that the stop has to be recorded where the next start reads it first (section 5.7).
On SQLite, the backup page describes the older method of copying the database file under a shared lock and notes: "If a power failure or operating system failure occurs while copying the database file the backup database may be corrupted following system recovery." The online backup API produces "a bit-wise identical copy of the source database as it was when the copying commenced"; VACUUM INTO is another option (SQLite backup). Each of these gives a consistent copy of one database. A platform with several databases plus configuration files gets one consistent recovery point only if nothing writes to any of them while the copies are taken (section 5.6).
Takeover logic belongs in the volume too. OpenClaw's docs say "Keep one Gateway replica per state volume, and stop the old container before starting its replacement"; if the old container stopped abruptly, "allow up to 90 seconds from its last heartbeat for automatic takeover"; the state directory holds "state ownership locks"; and "Do not delete lock files or repeatedly restart competing containers" (OpenClaw docs). Inference: ownership should be decided from the volume, not from image defaults; section 5.4 uses a kernel file lock, which needs no heartbeat.
4.5 Native modules versus the runtime in the image
The Node ABI guide states the rule for addons built against Node's own headers: an addon compiled against a major "will load successfully when loaded by any Node.js minor or patch version within the major version against which it was compiled," and an application with native addons "has to be recompiled, reinstalled, and redeployed whenever a new major version of Node.js is introduced into the production environment" (ABI stability). Node-API is designed to "allow modules compiled for one major version to run on later major versions of Node.js without recompilation," but the same page adds that "other parts of Node.js do not, and any external libraries used from the addon may not" give that guarantee; only an addon that uses Node-API exclusively and checks its external libraries stays compatible across majors (Node-API). The addons page warns that the V8 API "can, and has, changed dramatically" between releases (addons).
The distribution index exposes Node's module ABI as a modules field. As fetched on 2026-12-03: v20.0.0 is 115, v22.0.0 is 127, v24.0.0 is 137, v24.23.0 is still 137, and v26.0.0 is 147 (dist index), consistent with the guide.
For a runtime-only image (inference unless cited):
- The module ABI answers only the Node layer. A compiled addon also depends on platform, CPU architecture, the libc it was linked against and any system libraries it loads, all of which come from the image. A matching
process.versions.modulesis necessary, not sufficient. - Minor and patch Node updates on the same base OS are the safe case. A Node major change, a different architecture, a switch between glibc and musl, or a new Debian release can each break installed addons, Node-API ones included if they link system libraries.
- The simple rule is to rebuild native modules whenever the image changes (section 5.9), rather than trying to classify which addons are affected. Whether the platform's SQLite binding compiles native code is unverified.
- Debian release matters. Official tags
node:24andnode:24-slimresolved to Bookworm when I read the page, whilenode:26andlatestresolved to Trixie, and the page advises explicit Debian-suite tags to "minimize breakage when there are new releases of Debian" (Docker Hub: node). Moving from Node 24 to 26 on unsuffixed tags would change the Debian release too.
4.6 Reproducibility and supply chain
"What is actually running?" has a short answer in the baked model: an image digest. Kubernetes says tags can move and digests cannot (Images); Docker notes that digest pinning means "opting out of automated security fixes" and recommends Dependabot pull requests over moving tags, because then "you have an audit trail of when and how the change occurred" (best practices); BuildKit adds minimal provenance attestations to images by default and can add SBOMs (attestations).
In the runtime-only model the digest tells you only the runtime; the application is whatever the upgrade command fetched, when it fetched it, and image attestations say nothing about it. What the platform must provide itself (inference):
- A lockfile-driven install (
npm ci), so one app version gives one intended dependency set. The lockfile records intent; it says nothing about whether the files on disk still match it. - Signature and provenance checks:
npm audit signaturesverifies registry signatures and provenance attestations of downloaded packages (npm audit). Provenance "does not guarantee the package has no malicious code"; it gives an auditable link to source (npm provenance). By defaultnpm ciruns dependency install scripts during the install, so an audit run afterwards cannot undo what those scripts did; section 5.15 orders these steps. - A status output and start-up log line with image identity, Node version and runtime record, app version and lockfile hash. Hermes keeps image provenance in
/etc/hermes/image-provenance.jsonand a build stamp in/opt/hermes/install-stamp.json, the baked analog (Hermes docs).
The supply-chain boundary moves from release time to every upgrade on every user's machine; the mitigations exist but are the platform's responsibility.
4.7 Security patching of the base OS and runtime
Official images are rebuilt when their base changes: tags are rebuilt "through an update to that library file or as a result of its base image being updated" (official-images README). A derived image is a snapshot, though; Docker says rebuild regularly and distinguishes --pull (fresh base) from --no-cache (re-run build steps) (build best practices). WordPress's README gives the same warning for its static variant.
An in-container upgrade command patches the application, not the runtime layer. A community OpenClaw image separates updating OpenClaw itself from updating the "Docker image (Node, Chrome, OS packages, shim itself)" (README), and Discourse separates the web updater from the command-line update for "the latest security releases and newest libraries."
Concrete facts as of 2026-12-03:
- Per the release schedule file, Node 24 ("Krypton") entered Maintenance LTS on 2026-10-20 and reaches end of life on 2028-04-30; Node 26 became LTS on 2026-10-28 (schedule). Node says "Production applications should only use Active LTS or Maintenance LTS releases" (previous releases).
- The newest 24.x in the distribution index is v24.23.0 (2026-11-30). The November 2026 security release patched 24.x in v24.22.3, highest severity HIGH (November post). Another release for 26.x, 24.x and 22.x is pre-announced to ship "on or shortly after" 2026-12-09, again highest severity HIGH; end-of-life lines are always affected (December post). The date is still a plan. I claim no specific exposure for a CLI-plus-services workload.
Inference: under "republish only when the Docker files change," the 2026-12-09 release reaches users only if a release that edits the Docker files happens to ship soon after (options in 5.11).
4.8 Tag strategy: latest-only versus semver
Kubernetes and Docker both warn against latest for reproducibility; the official-images README gives it a specific meaning: it is really "default," and the image it aliases "should reflect which version or variation of the software users should use if they do not know or do not care which version they use." Agent-adjacent projects differ:
- The Coolify OpenClaw image publishes
<version>andlatestand advises: "Pincoollabsio/openclaw:<version>" (README). - pingtxt's merged change stops pushing
:latestfrommain:mainpublishes:main, av1.2.3tag publishes:1.2.3and:latest, and pre-releases do not move:latest(PR 44). - n8n's page shows pulling the latest stable version, an exact version, or
next, which it labels unstable (n8n docs).
For a runtime-only image, latest-only is less dangerous than for a baked app, since the app version is not in the tag. The costs (inference): nobody can pin the previous runtime except by digest, and only while the registry still serves that manifest; support must ask for a digest or status output rather than a tag; and a runtime change that breaks the volume (Node major, Debian release) reaches everyone who pulls and recreates, with no opt-out. Under the team's rule on new mechanisms, adding immutable tags is their decision; section 5.14 lists compensations that need no new tags.
5. Design Guidance for the Runtime-Only Model
Everything in this section is my synthesis of the sources above and standard container practice. Where a statement rests on a specific source, it is cited; otherwise it is inference. The two code samples are illustrative skeletons; I ran both against temporary directories with a test stub standing in for the bootstrap, including the failure paths listed in 5.3.
5.1 What the image should carry
- Node.js pinned to a major. The ABI rule makes the major the compatibility boundary for Node itself. Pin it and let minors and patches move on rebuild. If using an official tag,
node:24resolved to Bookworm in the page I read; use an explicit Debian-suite tag if the OS release matters (Docker Hub: node). - A stated Debian or Alpine release. Native binaries link against the libc and system libraries of the image. The Node image page notes that Alpine uses musl, so "software will often run into issues depending on the depth of their libc requirements"; Node-RED documents the same for native modules (Node-RED docs).
- The platform bootstrap. A small, versioned program shipped in the image, not in the volume: the entrypoint script plus a
platformcommand that owns the locks, the state record, schema reading, first install, native rebuilds, migrations and recovery. It reads the release manifest as data and never loads the app tree, so it works on an empty volume and on an app that is broken or was built for another runtime. The app supplies its migrations and health command; the bootstrap decides when they may run. This is the part of the runtime-only image that is not "just runtime." - Tools the bootstrap and app need: git, build tools if any package compiles, CA certificates,
tini,flock(util-linux, present in the Debian-basednode:22-slimimage I tested) and thesemverpackage for the bootstrap. Twelve-factor's view is that tools should not be implicitly present (Dependencies). - A non-root user with a fixed UID. The Node images "provide the
nodeuser with uid 1000" (best practices); decide the UID once and document it. - A build identity, written into the image at build time (for example a random ID in a file), because the registry digest is not visible inside the container. The bootstrap uses it to detect a new image (5.9).
- Not the app version. Pinning one "just in case" recreates the skew problem.
5.2 State on the volume
Keep two kinds of files apart (inference):
- Control files in one directory, say
.platform/: the two lock files and the state record. The entrypoint creates this directory before it looks at anything else, so a volume that contains only.platform/still counts as empty. - Everything else: release directories, databases, memory, configuration, caches, backups.
The state record is one small JSON file, written atomically (temporary file, fsync, rename, fsync of the directory). It holds:
phase:installing,ready,upgradingormaintenance. Onlyreadylets services start.install_idandowned(while installing): an identifier for this attempt and which of the fixed first-install names (releases,data,config) it may create, written before it creates any of them (5.5).app: the active release directory,releases/<name>, and its manifest: version, supported Node majors, and for each database the oldest schema it can migrate from and the schema it expects. Services run from the directory named here, so switching releases is a state write, not a separate symlink.native: the build identity of the image the release's native modules were built under, plus Node version, module ABI, platform, architecture and libc, which are diagnostics.dbs: the databases that existed when the current state was committed; it tells a missing database from a new one (5.3).upgradeandprev(while upgrading): origin (commandfor an online or offline upgrade,bootfor a migration the gate found), from and candidate versions, the current step and the backup identifier (the backup lives inbackups/<id>);previs thereadyormaintenancerecord the transaction started from.reason(in maintenance): what failed and which command resolves it.
The layout is fixed, so the record holds plain names (no /, . or ..), not paths. Every file operation also re-checks that the resolved path is inside the directory it may touch.
What the record deliberately does not hold is the current schema of each database. That is read from the databases themselves at every start (for example PRAGMA user_version), because a migration can advance a database before the record is updated, and a restored backup can move it back.
Precedent for tying an in-volume artifact to the runtime: pingtxt runs a self-updated binary from its /data volume only "if that update was installed on this same image," and otherwise discards it (pingtxt PR 44). There the image is the authority; here the volume is, so a runtime mismatch leads to a rebuild or a refusal instead.
5.3 The entrypoint: a fixed order of checks
The entrypoint is a short script that can be killed at any line and re-run. It provides the locks, the entry modes, a bounded loop and three outcomes (start, hold, stop); the decisions are made by the bootstrap's platform next-action, and each step by platform run, which already runs under the entrypoint's state.lock and does not take it again.
#!/bin/sh
# Illustrative skeleton. "platform" is the bootstrap shipped in the image
# (section 5.1); it never loads the app tree.
set -eu
H=${PLATFORM_HOME:-/home/app} # the one volume
C="$H/.platform" # control files, never counted as user data
mkdir -p "$C"
# Volume ownership for the container's lifetime. fd 8 is inherited on
# purpose by whatever is exec'd below; the kernel drops the lock when the
# last process holding it exits, which in a container means container exit.
exec 8>"$C/owner.lock"
flock -n 8 || { echo "volume is in use by another container" >&2; exit 75; }
# Offline commands (docker run ... upgrade): same owner lock, no boot gate;
# each takes state.lock itself.
case "${1-}" in upgrade|repair|resume|rollback) exec platform "$@" ;; esac
# Boot gate. The subshell scopes fd 9, so state.lock is released before
# exec. set -e does not apply inside "( ... ) || rc=$?": every exit is explicit.
rc=0
(
flock 9 || exit 4 # no lock: touch nothing, start nothing
for pass in 1 2 3 4 5; do
action=$(platform next-action) || exit 3
case "$action" in
start) exit 0 ;;
maintenance) exit 3 ;; # refusal: recomputed on every start
*) platform run "$action" || exit $? ;;
esac # 1 = retryable, 5 = failed and persisted
done
exit 3
) 9>"$C/state.lock" || rc=$?
case "$rc" in
0) exec "$@" ;; # pm2-runtime --no-auto-exit ecosystem.config.js
3|5) exec platform hold ;; # stay up and unhealthy; never migrate again
*) echo "boot gate stopped (code $rc); nothing started" >&2; exit "$rc" ;;
esac
Three entry modes share the same two locks:
- Normal boot runs the gate: checks, at most five steps, then services start only on a
startanswer. - Offline commands (
docker run --rm -v <volume>:/home/app <image> upgrade, orrepair,resume,rollback) takeowner.locklike any start, skip the gate and run the bootstrap command, which takesstate.lockitself and exits when done; services start only through the gate on the next start. A volume the gate refuses can therefore still be repaired or upgraded; the offline upgrade checks the candidate, not the installed release, which is never started offline (5.6 step 1). - Online commands (
docker exec <container> platform upgradeand the others) run inside the owning container and takestate.lock(5.4); a successful online upgrade starts the services through PM2.
next-action reads the state record, the runtime and the actual schemas and returns the one step that must happen next; upgradeProblem is the upgrade command's precondition (5.6):
// decide.js, part of the image's bootstrap (illustrative). It never loads
// the app tree and acts only on records that pass these checks.
// state: parsed .platform/state.json, or null if the file is absent
// rt: runtimeOf(buildId) for the running image
// actual: { userData: bool, schema: { db: number|null } } with one entry
// per database file found on the volume (null = unreadable)
const semver = require('semver');
const own = (o, k) => o !== null && typeof o === 'object' && Object.hasOwn(o, k);
const int = Number.isSafeInteger;
const str = (v) => typeof v === 'string' && v !== '';
// Fixed layout: records hold plain names, never paths. A plain name has no
// '/' and cannot be '.' or '..'. A first install creates only SEEDS.
const name = (v) => typeof v === 'string' && /^[A-Za-z0-9][\w.@+-]*$/.test(v);
const SEEDS = ['releases', 'data', 'config'];
// Contract: canonical SemVer without build metadata; numeric parts of 16+
// digits are refused because semver compares them as JS numbers.
const ver = (v) => str(v) && semver.valid(v) === v && !/\d{16}/.test(v);
const STEPS = ['stopping', 'backed-up', 'migrated'];
function validManifest(m) {
if (!own(m, 'version') || !own(m, 'nodeMajors') || !own(m, 'schema')) return false;
const { version, nodeMajors: n, schema: s } = m;
return ver(version) && Array.isArray(n) && n.length > 0 && n.every(int) &&
s !== null && typeof s === 'object' && !Array.isArray(s) && Object.keys(s).every(name) &&
Object.values(s).every((r) => own(r, 'oldest') && own(r, 'current') &&
int(r.oldest) && int(r.current) && r.oldest >= 0 && r.oldest <= r.current);
}
// ready and maintenance records describe the installed release; dbs lists
// the databases that existed when that state was committed.
const validInstalled = (s) => own(s, 'app') && validManifest(s.app) &&
str(s.app.dir) && s.app.dir.startsWith('releases/') &&
name(s.app.dir.slice(9)) && own(s.native, 'build') && str(s.native.build) &&
Array.isArray(s.dbs) && s.dbs.every((d) => own(s.app.schema, d));
function validRecord(s) {
if (!own(s, 'phase')) return false;
const u = s.upgrade;
switch (s.phase) {
case 'ready': return validInstalled(s);
case 'maintenance': return validInstalled(s) && str(s.reason);
case 'installing': return name(s.install_id) && Array.isArray(s.owned) &&
s.owned.length > 0 && s.owned.every((p) => SEEDS.includes(p));
case 'upgrading': return own(u, 'origin') && ['command', 'boot'].includes(u.origin) &&
STEPS.includes(u.step) && ver(u.from) && ver(u.candidate) && name(u.backup) &&
own(s.prev, 'phase') && ['ready', 'maintenance'].includes(s.prev.phase) &&
validRecord(s.prev);
default: return false;
}
}
function nextAction(state, rt, actual) {
if (state === null)
return actual.userData ? ['maintenance', 'data without platform state']
: ['install'];
if (!validRecord(state)) return ['maintenance', 'unreadable platform state'];
if (state.phase === 'maintenance') return ['maintenance', state.reason];
if (state.phase === 'installing') return ['discard-and-install'];
if (state.phase === 'upgrading') return ['recover'];
if (!str(rt.build)) return ['maintenance', 'image has no build identity'];
const app = state.app;
if (!app.nodeMajors.includes(rt.nodeMajor))
return ['maintenance', `image Node ${rt.nodeMajor} is not supported`];
if (state.native.build !== rt.build) return ['rebuild'];
const why = schemaProblem(app, state.dbs, actual);
if (why) return ['maintenance', why];
// Behind, or a database the release defines that was never created.
const behind = Object.keys(app.schema).some((db) =>
!state.dbs.includes(db) || actual.schema[db] < app.schema[db].current);
return [behind ? 'migrate' : 'start'];
}
// Every recorded database must exist and be within the release's range;
// nothing else may be on disk. A missing one is restored, never recreated.
function schemaProblem(app, dbs, actual) {
for (const db of Object.keys(actual.schema))
if (!dbs.includes(db)) return `${db}: database not in the record`;
for (const db of dbs) {
if (!own(app.schema, db)) return `${db}: not supported by this release`;
if (!own(actual.schema, db)) return `${db}: missing, restore from backup`;
const v = actual.schema[db], r = app.schema[db];
if (!int(v)) return `${db}: schema unreadable`;
if (v > r.current) return `${db}: schema ${v} is too new`;
if (v < r.oldest) return `${db}: schema ${v} is too old`;
}
return null;
}
// Precondition for upgrade (online or offline). It checks the candidate,
// not the installed release, which is never started during the upgrade.
function upgradeProblem(state, rt, actual, cand) {
if (!validRecord(state)) return 'platform state is missing or unreadable: run repair';
if (!['ready', 'maintenance'].includes(state.phase))
return `phase ${state.phase} is open: run recover or repair first`;
if (!str(rt.build)) return 'image has no build identity';
if (!validManifest(cand)) return 'candidate manifest is invalid';
if (!cand.nodeMajors.includes(rt.nodeMajor))
return `candidate does not support Node ${rt.nodeMajor}`;
if (semver.compare(cand.version, state.app.version) <= 0)
return 'candidate is not newer than the installed release';
return schemaProblem(cand, state.dbs, actual);
}
// build: identity written into the image when it is built (5.9); any change
// triggers a rebuild. The other fields are diagnostics.
function runtimeOf(build) {
const glibc = process.report.getReport().header.glibcVersionRuntime;
return { build, nodeMajor: Number(process.versions.node.split('.')[0]),
node: process.versions.node, modules: process.versions.modules,
platform: process.platform, arch: process.arch,
libc: glibc ? `glibc ${glibc}` : 'not glibc' };
}
module.exports = { nextAction, upgradeProblem, runtimeOf };
The rules this encodes:
- Act only on validated records. Each phase has its own checks (
validRecord). Anything else, including a record that holds only a phase, names a path instead of a plain name, or nests one transaction in another, is refused as unreadable, before any delete or restore. A missing record next to user data and an image without a build identity are refused too. - Missing versus new is decided by the record, not by schema 0. Every database in
dbsmust exist and be within the release's range; one that is missing is refused with "restore from backup", even if the manifest's oldest schema is 0. A database the manifest lists butdbsdoes not is new, andmigratecreates it; a file in neither is refused. Any such problem in any database refuses the whole start, in any order;migrateis returned only when there is none. - Order: phase, runtime, native modules, schema. Native modules are rebuilt first, because migration code may load them. An image whose Node major the release does not list is refused, not "fixed," because the fix is a different image or an app upgrade.
- One step at a time, then re-check. Each step commits its own state and the loop asks again from the top, so a start that finds both a new image and a pending migration runs
rebuild, thenmigrate, then starts. - Lock failure stops everything. If
flockonstate.lockfails, or the lock file cannot be opened, the gate exits without calling the bootstrap and without starting services. - Refusals and failures are different. A refusal touches nothing and is recomputed on every start, so pulling the right image or restoring the right backup clears it. A failed step that changed data persists
phase=maintenance(code 5), so a restart never repeats it (5.7). Only steps that touched no user data (first install, native rebuild) return the retry code 1. - Versions follow an explicit contract wherever they are read: canonical SemVer without build metadata, and no numeric part of 16 or more digits, because npm's
semverpackage compares numeric identifiers as JavaScript numbers (it reported1.0.0-9007199254740992and1.0.0-9007199254740993as equal). The upgrade precondition compares withsemver.compare; a candidate must be strictly newer, and lower is the rollback command's job.
Tested with both samples byte-identical to the text above, the script run by dash, and a stub bootstrap that creates real SQLite files. Every new case was also run against the previous revision of the samples as a negative control:
nextActionandupgradeProblem: 18 new cases plus the 65 earlier ones (including all 36 orderings of three databases with one behind and one too new, and the SemVer 2.0.0 precedence chain).- Records that would steer a delete or restore (
ownedof.or.platform,app.diroutsidereleases/, backup../other, aprevin phaseupgrading, a backup manifest from another transaction, a backup directory symlinked out of the volume) were all refused with the volume and its parent unchanged. The previous revision deleted the whole volume for., the lock directory for.platform, and restored from the wrong backup in the last four. An upgrade on an image without a build identity is now refused; the previous revision committed a record the next start refused. - A boot migration killed at
step=stopping, then two starts: both held in maintenance with the data untouched; the previous text returned toready, and the first start migrated again. - Offline upgrades of a Node 24-only release on a Node 26 image to a candidate supporting both, and of a volume in maintenance after a restored boot migration to a fixed release, committed and exited without starting services; the next start ran through the gate. The previous text refused both. A volume in
upgradingwas refused unchanged. Killed before the recovery point, the upgrade returned to the old record and the next start held; killed after it, the next start restored, removed the database the migration had created, and held. - A boot migration committed, then the gate asked again and started. Lock scope,
flockfailing on fd 9 only, first-start crash and retry, old volume, schema newer than the release, new image plus pending migration, crash during the restore itself, and a corrupt record behaved as described in 5.4–5.7.
5.4 Locks and volume ownership
Two locks, two purposes (inference, with the behavior tested as described):
owner.lock: one container per volume. The entrypoint takes it withflock -non a file descriptor that stays open in whatever itexecs. Tested: with two containers on one named volume, the second was refused while the first ran; after the first was killed with SIGKILL, a new container got the lock at once. There is no heartbeat, PID file or takeover timeout: the kernel releases the lock when the last process holding the descriptor exits, and in a container all processes exit together.state.lock: one state transition at a time. The boot gate holds it in a subshell and releases it beforeexec, as Nextcloud does; steps the gate runs are internal calls under that lock. The online and offlineupgrade,rollback,repairandresumecommands take it for their whole run and re-read the state record only after they have it.- Online commands run only in the owning container. The entrypoint writes a random boot identifier both under
/runand, holdingowner.lock, into the volume; online commands refuse to run unless the two match.
Whether flock behaves the same on every volume driver and network filesystem is something I did not verify; Docker's documentation notes that "bind mounts are dependent on the directory structure and OS of the host machine" while volumes are managed by Docker (Docker volumes). The tested case is a local named volume.
5.5 First start as a transaction
A first start may download, build, create databases and seed configuration. To make every interruption recoverable without a human (inference, tested with the stub):
- Recognise an empty volume. Nothing outside
.platform/and no state record. Anything else without a state record is refused (section 5.13). - Write the intent first.
phase=installing, an install identifier and the list of paths this install may create (for examplereleases/,data/, the default config file). Nothing else exists yet. - Install the release into its own directory, with
npm ciand the integrity steps in 5.15. Re-runnable: the directory is discarded on retry. - Create and seed databases and configuration. Re-runnable only by discarding and recreating them, which is safe because services have never run: nothing in them came from the user.
- Write
phase=readywith the release directory, its manifest and the runtime record. This is the commit point.
On the next start, phase=installing means "our own leftovers": the bootstrap deletes exactly the recorded names and starts again from step 2. A volume with data and no record is never treated as leftovers. That one rule removes the conflict between retrying a failed first start and refusing an old volume: the record says which case it is.
5.6 Upgrades and migrations: one recovery protocol
The upgrade command runs in the same container as the services it replaces, which has no counterpart in the baked model. One protocol covers upgrades started by the command and migrations the boot gate finds pending (inference; boot migrations and offline upgrades tested with the stub). The commit point is step=backed-up.
- Lock and check the candidate. Take
state.lock(the boot gate already holds it) and re-read the record. Acceptready, even on a volume the gate refuses, or persistedmaintenance; refuseinstallingandupgradingwith a pointer torecoverorrepair. The installed release is not started, so its boot checks are skipped;upgradeProblemchecks the image's build identity and the candidate: valid manifest, the image's Node major listed, every recorded database's schema within its range, and a version strictly greater than the installed one, from maintenance too, since the same version would repeat the failure (damaged files arerepair's job). Offline, only the candidate's probe runs (step 7), so the old release never starts on an unsupported runtime. - Stage. Install the candidate into its own release directory with the integrity steps in 5.15 and run its self-test without opening the live databases. On failure delete the directory and stop; nothing in use changed.
- Record intent. Write
phase=upgradingwith origin, versions, a new backup identifier,step=stoppingand the starting record asprev. - Stop every writer. Stop all services and scheduled jobs through PM2 and wait until their processes have exited, not just been signalled.
pm2-runtimemust run with--no-auto-exit, or it ends the container once no app is online (5.8). The upgrade command must not itself be a descendant of any service it stops: PM2'streekilloption defaults to true, so stopping an app also kills its child processes (PM2 schema.json). Inference: when the agent starts its own upgrade, it should hand off to a process outside the services' process trees (for exampledocker exec … platform upgrade, or a double fork that leaves the upgrader reparented to the init process) and only then report that the upgrade has begun. - Take one recovery point. Copy every database with the backup API or
VACUUM INTOand copy the configuration files; the previous release directory stays where it is. Write a backup manifest (transaction identifier, files, sizes, hashes, versions),fsyncevery file and the backup directory, and only then writestep=backed-up. From here a restore can be repeated as often as needed, including after a power loss during the restore. - Switch and migrate. Run the candidate's migration command with no services running; then write the candidate's directory into the record with
step=migrated. - Probe. Start the candidate's services in a probe mode that accepts no normal work (no message intake, no scheduled jobs) and run its health command. Then stop the probe processes and confirm they have exited.
- Commit and hand over. Write
phase=readywith the candidate's directory, manifest and runtime record. Online, start the services through PM2; offline, exit, and the next start runs the gate; a boot migration returns to the gate loop, which checks again, releasesstate.lockand starts the supervisor. Keep the previous release directory and the recovery point until the next successful upgrade.
Failure paths, split at the commit point:
- Before
step=backed-upno data has changed and there is no complete recovery point, so nothing is restored. An upgrade command discards the staged candidate and returns toprev: online, the previous services restart, since they ran on exactly this data; offline, the next start runs the gate onprev. A boot migration persistsphase=maintenancefromprevinstead, because the next boot would only migrate again. - From
step=backed-upon, both restore the recovery point, only frombackups/<id>and only if its manifest names this transaction (databases and configuration, deleting any database not inprev'sdbs, previous release directory in the record) and persistphase=maintenance. - Crash or container stop during the protocol: the next boot finds
phase=upgradingand runsrecover, which applies the same two rules by origin and step. An interrupted transaction is never retried automatically; the operator decides once. - A migration found pending at boot runs steps 3, 5, 6 and 8 under the gate's lock, without staging or probe workload. It never writes
readyafter a failure, because the previous release could not start on this data either. - A crash after commit (the new version passes the probe, then fails in normal work) is outside the transaction. If only a PM2 child crashes, the container stays up; the health check reports it and alerts, and a person decides whether to roll back. Nothing counts restarts automatically.
- Rollback is the same protocol in reverse, run on request: first check that the previous release directory, or a rebuild of it, matches the current image build (5.9); only then stop writers, restore the kept recovery point and commit
readyfor the previous version. Data written since the upgrade is lost, and the command should say so before it starts.
OpenClaw's documentation is the closest published counterpart (section 4.4). Home Assistant's Supervisor rolls back when an update "fails to start" (Supervisor docs). Nextcloud's pre- and post-upgrade hooks are a model for letting third-party components act around the transaction (README).
5.7 Restart policy, maintenance state and health checks
A failed migration must not be retried by an automatic restart, and section 4.4 shows that an exit code does not prevent that. Two options (inference, both tested):
- Persisted maintenance, container stays up (recommended). A failed step writes
phase=maintenancewith a reason. The gate reads it before anything else andexecs a small holder process instead of the services; the holder logs the reason and keepsowner.lock. The operator runsdocker exec … platform repairorresume, which change the record understate.lock, and thendocker restart, so the full gate runs again; there is no in-place handover from the holder to PM2. Tested with--restart unless-stopped: a container whose start script found a maintenance flag on its volume stayed running with zero restarts, reportedunhealthy, and afterdocker restartheld again without re-running the step it had recorded. - Exit with a bounded policy.
--restart on-failure:Nstops after N restarts (tested with N=2). This works only if every user runs that policy;unless-stoppedrestarts forever.
Health checks report state; they do not repair it:
- Docker's
HEALTHCHECKdefaults are a 30-second interval and timeout, three retries and a--start-periodof 0 seconds; probe failures during the start period "will not be counted towards the maximum number of retries," and exit code 0 means healthy and 1 unhealthy (Dockerfile reference). On plain Docker Engine an unhealthy status is reported, not acted on (tested). Kubernetes liveness probes are different: on failure "the kubelet kills the container" (Kubernetes probes), so do not map maintenance onto a liveness probe. - The health command reports healthy only when
phase=ready, every service is online in PM2 with a restart count that is not climbing, and the databases open. It must not depend on the package registry.
5.8 PID 1, signals and PM2 in a container
The Node project's Docker guidance says "Node.js was not designed to run as PID 1," and such a process "will not respond to SIGINT" and similar signals; the fixes are docker run --init or Tini in the image, and CMD ["node","index.js"] rather than npm so signals are not swallowed (docker-node best practices).
The Docker build guide ends its entrypoint example with exec "$@" and explains that exec makes "the final running application" become "the container's PID 1," so it receives the container's signals (Docker build best practices); with Tini as PID 1, the same exec makes the application Tini's direct child. The Dockerfile reference adds that shell-form ENTRYPOINT runs under /bin/sh -c, "which does not pass signals," so docker stop waits and then sends SIGKILL (Dockerfile reference); docker stop sends SIGTERM and the default timeout is 10 seconds for Linux containers (docker stop). PM2's page calls pm2-runtime "a drop-in replacement Node.js binary for containers" and says that by default PM2 waits 1600 ms before a final SIGKILL (kill_timeout) (PM2 Docker docs). In Runtime4Docker.js, --no-auto-exit is documented as "do not exit if all processes are errored/stopped or 0 apps launched"; without it, the runtime checks every 2 seconds and exits with code 2 after repeated checks find no app online (Runtime4Docker.js). Tested with PM2 7.0.1 in a throwaway container: after pm2 stop of the only app, the default runtime exited with code 2 about 9 seconds later; with --no-auto-exit it was still running 20 seconds later.
Putting this together (inference):
- Run
tini(or--init) as PID 1, then the entrypoint, thenexec pm2-runtime --no-auto-exiton an ecosystem file. Without the flag, stopping every service for an online upgrade ends the container, and the upgrader with it. - Make the stop budget consistent: service shutdown time (SQLite checkpoints) must fit within PM2's
kill_timeout, which must fit within Docker's stop timeout. PM2's 1.6-second default is short for services that flush databases. - Rebuild the process list from the ecosystem file at every start rather than relying on
pm2 save/resurrect; PM2's startup generator targets host init systems (PM2 startup), and in a container the runtime is the boot manager. That is my design preference, not something the PM2 pages state.
5.9 Native modules after a runtime change
The rebuild step in 5.3 runs whenever the image's build identity differs from the one recorded for the active release (inference, tested with the stub):
- Why the build identity. It is the simplest rule that is never wrong in the unsafe direction. Node version, module ABI, platform, architecture and glibc version are recorded as diagnostics, but they do not cover everything an addon links against: Node does not report a musl version, and a system library can change while
/etc/os-releasestays the same. The cost is a rebuild after every image change, which is rare under this release policy. - Rebuild into a copy. Copy the active release directory, run
npm rebuildthere for the allowlisted packages only (5.15; with package names,npm rebuildrebuilds only those packages, npm rebuild), load-test the native modules, then commit one state write that names the new directory and the new build identity together. An interrupted rebuild leaves the active directory and record untouched. Tested: interrupting the rebuild under image B and starting image A again started on a tree built entirely for A; the same test with an in-place rebuild started image A on a tree mixing modules built for A and B. - It is networked. Prebuilt binaries are downloaded or modules compiled with the image's build tools. A failure returns the retry code because no user data changed.
- Refuse what a rebuild cannot fix. If the release does not list the image's Node major, the gate refuses and points to an app upgrade or the previous image.
5.10 Volume layout and backups
One volume for everything the app owns: Jenkins ("All Jenkins data lives in there - including plugins and configuration," README), Node-RED's /data, and Nextcloud's /var/www/html with an exclude list. Split by owner: Hermes keeps the root-owned, read-only application at /opt/hermes and state in /opt/data, with on-demand installs under /opt/data/installs so they survive container recreation and image updates (Hermes docs); OpenClaw lists separate writable locations (/state, workspace, cache, /tmp) for read-only root filesystems (OpenClaw docs).
Why one home volume suits the team's design (inference): app tree, state record, databases and memory can be saved and restored as one unit, so the record's app version and schema ranges match the files beside it (with split volumes you can restore data from time T and keep the app from T+1); it matches the per-user home that non-container users already have; and Docker documents volumes as easier to back up or migrate than bind mounts (Docker volumes).
Costs to manage:
- A backup is consistent only if taken without writers. Archiving the volume while services run can capture the release, the state record and each database at different moments. Stop the container first (
docker stop, archive with a one-off container,docker start), or use the platform's backup command, which takes the recovery point of 5.6. On restore, the gate's schema check confirms that record and databases agree. - Image content over the mount point is hidden. Docker populates an empty volume from the image directory at first mount, but if the volume holds data, "the pre-existing files are obscured by the mount" (Docker volumes). Skeleton files the image puts in the home directory reach only new volumes, so the entrypoint must write anything it needs explicitly.
- Caches travel with backups. Keep npm cache and build output in a named subdirectory that can be excluded or deleted.
- Ownership. Jenkins and Node-RED both document UID problems with bind mounts; prefer a named volume and a fixed UID.
5.11 Rebuilding the runtime when Node needs a security release
Node security releases arrive on their own schedule: posts dated 2026-06-18, 2026-07-29, 2026-10-21 and 2026-11-11, and a December post (updated 2026-12-02) for a release planned on or shortly after 2026-12-09 (vulnerability blog), five in about six months.
Options, least to most new machinery (all inference, each a team decision):
- Release-time rule. Add a release checklist step: has the pinned Node line had a security release since the last image publish? If so, rebuild and republish. No new machinery, but tied to release cadence.
- Calendar rule. Rebuild and republish within a stated number of days of each Node security release, even with no Docker file change. This is an exception to the current policy.
- Staleness warning in the upgrade command. It could compare
node --versionwith a minimum from release metadata and tell the user to pull and recreate. Visible, but new behavior with its own maintenance cost. - Unattended OS or Node updates inside the container. Not recommended: it makes contents non-reproducible, and I found no source recommending it for containers.
Whether a rebuild actually picks up the patched Node depends on how the Dockerfile gets Node (inference from the Docker build guide's description of --pull and --no-cache, Docker guidance):
FROM node:24-…by tag:docker build --pullfetches the rebuilt official image, which carries the new 24.x once Docker's official image has been rebuilt; that can lag the Node release.FROM node:24-…@sha256:…by digest:--pullfetches the same digest again, so nothing changes until the digest is updated (by hand or by a Dependabot pull request).- Node installed in its own layer (from a tarball, apt or a version manager) on another base:
--pullrefreshes only the base; the Node version in that layer must be bumped, and--no-cacheis needed if the step would otherwise be reused from cache.
In every case, the release step should check node --version inside the built image against the patched version before publishing.
5.12 Telling users which image they need
What users need to know (documentation, not mechanism):
- That this image is runtime-only, that the app installs on first start (and needs network access), and the name of the volume that holds everything.
- That the app upgrades with the platform's upgrade command inside the container, and the image only carries the runtime. Home Assistant, GitLab, n8n and Nextcloud all say "pull the new image," so the README should state the inverted instruction first.
- That
docker pullonly downloads the new image; a running container keeps the old runtime until it is recreated. The runtime update is:docker pull <image>, thendocker stop <name>anddocker rm <name>, then the samedocker runcommand as before with the same-v <volume>:/home/app(ordocker compose pullfollowed bydocker compose up -d, which recreates the service). The volume name is what must not change;docker compose down -vdeletes it. - How to see the current state: image digest, Node version and runtime record, app version, phase. Support requests need one status command whose output is pasted into issues.
- When a pull and recreate is required: Node major changes, Debian release changes, or the Node security patches discussed above.
5.13 Handling users on the older baked images
Not migrating old instances aligns with Home Assistant's 2025 deprecation: announce, set a window, recommend backup and restore, and accept that people may stay put (HA blog). Practical points (inference):
- The risky case is "old volume mounted into the new image," not "old image." In the baked model the volume held data only. Mounting it into a runtime-only image would trigger a first-start install and an automatic migration on older-schema data: the situation behind the reported crash loop.
- Refuse it. A volume with data outside
.platform/and no state record is held in maintenance with a message pointing to the manual path (section 5.3, tested). This is not optional in this design: it is the same rule that lets a failed first start be retried safely (section 5.5). Jenkins'TRY_UPGRADE_IF_NO_MARKERexists because marker-less volumes happen; here the equivalent decision is "refuse" rather than "try." - Document the manual path: export with the platform's own tooling, start a fresh volume on the runtime-only image, import, and say what is and is not carried (memory, component installs, configuration).
- State a support position. Old images keep working until pulled, with no migration promise. HA's line that becoming unsupported "doesn’t mean you can’t keep running it" is a model.
- Same name, incompatible layout. With a shared name and
latest, an old container recipe puts the new layout over an old volume; the refusal above turns that into a clear message.
5.14 Tags without adding mechanisms
With latest only, these compensations need no new tags (inference): print the image identity at every start and in the status command; record each published digest in release notes so a user can pin image@sha256:... (Kubernetes: Images); and keep the publish rule narrow and written down, as pingtxt does by moving :latest only on release tags (PR 44). A recorded digest is restorable only while the registry still serves that manifest; once latest moves, the old manifest is untagged, and I did not verify how long the registry used keeps untagged manifests. If immutable tags are ever wanted, the Node image's major/minor/patch/OS-suffix scheme is a worked example (Docker Hub: node).
5.15 Install scripts and integrity
Two promises are easy to overstate here (inference unless cited):
- Order the install steps so checks come before code runs.
npm ciruns dependency install scripts unless--ignore-scriptsis set; npm 11 adds anallowScriptspolicy inpackage.jsonand astrict-allow-scriptssetting that turns unreviewed install scripts from a warning into an error (npm ci). One workable order:npm ci --ignore-scripts, thennpm audit signatures, then run install scripts only for an allowlist (npm rebuild <package>), then the release's self-test. Runningnpm audit signaturesafter a plainnpm civerifies the packages but cannot undo what their scripts already did. - A lockfile hash is not an integrity check. It shows which dependency set was intended. It does not detect changed files in the app tree or
node_modules, and a process running as the same UID as the app can rewrite both the files and the state record. A real start-time check needs a reference the agent cannot write, for example a signed per-release manifest of file hashes verified with a key in the image, or a file owner the agent cannot write to (section 6.4). Without one, record the hash for diagnostics and do not call it verification.
6. AI Agent Platforms Specifically
AI agent platforms stress this design in ways web applications do not.
6.1 What the open-source agent projects actually do
I read the Docker documentation of two open-source agent projects:
- Hermes Agent says the image "is stateless and can be upgraded by pulling a new version without losing any configuration." The application is in
/opt/hermes, root-owned and read-only to the runtime user. State (.env,config.yaml,SOUL.md, sessions, memories, skills, cron, hooks, logs,state.db) lives in the/opt/datavolume, described as "the single source of truth for all Hermes state." In the page's words, "hermes update refuses image-owned code changes; replace the image to update the application." Agent self-improvement is limited to skills, memory, plugins and config under/opt/data. On each boot, an init stage fixes ownership, seeds missing config, runs config migrations (with backups) and syncs bundled skills (Hermes Docker docs). - OpenClaw says pulling a new image is the update path and that
openclaw updateinside the official image "does not replace its code"; it tells you to pull and recreate instead. State lives in a volume. On boot, the entrypoint migrates state in place with the verified-backup behavior described in section 4.4 (OpenClaw Docker docs).
Both are baked-image designs with a carefully separated state volume and with migrations that run at start under backup. Neither supports a runtime-only mode in its official image.
6.2 Community packaging shows why the line is drawn
Community images of OpenClaw explore the other side; these are third-party packagings, not upstream recommendations:
- A Coolify-oriented image blocks
npm install -g openclawandopenclaw updateinside the container because a global npm install "lands on/data/npm-global, which stays on the volume" and "would hide the binary from later image tags." It advises pinning versions and warns that trackinglatestwith automatic redeploys "follows breaking releases as well" (coollabsio README). - A desktop-style image supports in-container
openclaw updatebut installs to a path outside the home volume, deliberately, to prevent "a stale user-installedopenclawfrom shadowing the image-baked version"; an in-place update reverts when the container is recreated (Neoplanetz image). - Another image has
OPENCLAW_AUTO_UPDATE(default false) that runsopenclaw updateevery time the container starts (fourplayers image): the update-on-every-start end of the spectrum.
The first two describe one problem from opposite sides: an updated app in the persistent volume outlives and can shadow whatever a newer image brings. A pure runtime-only image avoids shadowing because it has no app to shadow; the risk returns if the image ever carries an app copy "for convenience."
6.3 Self-upgrade lost on recreate
The opposite failure is documented in small projects. A pull request to Agent Zero describes self-updates vanishing silently after docker compose down/up, image pull and recreate, Watchtower or a host reboot, and proposes a breadcrumb file on the persistent volume that initialize.sh uses to re-apply the update. It was not merged; a bot closed it for inactivity on 2026-09-10 (PR 1454). The merged pingtxt change ties a volume-held update to the image (section 5.2). The team's design already puts the app on the volume; what it still needs is the state record and the rule that a changed runtime triggers a rebuild or a refusal (sections 5.2 and 5.9).
6.4 Agent-specific considerations
- The home directory is the product. Memory, skills, history and credentials are the accumulated value; the application is replaceable. Hermes calls
/opt/datathe single source of truth; OpenClaw says back up state before upgrading and not to delete state or lock files to get around errors. A single home volume makes the same statement structurally. Protect it first: a recovery point before every upgrade, a documented restore, and no automatic step that can destroy it. (docker compose down -vdeletes the volume, as both community OpenClaw READMEs warn.) - The upgrader is the thing being upgraded. An upgrade the agent starts itself must run outside the agent's own process tree, or step 4 of 5.6 kills it.
- Writable code is a trust boundary. Hermes makes its application tree root-owned and read-only and confines self-improvement to skills, memory, plugins and config. A runtime-only model needs the tree writable by whoever runs the upgrade. Inference: if the agent and the upgrader run as the same user, anything that can make the agent run commands can change its own code and state record, and the change survives container recreation. The effective fix is a different identity: the upgrader owns the release directories, the agent's services can read but not write them. A start-time integrity check helps only with a reference the agent cannot write (5.15). In a baked image, recreation resets the code; here it does not.
- Agents are stateful during upgrades. Open sessions, scheduled jobs and in-flight tool calls exist. Inference: connections such as WebSocket sessions drop when services stop or the container is recreated. Drain or checkpoint work before step 4 of 5.6 and make scheduled jobs tolerate a missed window, in line with twelve-factor's guidance on robustness against sudden death (Disposability).
- Several components share one home. With a component installer, the state record (or a manifest next to it) should list component versions and their schema ranges too, and the recovery point should cover their databases.
- Single owner per home. Two containers on one agent home can double-act on messages and corrupt SQLite;
owner.lockprevents the second from starting (5.4). - Ownership decisions come from the volume. Whether an agent takes over, resumes or resets a prior session depends on state, so it must be read from state, not from defaults in whichever image starts.
7. Checklist
An ordered checklist for the runtime-only model; section references hold the detail. Items marked "optional" are new mechanisms to weigh against their cost.
Image
- Node pinned to a major; Debian or Alpine release stated (5.1).
- Bootstrap in the image, never loading the app tree;
tini,flock, CA certificates; fixed non-root UID. - Build identity written in and printed at start; exec-form
ENTRYPOINT;HEALTHCHECKstart period covering first install.
State and boot gate
- Control files in
.platform/; record written atomically; schema read from the databases (5.2). -
owner.lockfor the container's lifetime;state.lockfailure stops the gate; released beforeexec(5.4). - Records validated per phase; versions under a stated contract;
dbsrecorded at commit; missing, unknown, unreadable or out-of-range data refused beforemigrateorstart(5.3). - Offline and online commands take both locks and skip the gate.
First start
- Fixed layout: records hold plain names; resolved paths re-checked before every delete or restore (5.2).
- Install identifier and owned names recorded first; only those leftovers discarded; retry only for steps that changed no user data (5.5).
Upgrade and migration
- Precondition checks the image build identity and the candidate:
readyormaintenanceaccepted, open transactions refused, strictly newer (5.6). - Candidate staged; upgrader outside the services' process tree; all writers stopped; recovery point
fsync'd beforestep=backed-up. - Migration, probe without normal work, commit, start.
- Before the commit point nothing is restored (an upgrade returns to
prev, a boot migration persists maintenance); after it, restore, then maintenance. - Rollback checks the previous release against the current image and states what data it discards.
Runtime and supervision
- Init as PID 1;
pm2-runtime --no-auto-exit; stop time withinkill_timeout, within Docker's stop timeout (5.8). - Maintenance holds the container up;
repair/resumeunder the lock, thendocker restart(5.7). - Health command reads phase, PM2 status, restart counts and database access; a person decides on rollback.
- Native modules rebuilt into a copy on every build-identity change; allowlisted scripts only (5.9).
Volume
- One named home volume with a documented layout; caches in a deletable subdirectory (5.10).
- Backups with the container stopped or by the platform's command; restore tested on a fresh volume.
- Nothing the platform needs exists only in the image's home directory.
Release and security
- Per release: has the pinned Node line had a security release since the last publish? If so, rebuild so the new Node is picked up and check
node --versionin the image (5.11). - Published digests in release notes; registry retention of untagged manifests checked (5.14).
-
npm ci --ignore-scripts,npm audit signatures, then allowlisted install scripts (5.15). - Status command prints build identity, Node version, app version and phase.
- Optional: stale-Node warning in the upgrade command; agent services unable to write the app tree (6.4).
Users
- README first: runtime-only image, first start needs network, the app upgrades inside the container, a pull takes effect only after recreating with the same volume.
- Manual path and support position for older baked images; their volumes are refused, not migrated (5.13).
8. Comparison: Baked vs Runtime-Only (and the Hybrid)
Baked image
- Upgrade unit: the image.
- Reproducibility: strong (digest).
- Rollback: older image plus state restore.
- Registry needed for upgrades: yes, an image pull.
- Container runtime access needed to upgrade: yes, by the user or an orchestrator.
- First start: fast and offline-capable.
- Same upgrade path as non-container users: no.
- Security patching of OS and Node: rebuild the image.
- Code integrity after compromise: reset by recreate.
- Native module risk: fixed at build.
- Typical failure: data newer than code.
- Fits: orchestrated infrastructure and teams that release immutable artifacts.
- Observed in: Hermes, OpenClaw (official docs), GitLab, n8n, Ghost, Home Assistant Container.
Runtime-only, app in the volume
- Upgrade unit: the app upgrade command in the container; the image only for the runtime.
- Reproducibility: image digest plus state record plus lockfile; the platform must record them.
- Rollback: a platform feature (recovery point plus previous release).
- Registry needed for upgrades: the package registry, reachable from the container; an image pull only for the runtime.
- Container runtime access needed to upgrade: no.
- First start: slow; needs network; can fail on user machines.
- Same upgrade path as non-container users: yes.
- Security patching of OS and Node: rebuild the image and recreate containers; app upgrades do not help.
- Code integrity after compromise: persists in the volume.
- Native module risk: a runtime change can break installed modules until rebuilt.
- Typical failure: image, app and data skew; interrupted installs and migrations.
- Fits: self-managed platforms with their own upgrader and installer.
- Observed in: WordPress (after first start), Jenkins plugins, Node-RED nodes.
Hybrid (for example Nextcloud, Discourse)
- Upgrade unit: both, with a coupling rule.
- Rollback: image plus state restore.
- Registry needed for upgrades: both.
- Security patching: rebuild the image; a web updater for the app.
- Code integrity after compromise: persists in the volume.
- Typical failure: an old image blocks the in-app upgrade.
- Fits: applications with their own updater and heavy OS-level dependencies.
9. Gaps, Unverified Points and Open Questions
Not verified (flagged in the text or left out):
- GitLab: upgrade-path and downgrade rules; the pages I opened were indexes pointing elsewhere.
- n8n, Ghost, code-server: where community nodes land relative to the volume; Ghost's content volume path; code-server's upgrade model. The pages were silent.
- Node-RED: whether a Node major change in a new image breaks nodes in
/data; the documentation is silent. - Discourse: the exact rule that blocks the web upgrader on an old image; I verified only a maintenance-guide comment.
- Home Assistant Supervisor: update mechanics.
flockon network filesystems and volume drivers other than a local named volume, whether the platform's SQLite binding compiles native code, and registry retention of untagged manifests: not checked.- Tested behavior covers one Docker Engine (29.2.1) and one PM2 (7.0.1). The section 5 samples ran with a stub bootstrap; they show control flow and lock behavior, not a production implementation.
- Node security pages also listed CVE-level detail that I did not cross-check; I rely only on dates, affected lines, the highest severity rating (HIGH) and the distribution index showing v24.22.3 and v24.23.0.
Open design questions for the team (decisions, not recommendations):
- Is a Node security release a reason to republish the image when the Docker files are unchanged?
- Should the upgrade command warn when the container's Node is stale?
- Should agent services and the upgrader run as different identities?
- Does
latestneed a companion immutable tag once the first Node major change is due?
References
Methodology and norms
- The Twelve-Factor App: Build, release, run
- The Twelve-Factor App: Dependencies
- The Twelve-Factor App: Disposability
- Kubernetes: Images
- Kubernetes: Liveness, readiness and startup probes
- Semantic Versioning 2.0.0
Docker and container mechanics
- Docker: Building best practices
- Docker: Dockerfile reference
- Docker: Volumes
- Docker: Start containers automatically (restart policies)
- Moby v26.1.2: restartmanager.go
- Docker: docker container stop
- Docker: Build attestations
- Docker Official Images README (docker-library)
- Docker Hub: node official image
- docker-node: Best practices
- PM2: Docker integration (pm2-runtime)
- PM2: Runtime4Docker.js (pm2-runtime source)
- PM2: schema.json (process options, including treekill)
- PM2: Startup script generator
- Development Containers: devcontainer.json reference
Node.js and npm
- Node.js: Previous releases and release status
- Node.js release schedule data (nodejs/Release)
- Node.js distribution index (versions and ABI
modulesfield) - Node.js: ABI stability guide
- Node.js: Node-API
- Node.js: C++ addons
- Node.js: Vulnerability blog index
- Node.js: November 2026 security releases
- Node.js: December 2026 security releases (pre-announcement)
- npm: npm ci
- npm: npm rebuild
- npm: config
- npm: audit (signatures)
- npm: Generating provenance statements
- SQLite: Online Backup API
Products and projects
- Nextcloud docker: README
- Nextcloud docker: docker-entrypoint.sh
- Nextcloud admin manual: Updating
- WordPress official image (Docker Hub)
- docker-library/wordpress: docker-entrypoint.sh
- Jenkins Docker image README
- Node-RED: Running under Docker
- n8n: Docker installation
- n8n: Install community nodes (GUI)
- GitLab: Upgrade GitLab running in Docker
- GitLab: Troubleshooting and rolling back
- Discourse: Cloud install guide
- Discourse Meta: Manually update Discourse and Docker image to latest
- Home Assistant: Installation
- Home Assistant: Container install
- Home Assistant: Deprecating Core and Supervised installation methods
- Home Assistant contributor docs: Supervisor
- Ghost: Docker install
- code-server: Install
AI agent projects
- Hermes Agent: Docker user guide
- OpenClaw: Docker install
- coollabsio/openclaw (community image)
- Neoplanetz/openclaw-desktop-docker (community image)
- fourplayers/openclaw (community image, Docker Hub)
- agent0ai/agent-zero PR 1454: self-update persistence
- federico-it/pingtxt PR 44: agent self-update through a data volume
