Docker Compose
This Docker Compose setup runs HAProxy in front of several Hour Advantage instances that share one Postgres and a Valkey, on one machine. Use it to try a cluster, or to run a small site. Clocks talk to HAProxy. Any instance can serve any clock, because everything the server keeps (setup, devices, commands, events) is in Postgres. The instances tell each other what changed through the Valkey, which more than one instance requires (a shared Valkey). It keeps nothing on disk: all of it can be rebuilt from Postgres.
clocks │ port 28080 ▼haproxy stats: 127.0.0.1:28404 │ ▼gateway x N admin: 9090, inside │ the compose network ├──> postgres └──> valkey| File | |
|---|---|
| the Hour Advantage image | From the Hour Advantage distribution. It is non-root. The official package bundles are in /usr/share/houradvantage/packages (containers). |
docker-compose.yml | postgres, gateway (3 replicas), haproxy, and packages, a one-shot that pushes the bundles. The project is houradvantage. |
docker-compose.external-db.yml | Override: use your own Postgres instead of the bundled one. |
haproxy.cfg | discovery, health checks, balancing, timeouts |
houradvantage-setup.toml | The listeners, endpoints and trusted proxies, for hourctl apply. |
.env.example | Settings. Copy to .env. |
rolling-update.ps1, rolling-update.sh | Move the gateways to a new image one at a time, without turning clocks away. |
How it works
Section titled “How it works”Device ports. Exposed ports are deploy config. Listeners are runtime config. Listeners and endpoints live in Postgres and change at run time (hourctl apply, the admin API). Which ports reach the instances from outside is this folder’s business, listed port by port. It is the ports: of the haproxy service in docker-compose.yml, and a frontend and backend each in haproxy.cfg (fe_http_8080, be_http_8080). The stack exposes one HTTP device port, 8080, published on the host as 28080. Every HTTP endpoint shares it, told apart by path (/office, /branch…). So a new endpoint, package or site needs no change here. There is no MQTT port: MQTT listeners connect out to their broker, which is not part of this stack. See Adding a port below for the rest.
Discovery. Compose gives the gateway service one DNS name that resolves to every running replica. HAProxy’s server-template gw 16 gateway ... resolvers docker init-addr none keeps sixteen server slots. It fills them from Docker’s DNS (127.0.0.11), asking again every few seconds. Scale up and the new replicas fill free slots. Scale down and their slots go to MAINT (resolution) within about five seconds (hold obsolete 5s). HAProxy is never reloaded. Sixteen slots means at most fifteen replicas, with one more beside them during a rolling update. Raise the number in haproxy.cfg for more.
Health. Every slot is checked with GET /api/ready on the instance’s admin port (check port 9090). The probes need no login. Three failed checks (about 4 s) take an instance out. Two good ones bring it back. An instance answers not-ready while it starts and while it drains for shutdown (6 s, longer than the checks take). So docker compose stop, a scale-down or a rolling update takes it out of rotation before it stops. It does not answer not-ready when Postgres is slow or down. That would take every instance out at the same moment and leave HAProxy turning every clock away. Instead the messages that need the database get 503 at once, and clocks send them again. Errors on the device port do not mark a server down by themselves (no observe layer4). A dead instance is caught by the checks, and until then its requests are retried on another one. The gateways’ own compose health check asks the same (hourd healthcheck --ready). So docker compose up --wait returns once every instance would be put in rotation.
Balancing. balance roundrobin: a clock’s requests go to every instance in turn. All instances share Postgres, so any of them handles any request. A device’s messages are handled one at a time whichever instances receive them. hourctl wire and hourctl stream gather what every instance sees. No affinity is needed. Hashing on the serial number (balance url_param SN, commented in haproxy.cfg) is optional.
Failures. A connection that fails or is closed without an answer is retried up to twice more, each time on another instance (retry-on conn-failure empty-response, option redispatch 1). The gateway stores an upload before it answers, and events carry stable ids. So a retried upload is at worst stored twice under the same id. Clocks send again on their own when they get no answer, so timeouts are short. They are 1 s to connect, 10 s for a request and 20 s for an answer. A request waits at most 2 s in a queue. There are 200 connections per instance.
Client addresses. HAProxy removes any X-Forwarded-For a client sent and adds its own (option forwardfor). The gateways believe it only from their trusted_proxies, a stored setting. houradvantage-setup.toml sets it to the compose network (172.30.28.0/24). That must match COMPOSE_SUBNET, so change them together. A second stack or a network already using that range fails with “Pool overlaps with other one”. Until it is applied, a clock’s address is HAProxy’s. Change it later with hourctl settings set trusted_proxies=....
Where clients seem to come from. HAProxy can only report the address it sees. Where Docker publishes the port through its userland proxy, every connection reaches HAProxy from the Docker network’s gateway address. That is the case on Docker Desktop, Colima, rootless Docker, and any published port whose traffic comes from the host itself. So X-Forwarded-For is that one address for every clock. The limits kept per address (the allow and deny lists, the rate limits) and the logs see a single client. Docker Engine on Linux with its default NAT keeps the client’s address. To keep the address where it is lost, you have two ways:
- Run HAProxy with host networking (
network_mode: host). The gateways are then reached on their published addresses, not the compose names. - Put a balancer outside Docker in front. It sends the PROXY protocol to a listener set for it (Networking, PROXY protocol), as a cloud load balancer does.
Check what the gateways see with hourctl device show: a device’s remote_ip.
Request ids. HAProxy gives every request an id. It sends it to the gateway as X-Request-Id and logs it as the last field of its line. The gateway puts it on its own log lines about the request (request_id) and sends it back. HAProxy logs the path without the query string, where clocks put their keys.
Logs. Every container logs to stdout. The gateways write one JSON object per line (their stdout is not a terminal). Docker keeps at most LOG_MAX_FILES files of LOG_MAX_SIZE per container (5 x 20 MB): docker compose logs gateway.
Metrics. Each instance serves Prometheus metrics at http://<instance>:9090/metrics on the compose network, with an install token (metrics). A Prometheus on that network can find the instances with dns_sd_configs: [{names: [tasks.gateway, gateway], type: A, port: 9090}].
The admin API listens on 0.0.0.0:9090 inside each container (the image’s HOURADVANTAGE_ADMIN_LISTEN). It is reachable only on the compose network. It is not published on the host. Off loopback the gateway insists on a login, given as HOURADVANTAGE_ADMIN_USERNAME and HOURADVANTAGE_ADMIN_PASSWORD_HASH (required in .env).
Pool. Postgres must allow replicas x (pool size + 2) + a few connections (+ 3 with Time and Attendance on). The setting is POSTGRES_MAX_CONNECTIONS, 200 in the example. A gateway’s pool is 4 per CPU of its GATEWAY_CPUS, between 8 and 32.
Secrets. The database URL, the password hash, the secret key and the Postgres password are set in .env (or your environment). Compose hands them to the containers as files in /run/secrets (top-level secrets: with environment:). The gateway reads them through the *_FILE variables. They are not in the containers’ environment, so docker inspect does not show them. Compose refuses to start a service while a secret it needs is not set. HOURADVANTAGE_SECRET_KEY is one. To change the key, put the new one in HOURADVANTAGE_SECRET_KEY, the old one in HOURADVANTAGE_SECRET_KEYS_OLD, and run the rolling update. Once every gateway runs with the new key, the stored secrets are sealed again with it, and the old key can go (changing the key). HOURADVANTAGE_SECRET_KEYS_OLD is a secret too, read through its _FILE. The example .env holds a comma, which means none, because compose hands a secret over only when it is not empty.
Hardening. The Hour Advantage containers run as a non-root user with every capability dropped and no-new-privileges. Their root filesystem is not read-only here. Compose copies the secrets into the container, which a read-only root refuses. The Kubernetes setup runs read-only.
Versions. You need Docker Compose 2.24 or newer (secrets from the environment, !reset in the external-database override). You also need Docker Engine 25 or newer (the health checks’ start_interval). Compose is the Docker compose plugin: check docker compose version. The docker.io package of a stock Ubuntu has Docker Engine without it. Install Docker’s own packages, or the docker-compose-v2 package.
Images. The images the stack pulls (Postgres, HAProxy, Valkey) are pinned by digest. The tag in the file says which version it is. A newer patch is a deliberate change.
HAProxy is a single point of failure here: one container on one host. That suits one machine. For more, run HAProxy on two or more machines with a floating address between them (keepalived/VRRP), or put a cloud TCP load balancer in front of them. The gateways and Postgres need no change.
Time and Attendance. HOURADVANTAGE_ATTEND=on in .env runs it on every gateway beside Connect (off in the example). Then create its tenants through any instance:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl attend tenants create acme --name "Acme"A killed replica. A replica that is killed from outside (docker kill, an out-of-memory kill) is not started again by restart: unless-stopped. That setting restarts a container only when its own process fails. Docker leaves one that was killed from outside as stopped. HAProxy takes it out of rotation and the others carry on. To bring the stack back to the replicas it asks for:
docker compose up -d --no-recreate --waitPorts on the host
Section titled “Ports on the host”| Port | |
|---|---|
28080 | Devices: HAProxy’s 8080. With houradvantage-setup.toml, endpoint office is at <host>:28080/office. |
127.0.0.1:28404 | HAProxy stats: /stats, /stats;csv. |
Postgres and the admin API are not published. To reach Postgres from the host, uncomment its 127.0.0.1:25432 line in docker-compose.yml.
Run it
Section titled “Run it”Download the files above into one folder and run the commands there. Load the Hour Advantage image from your distribution first. The gateway and packages services run the image named by HOURADVANTAGE_IMAGE in .env (houradvantage:0.1.0 in the example). Set it to the name your image has. docker load -i <image file> prints it. up -d --wait runs that image as it is: nothing is built.
cp .env.example .env # set POSTGRES_PASSWORD (a long random one: it is empty in the example), HOURADVANTAGE_IMAGE and the login
# A password hash for the admin login. Paste it into .env as# HOURADVANTAGE_ADMIN_PASSWORD_HASH='...' (keep the single quotes: the hash is full of $).docker run --rm -it houradvantage:0.1.0 houradm hash-password# or, without prompts:# printf '%s\n' 'the password' | docker run --rm -i houradvantage:0.1.0 houradm hash-password --stdin
# The key that seals the secrets kept in the database. Paste it into .env as# HOURADVANTAGE_SECRET_KEY=... (required) and keep a copy somewhere safe.docker run --rm houradvantage:0.1.0 houradm gen-secret-key
export HOURADVANTAGE_ADMIN_PASSWORD='the password' # PowerShell: $env:HOURADVANTAGE_ADMIN_PASSWORD = '...'docker compose up -d --waitdocker compose run --rm packagesPackages. The gateways start with no packages. Packages are kept in Postgres, like the rest of the setup. The one-shot packages service pushes and activates the bundles the image carries (/usr/share/houradvantage/packages) through the admin API once the gateways are healthy. It prints [email protected]: revision 3 runs on 3/3 instances for each, and exits. It logs in with HOURADVANTAGE_ADMIN_USERNAME and HOURADVANTAGE_ADMIN_PASSWORD (from your environment or .env). It is in the setup profile, so docker compose up leaves it alone. up --wait waits for the long-running services only. Run it with docker compose run --rm packages. Pushing is idempotent: the same bundle is the same revision, and activating the active revision changes nothing. So running it again is safe. By hand, through any instance:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway sh -c 'hourctl pkg push --activate /usr/share/houradvantage/packages/*.tar.gz'docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl pkg listThen set the cluster up once, through any instance (the setup is in Postgres, so every instance follows). The endpoints name packages, so push them first:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl apply /etc/houradvantage/setup.tomldocker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl statushourctl in a gateway container logs in as HOURADVANTAGE_ADMIN_USERNAME. Only the password is given per command.
houradvantage-setup.toml sets trusted_proxies to the compose network. It makes the listener devices on 8080 with endpoint office (/office, [email protected], new_devices = "hold"). With "hold", a clock that calls in waits until it is allowed, so strangers cannot register themselves. "allow" lets any clock that calls in register. That suits only a network no stranger can reach.
Try it: register the clock first (the endpoint holds clocks it does not know until they are allowed). Then let it call in:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl device register office TEST0001curl "http://127.0.0.1:28080/office/iclock/cdata?SN=TEST0001&options=all&pushver=3.4.0"curl "http://127.0.0.1:28080/office/iclock/getrequest?SN=TEST0001"printf '1001\t2026-10-01 08:00:00\t0\t1\t0\t0\t0\n' | \ curl --data-binary @- "http://127.0.0.1:28080/office/iclock/cdata?SN=TEST0001&table=ATTLOG&Stamp=1"docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl events --type punchIf docker compose up -d --wait reports a container as unhealthy, the reason is in its log: docker compose logs gateway. For one, a placeholder password hash left in .env is refused there with “is not a password hash”.
Each answer carries x-houradvantage-instance: gwN, the HAProxy slot that served it.
Add an endpoint later on the same port, under its own path. It is reachable through HAProxy as soon as the instances have applied it (a second or so), with no change here:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl endpoint add branch --listener devices --path /branch --package [email protected] --new-devices allow --option timezone=America/Chicagocurl "http://127.0.0.1:28080/branch/iclock/cdata?SN=TEST0002&options=all&pushver=3.4.0"Adding a port
Section titled “Adding a port”A path on 8080 is the first choice. A port of its own is for clocks that cannot be told apart by URL. One case is firmware that takes a host and port but no path (an endpoint without a path must be alone on its listener). Another is two vendors’ clocks that use the same paths. Then:
-
Add the listener at run time, through any instance. The API’s answer says when its port is new, as a reminder to expose it:
Terminal window docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl listener add port --http 0.0.0.0:8081docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl endpoint add wholeport --listener port --package [email protected] --new-devices allow -
Expose it: a
fe_http_8081/be_http_8081pair inhaproxy.cfg(copy the 8080 pair) and- "28081:8081"under thehaproxyservice’sports:. Then rundocker compose up -d haproxy. A new port has to be published, so HAProxy is recreated: clocks see a second or two without an answer, and send again.hourctl export lbprints both from the listeners in the database:Terminal window docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl export lb haproxydocker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl export lb composeThe printed
serverlines are placeholders. Here the backend fills its servers from DNS instead (server-template gw 16 gateway:8081).
One port for each tenant. A listener is never shared between tenants. So a Connect tenant whose clocks reach the gateways over HTTP has a port of its own: its listener, a fe_http_<port> / be_http_<port> pair, and a ports: line, as above. hourctl -t acme export lb haproxy prints its pair. When hourctl apply or listener add warns that a port is one no listener of the setup used before, it is a reminder of this. It also appears for 8080 the first time houradvantage-setup.toml is applied, which the stack publishes already.
Kubernetes. The same split, with a Service of type LoadBalancer listing the device ports in place of HAProxy: see deploy/kubernetes.
docker compose up -d --no-recreate --scale gateway=5docker compose up -d --no-recreate --scale gateway=2curl -s "http://127.0.0.1:28404/stats;csv" | grep be_http_ # or open /statsOr the runtime API inside the HAProxy container:
docker compose exec haproxy sh -c 'echo "show servers state be_http_8080" | nc 127.0.0.1 9999'Update
Section titled “Update”Load the new image and set HOURADVANTAGE_IMAGE in .env to its name. docker compose up -d would then recreate every gateway at once. For a few seconds HAProxy has no server, and clocks are turned away. Replace them one at a time instead:
sh rolling-update.sh # PowerShell: .\rolling-update.ps1For each gateway the script starts one more from the new image. It waits until that one is ready and HAProxy has it in rotation. Then it stops the old one, which drains before it closes. If a new gateway is not ready in two minutes (a wrong key, a bad image), the script prints its last log lines and removes it. It says that the gateways running before are still serving, untouched. It stops there. The schema is migrated by the first new instance. The old ones keep working on it meanwhile (see Operations, Upgrades). With an external database pass the files: sh rolling-update.sh -f docker-compose.yml -f docker-compose.external-db.yml.
A new image may carry new package bundles. The gateways go on running the revisions active before. Once every gateway runs the new image, push the new bundles with docker compose run --rm packages. Each package line then moves to the new revision on every instance at once, without a restart. To go back, activate the earlier revision. hourctl pkg show <name> lists them. hourctl pkg activate <name>@<revision> activates one. See Packages. Swarm’s docker stack deploy with update_config: {order: start-first, parallelism: 1} does the same, if you run Swarm.
Backup and restore
Section titled “Backup and restore”The database is the bundled postgres service (or your own, see External Postgres). Back it up with pg_dump, to a file outside the volume, together with the .env file. The .env file holds HOURADVANTAGE_SECRET_KEY, without which the backup cannot be used:
docker compose exec -T postgres pg_dump -U houradvantage -Fc houradvantage > backup-$(date +%F).dumpRestore on a stack with no gateway running, into an empty database. Then run the after-restore step. Download after-restore.sql next to the compose file:
docker compose stop gateway # every gatewaydocker compose up -d postgresdocker compose exec -T postgres psql -U houradvantage -d postgres \ -c 'DROP DATABASE IF EXISTS houradvantage' -c 'CREATE DATABASE houradvantage OWNER houradvantage'docker compose exec -T postgres pg_restore -U houradvantage -d houradvantage --no-owner < backup-2026-10-26.dumpdocker compose exec -T postgres psql -U houradvantage -d houradvantage -v ON_ERROR_STOP=1 < after-restore.sqldocker compose up -dSkipping the after-restore step makes everything stored after the restore reuse numbers that readers of the event feed, the audit trail and the sync rows have already passed. They would miss it without any error.
Wire capture
Section titled “Wire capture”This watches every byte a clock sends and receives, live, on every instance. Keys and biometric data are included. It runs until --for is up or you press Ctrl-C:
docker compose exec -e HOURADVANTAGE_ADMIN_PASSWORD gateway hourctl wire --device TEST0001 --for 10mThe instance the command reaches gathers what every replica sees (HAProxy spreads a clock’s requests over all of them). It says so if one cannot be reached. Nothing of it is stored or logged. hourctl stream does the same for the traffic log, events and commands. hourctl peers lists the replicas and where each is reached.
External Postgres
Section titled “External Postgres”Set HOURADVANTAGE_DATABASE_URL in .env and add the override. The override keeps the bundled postgres service from starting:
HOURADVANTAGE_DATABASE_URL=postgres://houradvantage:[email protected]:5432/houradvantage?sslmode=require
docker compose -f docker-compose.yml -f docker-compose.external-db.yml up -d --waitThe database must exist and the user must be allowed to create tables in it. The gateway migrates its schema on start, one instance at a time. The user’s role must carry the limits the gateway asks of its connections (Operations, Database role settings). The gateway refuses to start without them, and prints the SQL.
sslmode follows libpq (disable, prefer, require, verify-ca, verify-full). Across a network use require or verify-full, since the default, prefer, falls back to plain text. A private CA goes in sslrootcert= in the URL. POSTGRES_PASSWORD is not needed.
With the bundled database, the URL in .env holds ${POSTGRES_PASSWORD}. A password with @, /, : or ? in it must be percent-encoded there. A Postgres on the Docker host is host.docker.internal. Operations, Postgres, lists what the server must allow.
Tear down
Section titled “Tear down”docker compose down # keep the database volumedocker compose down -v # and remove it