Deploying Karyo
One script, one Compose file, three required containers and optional managed Keycloak, one host. This document is both the runbook - every command an operator types to install and maintain an installation - and a description of what the deploy script does and why.
Derived from scripts/deploy-server.sh, infrastructure/docker/docker-compose.prod.yml,
infrastructure/docker/docker-compose.maintenance.yml, scripts/.env.prod.example,
scripts/render_compose_env.py, scripts/validate_public_origin.py,
scripts/validate_credential.py and scripts/migrate_keycloak_realm.py.
scripts/deploy-server.sh is the whole installation mechanism. There is no
installer, no configuration management and no orchestrator: Compose on one host is the supported
deployment (ADR 0022).
Set KARYO_IDENTITY_PROVIDER_TYPE=KEYCLOAK for Karyo-managed identity or EXTERNAL for a
standards-only OIDC provider. External mode leaves embedded Keycloak stopped and exposes no
provider lifecycle controls. Existing installations must complete the
identity principal upgrade before traffic reaches the new runtime.
Messages printed by the deploy script, the environment templates and the realm migration tool that point at a deployment guide by file name mean this document.
What has to be on the host
Choose one of two modes:
- Image-only installation (
--image-only) is the normal path for a released version. It pulls and starts the supplied application and nginx images without building anything. It requires only the container runtime with Compose and Python 3 as toolchains. It never searches for Java,javac, Node or npm. Git is not required: copy or unpack the release's repository files, includingscripts/andinfrastructure/, into the installation directory. - Build from source (the default) builds the backend, both front ends and both images.
Use it for development or a deliberately reviewed source build. It additionally needs the
JDK, Node and Git described below.
--quickretains these source-mode prerequisites.
Both modes run on a Linux host with Bash, standard Unix utilities and a responsive container
runtime. The runtime must support the production Compose file's journald driver, as described below.
Image-only URL validation, port checks and HTTP probes use Python, not host Node, ss or curl.
The build-from-source toolchains are:
- Java 21 or newer, as a JDK.
javacmust be available; a JRE fails. The script honoursJAVA_HOMEfirst (deploy-server.sh, thejavaccheck in Stage 1). - Node.js 24.x, the single supported line, declared once in
.nvmrcand enforced by both operator scripts throughscripts/lib/node-runtime.sh. A source deploy needs it for its environment validation (Stage 5 and--validate-env), which uses Node's WHATWG URL parser to validate the public origin. The front ends are built inside the nginx image, not on the host. - Git, for obtaining source and labelling source-built images.
Both modes also require:
- Python 3, for environment validation and rendering.
- Docker with the Compose plugin, or Podman with
podman-compose. - systemd-journald, reachable by the container runtime. The production Compose file sends every
service's log to the
journaldlogging driver, so a host without it cannot start the stack. Stage 1 looks for the journal socket (/run/systemd/journal/socket) before anything is stopped. Retention is set separately; see Operating an installation. cloudflared, only if the stack is exposed through a Cloudflare Tunnel (see Public access). Its absence is a warning, not a failure, and the warning does not say the stack is local-only: the tunnel may run on another host (deploy-server.sh, the cloudflared check in Stage 1).
Stage 1 checks the selected mode's prerequisites and reports missing tools before stopping containers.
--image-only --validate-env FILE needs only Python and standard shell utilities; it neither
checks nor starts the container runtime. Source-mode --validate-env still requires Node.
One Node line, declared once
.nvmrc at the repository root declares the one supported Node.js major (24). nvm reads it
directly, CI's setup-node consumes it through node-version-file: .nvmrc, and both operator
scripts source scripts/lib/node-runtime.sh, which accepts exactly that major and fails closed on
a missing node, an unreadable version and a missing or malformed declaration. The deploy
preflight runs it in Stage 1 and on the --validate-env path in source mode only; scripts/run-e2e.sh runs it before
resolving the E2E target. npm only warns on an engine mismatch, so the package manifests mirror
the line as engines.node: ^24.0.0 with engine-strict=true (.npmrc), and the nginx image's
builder stages use node:24-alpine (infrastructure/docker/Dockerfile.nginx, builder, mobile-builder stages);
tests/e2e/fixtures/node-runtime-preflight.test.ts keeps every mirror equal to .nvmrc.
The Java check
In source mode, Stage 1 requires a Java major of 21 or newer through scripts/lib/java-runtime.sh
(deploy-server.sh, the karyo_require_java call in Stage 1). The library reads the quoted
version from java -version, wherever the line sits in the output, and derives the major from all
the shapes a JDK prints: "21.0.10", a .0 GA release such as "17" that has no dot after the
major, an early-access "25-ea", and the legacy "1.8.0_292", whose major is 8. A release below
21 stops the deploy with Java 21+ required, found Java <major>. A missing java and a version
line that cannot be read also stop it, and the script never reports a version it did not read.
tests/e2e/fixtures/java-runtime-preflight.test.ts runs the library against each of those shapes.
Quick start
Released images (recommended)
Obtain the repository files for the same release as the images and unpack them on the host. Keep this installation directory for its configuration and future upgrades.
Authenticate the container runtime to the registry with read access, following obtaining the images.
Create
scripts/.env.prodfrom the template at mode 0600 and replace every placeholder.Export the selected project and the two complete image references, then deploy:
export COMPOSE_PROJECT_NAME=karyo-prod export KARYO_APP_IMAGE=ghcr.io/voyagerforge-dev/karyo-app:2.0.0-rc.1 export KARYO_NGINX_IMAGE=ghcr.io/voyagerforge-dev/karyo-nginx:2.0.0-rc.1 ./scripts/deploy-server.sh --image-only --validate-env scripts/.env.prod ./scripts/deploy-server.sh --image-only
Use an actual published version, not the example if it has not been released. Both image variables
are mandatory in this mode. To pin an installation exactly, replace each reference with the
ghcr.io/voyagerforge-dev/<image>@sha256:<64 hex digits> reference from published.txt.
The script passes it unchanged to pull and Compose, never substitutes a tag, and always starts
services with --no-build. It pulls the images before stopping the selected stack.
Both front ends already live inside the nginx image; no front-end source or host bundle is consumed.
For a configuration-only restart, keep the same image variables and run --image-only again.
It pulls the images each time, so they must stay reachable from the host. --image-only cannot be
combined with --quick, and source-mode --quick is no substitute on an image-only host.
Build from source
# 1. Clone the repository
git clone https://github.com/voyagerforge-dev/karyo-wms.git
cd karyo-wms
# 2. Create the environment file from its template, private from the start
install -m 0600 scripts/.env.prod.example scripts/.env.prod
# 3. Edit scripts/.env.prod: replace every CHANGE_ME value, including all five
# KARYO_SHIP_FROM_* fields, and set the deployment URLs.
# KARYO_PUBLIC_ORIGIN is the exact browser origin, for example https://wms.example.com
# 4. Check the file without building or starting anything
./scripts/deploy-server.sh --validate-env scripts/.env.prod
# 5. Build and deploy
./scripts/deploy-server.sh
# 6. Open the application
# Local: http://localhost (or http://localhost:<NGINX_HTTP_PORT>)
# Public: https://<your-domain> (see Public access)
The production realm imports no human users and no passwords. On a fresh managed-Keycloak
installation Karyo creates System, a setup account with a one-time password, and System creates
the first Administrator and Manager from the console; with an external provider, the first
administrator is enrolled by the reviewed identity manifest. See
Provisioning the first administrator.
The development realm, infrastructure/keycloak/karyo-realm.json, carries fixed demo users and
is for local development only.
Use an isolated target and synthetic data first, and verify receiving, putaway, picking and shipping before any real stock moves. The implementer guide walks through that.
The environment file
The deploy script reads one file, scripts/.env.prod. It is created mode 0600 from
scripts/.env.prod.example if absent, and the mode is re-enforced on every run
(enforce_private_mode and Stage 5 of deploy-server.sh). Edit only this file; every deploy
regenerates the per-service files derived from it (see
Rendering least-privilege container environments).
scripts/.env.prod.cloud-example is the same shape, with resource limits sized for a 24 GB,
four-core ARM64 host.
Required variables
| Variable | Purpose |
|---|---|
DB_USERNAME |
PostgreSQL role used by Karyo; must equal POSTGRES_USER |
DB_PASSWORD |
PostgreSQL role password, at least 16 characters; must equal POSTGRES_PASSWORD |
POSTGRES_USER |
The PostgreSQL role the container provisions; the same role |
POSTGRES_PASSWORD |
The password used when provisioning that role; the same password |
KC_DB_USERNAME |
Managed Keycloak only: database role; must equal DB_USERNAME |
KC_DB_PASSWORD |
Managed Keycloak only: database password; must equal DB_PASSWORD |
KC_BOOTSTRAP_ADMIN_USERNAME |
Managed Keycloak only: externally chosen bootstrap-administrator username. Required only for a fresh database or --reset-db; remove it once the bootstrap account is retired |
KC_BOOTSTRAP_ADMIN_PASSWORD |
Managed Keycloak only: externally generated bootstrap password, at least 16 characters, not predictable or username-derived. Same lifetime as the username |
KEYCLOAK_ADMIN_CLIENT_SECRET |
Managed Keycloak only: secret for the permanent karyo-admin service account, at least 32 characters and distinct from every other secret |
OIDC_SECRET |
Managed Keycloak only: secret substituted into the karyo-backend confidential client at realm import, at least 32 characters and distinct |
KARYO_PUBLIC_ORIGIN |
Exact browser-canonical origin: lowercase ASCII or punycode host, no default port, path, trailing slash, credentials or wildcard (for example https://wms.example.com) |
KARYO_DOMAIN |
The hostname portion of KARYO_PUBLIC_ORIGIN |
KARYO_MCP_RESOURCE_URI |
The agent endpoint audience: KARYO_PUBLIC_ORIGIN followed by /mcp. The preflight refuses any other value, because a realm import writes it once |
KC_HOSTNAME |
Managed Keycloak only: public URL including the /auth path (for example https://wms.example.com/auth) |
Ship-from address on bills of lading
Set all five fields in scripts/.env.prod before a production deploy. They configure the
installation-wide Ship From block, not the customer's Ship To address.
| Variable | Property | Purpose |
|---|---|---|
KARYO_SHIP_FROM_NAME |
karyo.shipping.ship-from.name |
Actual shipper or warehouse name |
KARYO_SHIP_FROM_STREET |
karyo.shipping.ship-from.street |
Street address |
KARYO_SHIP_FROM_CITY |
karyo.shipping.ship-from.city |
City |
KARYO_SHIP_FROM_ZIP_CODE |
karyo.shipping.ship-from.zip-code |
Postal code, including internal spaces when needed |
KARYO_SHIP_FROM_COUNTRY |
karyo.shipping.ship-from.country |
Country code, for example US or GB |
Use unquoted literal values. Internal spaces and apostrophes within a name are accepted; leading
or trailing whitespace, control characters, enclosing quotes, double quotes, #, $ and
backslashes are refused. For example, write KARYO_SHIP_FROM_NAME=Northstar Warehouse, not a
quoted shell assignment. The deploy script passes the values to the application environment.
The preflight refuses missing, empty or CHANGE_ME fields. It also refuses the demo name,
street, city or postal code, even if other fields have changed. US is a valid real country,
not a demo identifier. Only an explicit KARYO_DEMO=on or KARYO_DEMO=true in the file allows
omitted fields or the demo address; never enable it to bypass production validation.
The application retains non-empty demo defaults so an unconfigured local stack can boot. It logs a startup warning naming any retained demo fields. If you start the application without the deploy script, that warning is not a deployment refusal. Correct the settings and restart. These catalogue entries are environment-only and require a restart; they cannot be changed through runtime settings. Every goods owner and Facility shares the same address. Per-tenant ship-from overrides remain a follow-up.
Before commissioning shipping, dispatch one synthetic order through the manual path and open its bill of lading. Check every Ship From field against the physical shipper address.
Identity trust
Identity trust is deployment-controlled:
| Variable | Purpose |
|---|---|
COMPOSE_PROFILES |
managed-identity starts embedded Keycloak; leave it unset in external mode |
KARYO_IDENTITY_PROVIDER_TYPE |
KEYCLOAK enables the managed administration/audit adapter; EXTERNAL is authentication-only |
KARYO_IDENTITY_PROVIDER_KEY |
Stable key of the provider row created by the reviewed manifest |
OIDC_URL / OIDC_ISSUER |
Validation endpoint and the exact issuer tokens must carry; aliases belong in reviewed identity data, not string normalization |
OIDC_API_AUDIENCE / OIDC_SIGNATURE_ALGORITHM |
Required API audience and algorithm (karyo-api, RS256 in the shipped managed profile) |
KARYO_OIDC_*_CLAIM |
Claim paths for display profile, Business Unit, principal kind and tenant code |
KARYO_OIDC_BROWSER_CLIENT_ID / KARYO_OIDC_BROWSER_SCOPES |
Public authorization-code-plus-PKCE client and scopes returned by /api/v1/auth/config |
KARYO_OIDC_ADDITIONAL_ISSUER_TENANTS |
Optional exact issuer=named-tenant pairs for a reviewed overlap; each named Quarkus tenant must separately enforce its own trust profile |
The exact issuer/subject binding and local principal still decide identity after token validation; none of these settings enables inference or first-login enrollment. No setting reads provider roles, groups or scopes: authority is the grants stored in Karyo (ADR 0048). See identity for an integrating system.
The origin must match the browser's URL.origin serialisation, including the omission of the
default port - 80 for HTTP, 443 for HTTPS. The production realm permits exactly six callbacks beneath it,
and none may be relaxed into a wildcard:
/ desktop callback
/silent-check-sso.html desktop silent single sign-on bridge
/silent-callback desktop OIDC silent-renew callback
/m/ floor callback
/m/silent-check-sso.html floor silent single sign-on bridge
/m/silent-callback floor OIDC silent-renew callback
What the validator refuses
validate_env (in deploy-server.sh) is the substantial part of the script, and the only
thing between an operator and a stack that starts with the wrong credentials:
- Syntax. Every non-comment line must be
NAME=valuewith noexportand no whitespace around the name or the equals sign, and the offending line number is named (validate_env, theNAME=valueline loop). - Exactly once. A required variable assigned twice is refused, because the last assignment
silently wins (
validate_env, themust be assigned exactly oncecheck). - Literal values. Required credential and URL values containing whitespace, a quote, a
#, a$or a backslash are refused. Ship-from fields use the address rules above, allowing internal spaces without introducing shell interpolation (validate_env, themust use one unquoted literal valuecheck). - Placeholders.
CHANGE_ME,karyo.example.comand the literaldev-backend-secretare each named individually (validate_env, the same loop). - Consistency.
DB_USERNAMEandPOSTGRES_USERmust name the same role and password. In managed mode,KC_DB_USERNAMEandKC_DB_PASSWORDmust also match it. External mode does not require or inspect Keycloak database or client credentials. - Strength, through
scripts/validate_credential.py: 16 characters for the database and bootstrap passwords, 32 forKEYCLOAK_ADMIN_CLIENT_SECRET,OIDC_SECRETand, when set,KARYO_LOCI_CLIENT_SECRET, and rejection of dictionary, predictable, repeated and username-derived values. Existing role passwords are not grandfathered (validate_envandcredential_meets_policy). - Distinctness. The admin client secret must differ from the bootstrap password and the OIDC
secret; the OIDC secret must differ from the bootstrap password.
KARYO_LOCI_CLIENT_SECRET, when set, must differ from all three and fromDB_PASSWORD(validate_env, themust be distinctchecks). - Loci's machine credential. All four of
KARYO_LOCI_TOKEN_URL,KARYO_LOCI_CLIENT_ID,KARYO_LOCI_CLIENT_SECRETandKARYO_LOCI_TOKEN_SCOPEunset is valid: Karyo then sends no credential, which only an unauthenticated Loci on a private network accepts. A token URL requires a non-empty client id and a secret that meets the 32-character policy, and must behttp://orhttps://with a host, an optional port and a path. A client id, secret or scope without a token URL is refused as inert (validate_env, theKARYO_LOCI_*block, andloci_token_url_is_http). - URLs, through
scripts/validate_public_origin.py, which shells out to Node's WHATWGURLparser so that the accepted origin is the one a browser would compute (validate_public_origin.py,WHATWG_ORIGIN_PROGRAM, normalize_public_origin). Its exit code 3 is distinct from 2 so that a missing Node is reported as a missing tool rather than filed under the operator's configuration (validate_public_origin.py,ToolchainError, main, and theurl_statusbranch ofvalidate_env). Image-only mode instead selects--python-only: a strict canonical ASCII subset with DNS, punycode, IPv4 and compressed IPv6 hosts. It refuses alternate IPv4 spellings, Unicode hosts, escaped hosts, paths and default or zero ports. Supply the already canonical browser origin; the validator never repairs it and never looks for Node. - The ship-from address. All five
KARYO_SHIP_FROM_*fields are required outside an explicitly enabled demo. Retained demo identifiers, empty fields and ambiguous assignments stop deployment before containers start. - The maintenance port.
KARYO_KEYCLOAK_MAINTENANCE_PORTmust be an integer from 1 through 65535 and may be assigned at most once (validate_env, the same variable's check).
The whole validator is reachable on its own with --validate-env FILE, which exits before
anything is built or started (deploy-server.sh, the VALIDATE_ENV_FILE branch before Stage 1).
Success validates the values in the file. It proves nothing about the target host, or about the
password a persisted database role actually holds.
KEYCLOAK_URL is a legacy nginx substitution value and defaults to /auth for validation only.
Current browser authority, client id and scopes come from /api/v1/auth/config, not this injected
value. Keep /auth for the managed same-origin profile; external-provider authority comes from the
OIDC settings above.
Optional variables
| Variable | Default | Purpose |
|---|---|---|
DB_URL |
jdbc:postgresql://postgresql:5432/karyo |
JDBC connection URL |
OIDC_URL |
http://keycloak:8080/auth/realms/karyo |
OIDC validation/discovery endpoint; external mode must point it at that provider |
KEYCLOAK_ADMIN_URL |
http://keycloak:8080/auth |
Managed mode only: Keycloak Admin API used for optional provider administration |
KEYCLOAK_URL |
/auth |
Legacy nginx substitution and managed same-origin base; browser authority comes from /api/v1/auth/config |
NGINX_HTTP_PORT |
80 |
Host port nginx binds. Set a high port, for example 8088, for rootless Podman that cannot bind 80 |
KARYO_KEYCLOAK_MAINTENANCE_PORT |
8181 |
Loopback-only Keycloak port, published only while docker-compose.maintenance.yml is layered on for a maintenance window |
KARYO_PROVISIONING_FINGERPRINT_KEY |
unset | Server-held request-binding key. Set an independent stable value of at least 32 UTF-8 bytes before using POST /api/v1/principals; keep it across unrelated credential rotations so retries remain verifiable |
KARYO_LOCI_TOKEN_URL |
unset | Token endpoint of Loci's OIDC provider. Unset, Karyo sends no credential, which only an unauthenticated Loci on a private network accepts |
KARYO_LOCI_CLIENT_ID |
unset | OAuth client id for that token. Required when the token URL is set; inert without it |
KARYO_LOCI_CLIENT_SECRET |
unset | client_secret_post secret, at least 32 characters and distinct from the other secrets. For Authentik this is base64(<service account>:<app password>) |
KARYO_LOCI_TOKEN_SCOPE |
unset | Optional scope, profile for Authentik so the token carries groups. Inert without a token URL |
KARYO_PROFILE |
core |
The installation's profile at install: core or extended, any case, at most once (ADR 0052). A Company administrator changes it later on Admin > Capabilities, which wins over this value |
KARYO_SETUP_REOPEN |
unset | Managed Keycloak only. A new marker reopens a disabled System once, with a fresh 14-day expiry; requires KARYO_SETUP_PASSWORD. Remove both once done |
KARYO_SETUP_PASSWORD |
generated | Managed Keycloak only. System's one-time password; the deploy script generates it on a fresh installation unless set. Set it only to reopen System |
Application settings that are also environment variables - the scheduled jobs, the demo engine, the over-receipt stop, the stock reaper - are described in Operating an installation.
Resource limits
Resource limits are optional. Leave them commented out unless the host needs tuning, and tune only after observing the complete stack under representative load.
| Variable | Default | Example for a larger host | Controls |
|---|---|---|---|
APP_MEM_LIMIT |
1536m |
4g |
karyo-app container memory (docker-compose.prod.yml, services.karyo-app.mem_limit) |
JAVA_OPTS |
-Xms128m -Xmx1024m ... |
-Xms256m -Xmx3g ... |
JVM flags inside the application container (infrastructure/docker/Dockerfile.service, ENV JAVA_OPTS) |
GRADLE_OPTS |
-Xmx512m -XX:MaxMetaspaceSize=256m |
-Xmx2g -XX:MaxMetaspaceSize=512m |
Gradle heap for the Stage 2 build (deploy-server.sh) |
APP_MEM_LIMIT reaches Compose through the shell rather than an env_file, so the script reads
it from scripts/.env.prod and exports it before starting containers
(deploy-server.sh, Stage 5).
GRADLE_OPTS is read from the invoking shell at Stage 2, before the environment file is read
at Stage 5 (deploy-server.sh, Stages 2 and 5). Export it before running the script. Known
defect. Both environment templates and the script's own comment present GRADLE_OPTS as an
environment-file setting (scripts/.env.prod.example, GRADLE_OPTS, scripts/.env.prod.cloud-example, GRADLE_OPTS),
and a value set only there never reaches the build.
Rendering least-privilege container environments
scripts/render_compose_env.py splits the one source file into four - .env.prod.postgresql,
.env.prod.keycloak, .env.prod.app and .env.prod.nginx - each created with O_EXCL at mode
0600 before any secret is written, and moved into place atomically
(render_compose_env.py, write_private). The production Compose file mounts each as that service's
env_file (docker-compose.prod.yml, services.postgresql.env_file, services.keycloak.env_file, services.karyo-app.env_file, services.nginx.env_file), so database and bootstrap credentials never
enter the nginx or application containers.
The split is the whole containment story, so it is worth stating exactly
(render_compose_env.py, service_assignments):
| File | Contents |
|---|---|
.postgresql |
everything beginning POSTGRES_ |
.keycloak |
everything beginning KC_, plus KARYO_PUBLIC_ORIGIN, KEYCLOAK_ADMIN_CLIENT_SECRET and OIDC_SECRET |
.app |
everything that is not KC_, not POSTGRES_, and not KARYO_PUBLIC_ORIGIN or KEYCLOAK_URL |
.nginx |
KEYCLOAK_URL and nothing else |
All four are gitignored by name (.gitignore, the four scripts/.env.prod.<service> entries)
and excluded from every image build context (.dockerignore, scripts/.env.prod*).
Provisioning the first administrator
Creating an account at an OIDC provider is not enough. Karyo never enrolls a principal at first login, so an unbound administrator token is denied whatever roles or claims it carries.
Managed Keycloak: System, the setup account
On a fresh managed installation the deploy script generates a one-time password, writes it to
scripts/.karyo-setup-password (mode 0600) and passes it to the application only. A rerun
passes the file's password again until you delete the file. Within a
minute of start, Karyo creates System - the provider account system, shown everywhere as
"System (setup)" - binds it to a Karyo principal, records identity cutover 1 itself and grants it
every standard profile at the Company
(ADR 0053). Then:
- Sign in to the console as
systemwith the password fromscripts/.karyo-setup-password. Keycloak asks for a new password at once. - On Users, create the first Administrator and the first Manager, and any Operators, and grant each its profile in its Access section. System may grant every profile because it holds them all; the delegation rule is unchanged.
- When at least one Administrator and one Manager exist, choose Setup is complete on the Users page and confirm. System is disabled at once and cannot sign in again.
- Sign in as the new Administrator. Delete
scripts/.karyo-setup-password, retire the temporary master-realm bootstrap account and removeKC_BOOTSTRAP_ADMIN_USERNAMEandKC_BOOTSTRAP_ADMIN_PASSWORDfromscripts/.env.prod; changing those values later does not reset an account in an existing database.
System is console only: it has no API tokens, no /mcp access and no agents. If setup is not
confirmed, System stops by itself 14 days after installation. Every action it takes, its
disablement included, is recorded as "System (setup)" and shown on its user record. The console
cannot bring System back. To reopen it - for example to replace a lost sole administrator - set a
new KARYO_SETUP_REOPEN marker and a KARYO_SETUP_PASSWORD in scripts/.env.prod, redeploy,
sign in, and remove both settings again.
Karyo creates System only on an installation that has no principal and no identity cutover. A
redeploy of an installation that already has users, or that was commissioned through the reviewed
identity manifest, never creates System; only a new KARYO_SETUP_REOPEN marker reopens a System
that exists. Such an installation follows the external-provider route below.
External provider: the reviewed identity manifest
Create and export the identity through that provider's own reviewed administration process. Keep application traffic fenced and follow the identity principal upgrade from evidence collection through manifest review and apply. The manifest, not the provider account, creates the stable Karyo principal, exact issuer/subject binding and OPS affiliation, and the reviewed access manifest gives it its only authority, a Company grant. Only after the cutover checks pass should the administrator sign in through Karyo.
The canonical Users page can provision later managed-Keycloak principals through the disabled-first workflow. Authentication-only external mode has no runtime create or bind operation, so later principals are enrolled with the reviewed enrollment command.
Karyo's managed user administration uses karyo-admin, whose service account holds only
manage-users and view-realm. Login auditing uses karyo-backend with view-events and
view-users. Neither service identity is a Karyo principal or has master-realm administrator
access.
Commission a fresh installation
A fresh installation has the Company (node 1) and no Business Unit, and nobody holds authority. Commission it in this order:
- Deploy, so Flyway builds the schema and the seven standard permission profiles.
- Provision the first administrator as above. With managed Keycloak, System creates the first
Administrator and Manager and then finishes setup. With an external provider, enroll an OPS
principal with no Business Unit through identity cutover version 1, then apply access cutover
version 2 with its reviewed
COMPANYgrant; the access activation accepts it for an unaffiliated operations identity. - Choose the profile on Admin > Capabilities: Core, the default, or Extended, or Core with the few Extended capabilities the site needs (engine capabilities).
- Sign in as that administrator and create the Business Units under Admin > Business Units.
- Create each named Facility under its Business Unit in Warehouse > Facilities.
- Set each Facility's time zone and commission its printer through its settings.
- Run Set up Facility separately for each physical site. Setup copies no other Facility's layout or settings.
- Grant each later user a permission profile at the Company, Business Unit or Facility in the Users page.
- Commission integrations with an explicit
X-Karyo-Facility-Idon operational requests. - Rehearse receiving through shipping in each Facility and verify the configured printer receives only its labels.
A Business Unit-only operational request with sibling Facilities is refused as facility-context-required.
Never use a default-site stamp or change an integration's target silently.
Company sign-in events belong to the Company log, not a Facility movement journal.
With KARYO_DEMO=on, POST /api/v1/demo/seed creates Lumen Home Goods with Riverside DC and Hillcrest DC,
plus Cobalt Outdoor with Eastport DC. The response's tree lists their ids, names and codes.
Grant demo users on their Facility or parent. A demo installation is disposable: reset clears every
Business Unit's operational data, including units outside this demo tree.
Existing development and demo databases
This unreleased conversion supplies no automatic operational backfill or compatibility adapter. Existing development or demo databases may need a separately reviewed schema repair or rebuild and new grants. An ordinary redeploy is not evidence that old rows or identities have been commissioned for the final Facility model.
Rotating the PostgreSQL role password
PostgreSQL applies POSTGRES_PASSWORD only while initialising a fresh data directory. Changing
DB_PASSWORD and POSTGRES_PASSWORD in scripts/.env.prod does not update the persisted role;
managed mode also keeps the same value in KC_DB_PASSWORD. The deploy script does not run
ALTER ROLE for you. It does make the
mismatch loud: verify_postgres_role_password runs after PostgreSQL is up and before Keycloak
or the application start, and halts with a message saying the environment was updated but the
live role was not rotated (same function, deploy-server.sh). A password that fails the credential
policy is rejected before any container starts.
To rotate the live password:
Keep the current working password in
scripts/.env.prodso you can still authenticate.Generate a new password that satisfies the credential policy: at least 16 characters, and not a dictionary, predictable, repeated or username-derived value.
Read both values at hidden prompts and validate the exact candidate before changing the role. Substitute the actual
POSTGRES_USERvalue if it is notkaryo:DB_ROLE=karyo read -rsp 'Current PostgreSQL role password: ' PGPASSWORD echo read -rsp 'New PostgreSQL role password: ' ROTATED_DB_PASSWORD echo export PGPASSWORD ROTATED_DB_PASSWORD printf '%s' "$ROTATED_DB_PASSWORD" | python3 scripts/validate_credential.py --min-length 16 --username "$DB_ROLE" --env-literalApply that validated value through a quoted
psqlstdin program. The two exported values are passed to the container by name, so neither password appears in process arguments, the SQL program or shell history:# Keep COMPOSE_PROJECT_NAME set to the selected deployment. POSTGRES_CONTAINER=$(docker ps -q \ --filter "label=com.docker.compose.project=${COMPOSE_PROJECT_NAME:-karyo-prod}" \ --filter "label=com.docker.compose.service=postgresql") test -n "$POSTGRES_CONTAINER" || { echo 'No PostgreSQL container in the selected project'; exit 1; } docker exec -i --env PGPASSWORD --env ROTATED_DB_PASSWORD "$POSTGRES_CONTAINER" \ psql -h 127.0.0.1 -U "$DB_ROLE" -d postgres -v ON_ERROR_STOP=1 <<'SQL' \getenv rotated_password ROTATED_DB_PASSWORD SELECT format('ALTER ROLE %I WITH PASSWORD %L', current_user, :'rotated_password') \gexec SQL ROTATION_STATUS=$? unset PGPASSWORD ROTATED_DB_PASSWORD test "$ROTATION_STATUS" -eq 0Use
podmanin place ofdockerwhen that is the runtime; both accept an environment variable name without its value.Set
DB_PASSWORDandPOSTGRES_PASSWORDinscripts/.env.prodto the new password. In managed mode setKC_DB_PASSWORDto the same value.Restart the selected stack with
./scripts/deploy-server.sh --quick(or a full deploy). Managed mode restarts Keycloak and the application together; do not leave either on the old password.Confirm
/q/health/liveon the public origin and, in managed mode,/auth/realms/karyosucceed. Container healthchecks verify/q/health/readyon the internal application port, not through nginx.
If the environment values are updated before the ALTER ROLE, the next deploy stops after
PostgreSQL is up and names this procedure. Run the ALTER ROLE with the new password, then deploy
again. There is no supported path that leaves a selected service running against a password the
live role does not have.
OIDC_SECRET and KEYCLOAK_ADMIN_CLIENT_SECRET are rotated through the realm procedure below.
Changing an existing Keycloak realm
Keycloak imports infrastructure/keycloak/karyo-realm-prod.json only when the karyo realm does
not exist yet: start --import-realm skips a realm that is already in the database
(docker-compose.prod.yml, services.keycloak.command). Editing the realm file and redeploying therefore changes nothing
in an existing installation.
scripts/migrate_keycloak_realm.py applies the production security contract to an existing
realm in place (migrate_keycloak_realm.py, migrate). Its --apply mode binds the six exact
karyo-web callbacks beneath KARYO_PUBLIC_ORIGIN, installs the API-audience and identity claim
mappers described by the managed realm fixtures
on both token-issuing clients, disables the backend password grant, writes OIDC_SECRET to the
karyo-backend client and KEYCLOAK_ADMIN_CLIENT_SECRET to karyo-admin,
removes interactive credentials and federated identities from both service accounts and gives
them their least-privilege authority, and deletes the development realm's demo accounts - but
only accounts it can prove are unmodified fixtures that still accept their seeded passwords
(migrate_keycloak_realm.py, legacy_users, seeded_credential_holds). Use it whenever an existing Keycloak database carries
anything the production realm file does not: demo accounts, wildcard callbacks, or a
karyo-backend secret that fails the credential policy. --reconcile-service-clients restores
the two service clients alone and leaves human users and callbacks untouched
(scripts/migrate_keycloak_realm.py).
Decide first whether OIDC_SECRET must rotate. Every deploy, including --quick, and the
migration both enforce the credential policy in scripts/validate_credential.py. A
karyo-backend secret that fails it - the development value dev-backend-secret in particular -
is rejected, so the change becomes a genuine secret rotation. Decide this now rather than at step
5 with the stack half-changed.
docker-compose.maintenance.yml is the only way to reach Keycloak's admin interface. The
production Compose file publishes no Keycloak port, so /auth/admin and the Admin REST API are
never addressable from the deploy host; this twelve-line file adds a 127.0.0.1-bound port for
the duration of a maintenance window, and taking it down again is a mandatory numbered step
rather than a clean-up afterthought (docker-compose.maintenance.yml, services.keycloak.ports).
Isolate the identity service, then take a restorable backup of the Keycloak database and prove it restores, before anything else. Step 6 rotates the
karyo-backendclient secret and retires accounts; a run that fails partway is only recoverable from a backup already known to be good.python3 scripts/render_compose_env.py scripts/.env.prod >/dev/null docker compose -f infrastructure/docker/docker-compose.prod.yml \ stop karyo-app nginx keycloak test -z "$(docker compose -f infrastructure/docker/docker-compose.prod.yml \ ps --status running -q karyo-app nginx keycloak)" install -m 0600 /dev/null keycloak-pre-migration.dump docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'pg_dump -U "$POSTGRES_USER" -Fc keycloak' > keycloak-pre-migration.dump test "$(stat -c '%a' keycloak-pre-migration.dump)" = 600 # Prove the dump restores before trusting it. Every command here must exit 0. docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -c "CREATE DATABASE keycloak_restore_check"' docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'pg_restore -U "$POSTGRES_USER" -d keycloak_restore_check' < keycloak-pre-migration.dump docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d keycloak_restore_check \ -c "SELECT count(*) FROM user_entity"' docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'psql -U "$POSTGRES_USER" -c "DROP DATABASE keycloak_restore_check"'Keep
keycloak-pre-migration.dumpuntil step 8 has verified the deployment end to end. It contains password hashes and client secrets: store it as a secret and delete it afterwards.With the isolation still in place, create a temporary master-realm maintenance administrator while Keycloak is stopped, then expose only the loopback maintenance port. The password is read into the shell and passed by environment variable, never as a command-line argument.
export KARYO_KEYCLOAK_MAINTENANCE_PORT="$( grep '^KARYO_KEYCLOAK_MAINTENANCE_PORT=' scripts/.env.prod | cut -d= -f2- )" : "${KARYO_KEYCLOAK_MAINTENANCE_PORT:=8181}" export KARYO_KEYCLOAK_MAINTENANCE_URL="http://127.0.0.1:${KARYO_KEYCLOAK_MAINTENANCE_PORT}/auth" read -rp 'Temporary Keycloak maintenance username: ' KARYO_KEYCLOAK_MAINTENANCE_USERNAME read -rsp 'Temporary Keycloak maintenance password: ' KARYO_KEYCLOAK_MAINTENANCE_PASSWORD echo export KARYO_KEYCLOAK_MAINTENANCE_USERNAME KARYO_KEYCLOAK_MAINTENANCE_PASSWORD ./scripts/migrate_keycloak_realm.py --validate-maintenance-credentials docker compose -f infrastructure/docker/docker-compose.prod.yml \ stop karyo-app nginx keycloak test -z "$(docker compose -f infrastructure/docker/docker-compose.prod.yml \ ps --status running -q karyo-app nginx keycloak)" docker compose -f infrastructure/docker/docker-compose.prod.yml \ run --rm --no-deps \ -e KARYO_KEYCLOAK_MAINTENANCE_USERNAME \ -e KARYO_KEYCLOAK_MAINTENANCE_PASSWORD \ keycloak bootstrap-admin user \ --username:env KARYO_KEYCLOAK_MAINTENANCE_USERNAME \ --password:env KARYO_KEYCLOAK_MAINTENANCE_PASSWORD --no-prompt docker compose -f infrastructure/docker/docker-compose.prod.yml \ -f infrastructure/docker/docker-compose.maintenance.yml \ up -d --no-deps --force-recreate keycloak for _ in $(seq 1 150); do curl --noproxy '*' --fail --silent \ "${KARYO_KEYCLOAK_MAINTENANCE_URL}/realms/master" >/dev/null && break sleep 2 done curl --noproxy '*' --fail --silent \ "${KARYO_KEYCLOAK_MAINTENANCE_URL}/realms/master" >/dev/null test -z "$(docker compose -f infrastructure/docker/docker-compose.prod.yml \ ps --status running -q karyo-app nginx)" ./scripts/migrate_keycloak_realm.py --verify-maintenance-adminDo not continue unless the final three commands succeed. The tool accepts only a literal loopback HTTP
/authURL with an explicit port; it cannot send maintenance credentials through nginx, a public origin or a redirect (migrate_keycloak_realm.py,maintenance_url).Settle both secrets, and make sure each satisfies the credential policy.
KEYCLOAK_ADMIN_CLIENT_SECRET: generate a distinct securely random secret of at least 32 characters and put it inscripts/.env.prod.OIDC_SECRET: check the current value.printf '%s' "$(grep '^OIDC_SECRET=' scripts/.env.prod | cut -d= -f2-)" | python3 scripts/validate_credential.py --min-length 32 --username karyo-backend --env-literalExit 0 means it qualifies and may be kept. Any other exit means it does not: generate a replacement (
python3 -c 'import secrets; print(secrets.token_urlsafe(36))'), put it inscripts/.env.prod, and treat the change as akaryo-backendsecret rotation. The migration writes whichever value is supplied to the client, so the realm and the environment file end up in step.
Export the deployment-bound origin and the two secrets settled in step 3:
export KARYO_PUBLIC_ORIGIN='https://wms.example.com' export KEYCLOAK_ADMIN_CLIENT_SECRET='<the same distinct secret as in scripts/.env.prod>' export OIDC_SECRET='<the same backend secret as in scripts/.env.prod>'Leave the application and nginx stopped and run
./scripts/migrate_keycloak_realm.py --apply --verified-backup --isolated-maintenance. The backup flag attests that step 1's restore check succeeded, and the isolation flag attests that step 2 stopped every ordinary route; without either the tool refuses before contacting Keycloak (scripts/migrate_keycloak_realm.py). Before any change it proves, for every candidate account, both that its complete fixture fingerprint matches - attributes, direct realm roles, group membership, required actions and identity-provider state - and that it still authenticates with its seeded credential. An account whose profile changed, whose password was rotated, or which cannot be probed conclusively makes the tool refuse the whole run without touching the realm. Move the affected operator to a separately named account or resolve the identity by hand, then rerun.The run deletes only the accounts proven in step 5. It revokes all realm sessions and each candidate's sessions, then waits out the realm's longest configured access-token lifespan while the application, nginx and every other ordinary route stay stopped, so a bearer token minted just before maintenance expires before the application returns. For the production realm that wait is 900 seconds. The wait is an outage, so the tool prints
Planned access-token drain: <n> seconds (longest lifespan: <source>)before it revokes or deletes anything, naming the realm setting or client attribute that set the length. A drain longer than 3600 seconds is refused before any change: lower that lifespan in Keycloak and rerun, or accept the outage explicitly with--max-drain-seconds <n>(migrate_keycloak_realm.py,plan_access_token_drain, DRAIN_CEILING_SECONDS). Both client-credentials grants are verified before deletion and again after the drain. Deletion is recoverable only from the verified step-1 backup. A successful rerun deletes nothing but repeats the normalisation, session revocation and drain.Retire the temporary administrator while Keycloak is still reachable only on loopback, then take the maintenance port back down. The first command deletes the authenticated account from the master realm and proves the same credentials can no longer obtain a token:
./scripts/migrate_keycloak_realm.py --retire-maintenance-admin unset KARYO_KEYCLOAK_MAINTENANCE_USERNAME KARYO_KEYCLOAK_MAINTENANCE_PASSWORDTaking the port down is mandatory: recreating Keycloak from the production file alone restores the posture in which only nginx can reach the identity service. The check below reads the host's listening sockets rather than any container-runtime output, because the port forwarder binds the socket as soon as the container starts. It takes the port from
scripts/.env.prod, so it is safe to rerun from a fresh shell; a present but non-numeric value stops the step rather than silently widening the filter, and an absent value falls back to 8181, the same default step 2 used. Only the success branch clears the maintenance variables, so a stop leaves everything needed to retry. Proceed only when it reports the expected port closed.docker compose -f infrastructure/docker/docker-compose.prod.yml \ up -d --no-deps --force-recreate keycloak maintenance_port="$( grep '^KARYO_KEYCLOAK_MAINTENANCE_PORT=' scripts/.env.prod | cut -d= -f2- )" : "${maintenance_port:=8181}" if ! printf '%s' "$maintenance_port" | grep -qE '^[0-9]+$'; then echo "STOP: KARYO_KEYCLOAK_MAINTENANCE_PORT is not a port number: '$maintenance_port'" >&2 false elif ! bound="$(ss -tlnH "sport = :$maintenance_port")"; then echo 'STOP: could not query the host listening sockets' >&2 false elif [ -n "$bound" ]; then printf '%s\n' "$bound" >&2 echo "STOP: port $maintenance_port is still bound on this host" >&2 false else echo "Port $maintenance_port is closed; Keycloak is reachable only through nginx" unset KARYO_KEYCLOAK_MAINTENANCE_URL KARYO_KEYCLOAK_MAINTENANCE_PORT maintenance_port bound fiValidate and deploy in full:
./scripts/deploy-server.sh --validate-env scripts/.env.prod, then./scripts/deploy-server.shwithout--quick. Verify login auditing, then use the Users administration surface to exercise identity creation, profile changes, grants and local suspension/restoration. Verify authorized HUMAN password reset and provider enable/disable through the canonical principal HTTP routes, not the Users page. Keep the checks within the administrator's reviewed authority. Clear the remaining values:unset KARYO_PUBLIC_ORIGIN KEYCLOAK_ADMIN_CLIENT_SECRET OIDC_SECRET
Rolling back a failed realm change
A refusal needs no rollback: the tool changes nothing when a preflight check fails, so read the
message, fix the named condition and rerun. Once any Keycloak write has been attempted, even a
lost response makes the outcome ambiguous: the failure starts with REALM MIGRATION MAY BE PARTIALLY APPLIED and stops the deployment. Roll back whenever that message appears, or when
Karyo fails to start after an otherwise successful run.
Stop the application, the public proxy and Keycloak, so nothing writes while the database is replaced and no ordinary route can reach the restored identity service:
docker compose -f infrastructure/docker/docker-compose.prod.yml stop karyo-app nginx keycloak test -z "$(docker compose -f infrastructure/docker/docker-compose.prod.yml \ ps --status running -q karyo-app nginx keycloak)"Restore the step-1 dump over the Keycloak database:
docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -c "DROP DATABASE keycloak"' docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" \ -c "CREATE DATABASE keycloak OWNER \"$POSTGRES_USER\""' docker compose -f infrastructure/docker/docker-compose.prod.yml exec -T postgresql \ sh -c 'pg_restore -U "$POSTGRES_USER" -d keycloak' < keycloak-pre-migration.dumpRecreate and verify a temporary maintenance administrator. The step-1 dump was taken before that account existed, so the restore removed it. Run exactly the command block from step 2 of the procedure above.
Keep the application and nginx stopped. Generate a new
karyo-backendsecret for the restored realm, enter it at a hidden prompt, and validate it before any realm change:read -rsp 'New restored karyo-backend client secret: ' OIDC_SECRET echo export OIDC_SECRET printf '%s' "$OIDC_SECRET" | python3 scripts/validate_credential.py --min-length 32 --username karyo-backend --env-literalPut this exact value in the
OIDC_SECRETassignment inscripts/.env.prodwithout passing it on a command line. Reuse neither the earlier secret nor the failed run's secret.Select a distinct policy-compliant
karyo-adminsecret and put it in theKEYCLOAK_ADMIN_CLIENT_SECRETassignment:read -rsp 'Restored karyo-admin client secret: ' KEYCLOAK_ADMIN_CLIENT_SECRET echo export KEYCLOAK_ADMIN_CLIENT_SECRET printf '%s' "$KEYCLOAK_ADMIN_CLIENT_SECRET" | python3 scripts/validate_credential.py --min-length 32 --username karyo-admin --env-literalExport the deployment's exact public origin, then rerun the complete hardening through the loopback Admin API while every public route stays stopped:
export KARYO_PUBLIC_ORIGIN="$(grep '^KARYO_PUBLIC_ORIGIN=' scripts/.env.prod | cut -d= -f2-)" ./scripts/migrate_keycloak_realm.py --apply --verified-backup --isolated-maintenanceDo not continue unless it succeeds. Never substitute
--reconcile-service-clientshere: that mode deliberately leaves human users andkaryo-webcallbacks unchanged. If a restored human identity no longer matches the fixture fingerprint, keep the deployment isolated, resolve that identity by hand, and rerun the complete hardening.Retire the temporary administrator and take the maintenance port down, exactly as in step 7 of the procedure above.
Only then validate the environment and restore public service:
./scripts/deploy-server.sh --validate-env scripts/.env.prod ./scripts/deploy-server.sh --quickRepeat the post-migration verification in step 8 of the realm change procedure. If any check fails, the restored deployment is incomplete. Clear the exported values with
unset KARYO_PUBLIC_ORIGIN KEYCLOAK_ADMIN_CLIENT_SECRET OIDC_SECRET.
The tool deletes proven fixture accounts. Only the verified backup recovers a mistaken deletion.
Running the deploy script
Re-running the script stops and recreates the selected stack, so plan an outage and identify the
stack's project, ports, images and storage first (the header comment of deploy-server.sh).
Selecting the deployment
The script defaults to Compose project karyo-prod. Source mode defaults to application image
karyo/karyo-app:latest and nginx image karyo/nginx:latest; image-only mode requires both image
references explicitly (deploy-server.sh, the export COMPOSE_PROJECT_NAME,
KARYO_APP_IMAGE and KARYO_NGINX_IMAGE lines). For a second, isolated
rehearsal on a shared runtime, inspect the existing resources and choose an unused project name,
image tags and host port:
export COMPOSE_PROJECT_NAME=karyo-guide
export NGINX_HTTP_PORT=18088
export KARYO_APP_IMAGE=karyo/karyo-app:guide
export KARYO_NGINX_IMAGE=karyo/nginx:guide
export BASE_URL=http://localhost:18088
Export COMPOSE_PROJECT_NAME, KARYO_APP_IMAGE and KARYO_NGINX_IMAGE in the invoking shell;
the script does not read these three from scripts/.env.prod. A name set only in that file is
ignored, the project falls back to karyo-prod, and --reset-db then deletes any existing
karyo-prod containers and database volume. Keep them set for every deploy,
restart, maintenance and browser-test invocation, including direct Compose commands. Give this
checkout its own mode-0600 environment file with the matching origin and hostname settings. An
explicit NGINX_HTTP_PORT in that file overrides the exported port (deploy-server.sh, Stage 5),
so keep the two aligned.
Export NGINX_HTTP_PORT as well on every direct compose up, or nginx tries port 80, which a
rootless runtime refuses. Building an image by hand needs the argument the script passes:
podman build -f infrastructure/docker/Dockerfile.service --build-arg SERVICE_DIR=services/karyo-app
(Dockerfile.service, ARG SERVICE_DIR); without it COPY /build/image-legal fails.
Compose project names isolate containers, networks and volumes. Explicit image tags avoid
overwriting another stack's tags; a project name alone changes neither images, browser origin nor
host port. Health and database-password probes select containers by Compose project and service
labels on both Docker Compose and podman-compose (service_container_id in deploy-server.sh).
The script never prunes images, including untagged ones: clean-up is an explicit operator action.
Never reuse another deployment's identities, storage or credentials. BASE_URL selects the
browser-test target for scripts/run-e2e.sh, not the deployment origin.
The flags
| Command | What it does |
|---|---|
./scripts/deploy-server.sh |
Full rebuild: Gradle, both front ends, and both images with --no-cache. Preserves the selected project's database volume |
./scripts/deploy-server.sh --image-only |
Pulls and starts the explicitly supplied released images; requires no host JDK or Node |
./scripts/deploy-server.sh --quick |
Skips Stages 2-4 and restarts containers only. For environment or configuration changes; it compiles nothing, so a source change needs a full rebuild |
./scripts/deploy-server.sh --reset-db |
Destroys the selected project's database volume and starts fresh. In managed mode this includes Keycloak and needs new one-time bootstrap credentials; it never resets an external provider |
./scripts/deploy-server.sh --validate-env FILE |
Validates one environment file and exits |
./scripts/deploy-server.sh --help |
Shows the flags (show_help in deploy-server.sh) |
Flags combine: ./scripts/deploy-server.sh --quick --reset-db restarts on a fresh database.
--reset-db runs compose down -v after two warning lines and no confirmation prompt
(deploy-server.sh, Stage 6). Use it only for an explicitly disposable deployment, and never to
hide a Flyway checksum mismatch on retained data.
Replacing an image under the same tag
compose up -d --no-build keeps a container whose image tag is unchanged, so rebuilding an image
under the tag a running stack already uses does not replace the container. Remove the containers
before bringing the stack up again. Remove nginx first and the application in a separate command,
because nginx depends on the application and a single command naming both is refused:
podman rm -f "${COMPOSE_PROJECT_NAME}_nginx_1" # podman-compose names: <project>_<service>_1
podman rm -f "${COMPOSE_PROJECT_NAME}_karyo-app_1"
podman-compose -p "$COMPOSE_PROJECT_NAME" -f infrastructure/docker/docker-compose.prod.yml up -d --no-build
Check that the new image is the one running: compare podman inspect <container> --format '{{.Image}}'
with podman images. After a front-end-only change, rebuild only the nginx image, remove only
the nginx container and run the same up. The up also recreates PostgreSQL, Keycloak and the
application; data survives in the project's volume, so wait for the application to report healthy
before a browser run. Under Docker, docker compose up -d --force-recreate does the same in one
command.
Deploying to a host that cannot fetch the repository
A host that holds no read access to the repository takes the code as a Git bundle:
- On a machine with access, create the bundle of the commit to deploy and copy it to the host
with
scp. - On the host, in the checkout:
git fetch <bundle> HEAD && git merge --ff-only FETCH_HEAD. The fast-forward refuses a checkout that has diverged. - For a source build only, put the Node.js 24.x directory first on
PATHwhen the host's own Node.js is older, so the preflight in Stage 1 passes (one Node line). - Export the three project and image variables, then run the script or the commands above.
Copy a script to the host and run it there with bash file < /dev/null, rather than piping it over
ssh host 'bash -s' < file. A script that itself runs ssh, docker compose exec -T or
docker exec -i reads the rest of its own standard input, so the remainder of a piped script is
swallowed and never runs.
The eight stages
Each stage is one block of deploy-server.sh, headed by a # Stage N banner and announced by
log_stage.
- Check prerequisites - the host tools above, the container runtime's responsiveness, and on Podman the linger and unprivileged-port settings.
- Build the backend -
./gradlew :services:karyo-app:quarkusBuild -Dquarkus.profile=prod. - Front ends - no host build. Stage 4 builds both front ends inside the nginx image.
- Build both images with a determinism setting and
--no-cache(build_image); see container images. A failed front-end build fails this stage and stops the deploy. - Check the environment file - create it if missing, enforce mode 0600, validate it and render the four service files.
- Start infrastructure - tear down the previous run, check ports, start PostgreSQL and verify its persisted role password. Managed mode then detects/starts Keycloak; external mode leaves it stopped.
- Start the application -
karyo-app, then nginx, each with its own bounded health wait. - Verify the stack - four API probes and an SPA check through nginx, plus a managed-realm check only when Keycloak is selected.
--quick skips Stages 2-4. --image-only replaces them with supplied images and pulls after
Stage 5, before the outage.
--reset-db adds volume destruction to Stage 6. The interesting parts
are the orderings, each of which exists because something went wrong once.
Stage 6 starts PostgreSQL alone, first. verify_postgres_role_password then authenticates
the persisted role with the password from the environment file, before Keycloak or the
application are allowed to start. Credentials are expanded inside
the container shell, never in the host command arguments (keycloak_database_initialized and
verify_postgres_role_password).
Bootstrap credentials are decided by the database. See Provisioning the first administrator.
Health waits are per service and bounded separately. In managed mode Keycloak gets 420 seconds
rather than 200, because on a cold volume it runs Liquibase to build its schema and imports the
realm. External mode performs no Keycloak wait. The Compose
start_period values exist for the same reason and are commented the same way
(docker-compose.prod.yml, services.postgresql.healthcheck.start_period, services.keycloak.healthcheck.start_period).
Stage 7 starts the application and nginx one at a time, each with its own wait, because
starting nginx in the same Compose call can wait forever for a restart-looping application before
the script's own timer runs. A wait that times out prints the last
twenty lines of that service's log (wait_for_health).
check_service_healthy matches the health status exactly, because a plain
grep -q "healthy" also matches "unhealthy", and containers are
selected by Compose project and service labels rather than by name substring, so a healthy
container from another deployment cannot conceal this stack's failure
(service_container_id).
What "healthy" means differs per selected service. PostgreSQL runs pg_isready, the application
and nginx run wget against internal /q/health/ready and /, respectively. Managed Keycloak requires HTTP 200 from
/auth/realms/karyo/.well-known/openid-configuration on its application port. The image has no
curl or wget, so Bash sends the request over a TCP socket and checks the HTTP status
(docker-compose.prod.yml, services.postgresql.healthcheck, services.keycloak.healthcheck, services.karyo-app.healthcheck, services.nginx.healthcheck).
The management socket opens while bootstrap is still running and realm discovery answers 503.
Waiting for discovery prevents transient OIDC errors on a first installation. Compose dependencies,
the deploy script and the Karyo starts job all use this same health check before starting Karyo.
What Stage 8 proves
Four GETs through nginx - /api/v1/{stock-units,products,locations,principals} - count as healthy
on 200, 401 or 403. The SPA check and, in managed mode, Keycloak realm check only warn
(deploy-server.sh, Stage 8).
Accepting 401 and 403 is right: the probe is unauthenticated, and a route that refuses it is working. What it proves is therefore routing, not authorised functionality. A healthy backend does not prove provider authentication, exact principal binding or browser sign-in; sign in through the exact public origin before calling an installation ready (see verifying an installation).
The selected Compose stack
infrastructure/docker/docker-compose.prod.yml, project karyo-prod, one bridge network, one
named volume:
| Service | Image | Published |
|---|---|---|
postgresql |
docker.io/postgres:16-alpine |
nothing |
keycloak |
quay.io/keycloak/keycloak:26.8.0 |
nothing; managed-identity profile only |
karyo-app |
${KARYO_APP_IMAGE:-karyo/karyo-app:latest} |
nothing |
nginx |
${KARYO_NGINX_IMAGE:-karyo/nginx:latest} |
${NGINX_HTTP_PORT:-80}:80 |
Only nginx binds a host port. In managed mode Keycloak is reachable only through nginx in an
ordinary deployment, which is what makes /auth/admin and the Admin REST API unreachable from the
deploy host (docker-compose.maintenance.yml, services.keycloak.ports). External mode runs the other three services and
leaves Keycloak stopped.
Two details are worth carrying. The image: keys are explicit so that compose up runs the
freshly built image instead of a stale project-named one (docker-compose.prod.yml, services.karyo-app.image). And
KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true makes internal service-to-service OIDC discovery return
http://keycloak:8080 while browser requests still use the external KC_HOSTNAME
(docker-compose.prod.yml, services.keycloak.environment.KC_HOSTNAME_BACKCHANNEL_DYNAMIC) - the single setting that lets one Keycloak serve both an
in-network client and a browser behind a proxy.
infrastructure/docker/init-db.sh runs only on the first start of an empty data directory - a
property of the PostgreSQL image's entrypoint, not a fault. It creates the karyo schema
(belt-and-braces, since Flyway has create-schemas: true) and the keycloak database
(init-db.sh, CREATE DATABASE keycloak, CREATE SCHEMA karyo).
The port pre-flight checks NGINX_HTTP_PORT alone (check_ports), because nginx is the only
service that binds a host port: the postgresql service has no ports key
(docker-compose.prod.yml, services.postgresql). A PostgreSQL on the host, or a development
stack that publishes 5432, therefore does not block a production deploy.
Public access
The stack serves plain HTTP on one host port. Nothing in this repository configures a certificate, so TLS must terminate in front of the stack, at a reverse proxy or a tunnel.
One route that needs no open firewall port is a Cloudflare Tunnel, which is why the deploy script
checks for cloudflared and only warns when it is absent (deploy-server.sh, Stage 1 and the
closing reminder):
- Install
cloudflaredand authenticate withcloudflared tunnel login. - Create a tunnel:
cloudflared tunnel create karyo. - Route your domain to
http://localhost:80(or the chosenNGINX_HTTP_PORT). - Start it as a service:
sudo systemctl enable --now cloudflared.
Whatever terminates TLS, KARYO_PUBLIC_ORIGIN and KARYO_DOMAIN must name the origin browsers
actually use. Managed mode also requires KC_HOSTNAME to name its /auth endpoint.
The TLS ingress must overwrite X-Forwarded-Proto with the original request's protocol.
Nginx preserves a single http or https value; missing or malformed values use its own protocol.
Without the HTTPS value, managed OIDC discovery advertises HTTP backchannel endpoints and browsers refuse sign-in.
Nginx appends the client to the incoming X-Forwarded-For chain.
It replaces a chain with an empty element, the empty chain included, with the client it sees, because Keycloak refuses such a chain.
Do not expose the HTTP origin as an alternative public entry point around the trusted ingress.
Another product's realm on the same Keycloak
One managed Keycloak can serve a second realm for a product on a different public origin. Keycloak
26 resolves the frontend URL of a request, and with it the iss claim of its tokens and the
issuer of its discovery document, from the realm attribute frontendUrl first, then the
configured KC_HOSTNAME, then the request. The backend URLs (token and JWKS endpoints) follow the
request while KC_HOSTNAME_BACKCHANNEL_DYNAMIC is true, as the stack sets it (docker-compose.prod.yml,
services.keycloak.environment.KC_HOSTNAME_BACKCHANNEL_DYNAMIC). Karyo's own realm sets no
frontendUrl.
For the other product's realm:
- Set the realm attribute
frontendUrlto that product's origin plus/auth, so its sign-in stays on its own origin and its tokens carry that issuer. - Proxy only
/auth/realms/<realm>/and/auth/resources/on the product's own nginx. - Have the product validate
issagainst its own origin and fetch the JWKS over the private network.
Karyo's configuration and its realm are not touched by this.
Rootless Podman
Docker runs as a root daemon and needs neither of these. Two host-level prerequisites are warned about rather than enforced, because both need root:
Linger, so containers survive an SSH disconnect (
deploy-server.sh, Stage 1):sudo loginctl enable-linger $(whoami)Binding port 80 without root (
deploy-server.sh, Stage 1):sudo sysctl -w net.ipv4.ip_unprivileged_port_start=80 echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee -a /etc/sysctl.confOr skip the sysctl and run nginx on a high port by setting
NGINX_HTTP_PORT=8088; the stack is then athttp://localhost:8088.
Cloud hosts
The same script deploys to a cloud virtual machine. For released images, install Docker with the
Compose plugin (or Podman with podman-compose) and Python 3 on the Linux host configured for
journald, then follow the image-only quick start above. No host JDK or Node is needed.
For a source build, also install a JDK 21, Node.js 24.x (the line declared once in .nvmrc),
Git and, if used, cloudflared; clone the repository;
create scripts/.env.prod from scripts/.env.prod.cloud-example, whose resource limits suit a
24 GB four-core ARM64 host; export GRADLE_OPTS for a larger build heap; and run
./scripts/deploy-server.sh. Every base image in the stack has an ARM64 variant:
postgres:16-alpine, quay.io/keycloak/keycloak:26.8.0, eclipse-temurin:21-jre-alpine,
node:24-alpine and nginx:1.30.6-alpine.
Every deploy is an outage
The script's own header says "Re-running recreates the selected stack; plan an outage"
(the header comment of deploy-server.sh). Stage 6 runs compose down --remove-orphans before
anything starts, and --reset-db makes that down -v (deploy-server.sh, Stage 6). There is no
rolling restart, no second replica and no blue/green: one host, one instance, and a stop before the
start. That follows from the topology and is deliberate; its cost is a planned window for every
change, including a configuration-only --quick.
Troubleshooting a deploy
"Port X in use". The pre-flight runs in Stage 6, after the selected project's containers are
torn down, and uses ss to find what holds the nginx port, naming the process and its
PID. Identify its owner before acting; never stop another deployment to clear it. Choose an
unused nginx port and a matching origin, or resolve the conflict with the host's operator.
"Health check timeout". The script prints the last 20 lines of the service's log. Common causes: for PostgreSQL, a wrong password in the environment file or a full disk; for managed Keycloak, a slow first start while it imports the realm, or database connectivity; for the application, database errors, an unreachable configured OIDC provider, identity configuration failure, or a Flyway migration failure (see upgrade, backup and recovery).
"Required variables not configured". Replace every CHANGE_ME value. The script validates
every required variable, requires the bootstrap password, the administration-client secret and the
OIDC secret to be distinct, rejects weak or known demo credentials, and requires
KARYO_PUBLIC_ORIGIN to be one exact browser-canonical origin. It fails before starting any
container.
"Flyway checksum mismatch". Restore the applied migration file's exact released bytes,
including comments, and put any schema correction in a new forward migration; a new migration
alone cannot fix the checksum of an edited old file. Do not repair, re-baseline or renumber
retained data to conceal a mismatch. --reset-db is only for explicitly disposable data.
Podman: a health check hangs. Exec-based health checks can hang under Podman; Docker is
unaffected (the Podman note in Stage 6 of deploy-server.sh). If Keycloak's check hangs, rerun
the script; the second run usually succeeds. Switch to Docker if it happens often.
"init-db.sh did not run on redeploy". Expected: it runs only when the data directory is
empty. For a new database object after the first deployment, run the SQL against the running
PostgreSQL container, or use --reset-db on a disposable deployment.
For failures after a successful deploy - sign-in loops, missing menu entries, orders that will not move - see troubleshooting.
Related
- Operating an installation - schedulers, health, logs and the maintenance window
- Upgrade, backup and recovery - moving to a new release and coordinating Karyo with managed or external provider state
- Container images - what Stages 2-4 produce
- Licence settings (retired) - the 1.x licensing variables an environment file may still carry
- Identity and tenancy - what the user attributes mean
- ADR 0037 - provider-neutral authentication and principal ownership
- ADR 0022 - Compose as the supported deployment, with optional managed Keycloak