Skip to content

Kubernetes

This reference deployment runs Hour Advantage on Kubernetes with plain manifests and a kustomization.yaml, against an external (managed) Postgres, with a Valkey the instances share (valkey-statefulset.yaml: one replica, which suits a start; for high availability use Valkey behind Sentinel or a managed Valkey, see sizing and scaling). It follows the same design as Docker Compose, which explains health checks, balancing and draining. It uses a Service of type LoadBalancer where Compose has HAProxy.

clocks ──> cloud / MetalLB load balancer :8080
│
v
Service houradvantage-devices (LoadBalancer, externalTrafficPolicy: Local)
│ kube-proxy, ready pods only
v
gateway pods (Deployment + HPA) ──> Postgres (managed)
admin :9090 (probes, hourctl, metrics; Service houradvantage-gateway, in the cluster only)
File
gateway-deployment.yamlThe gateways. Each gets 2 CPU / 1 GiB, and the HPA sets how many. They are non-root, with a read-only root. Readiness is on /api/ready. Liveness is on /livez.
devices-service.yamlService houradvantage-devices, type LoadBalancer: the device ports, one entry each (8080).
gateway-service.yamlService houradvantage-gateway: the admin API (9090) inside the cluster, for the setup Job and hourctl.
gateway-hpa.yaml, gateway-pdb.yamlCPU autoscaling 2..10. One pod at a time through voluntary disruptions.
networkpolicy.yamlDevice ports from anywhere, the admin port from the gateways, the setup Job and Prometheus. Egress to DNS, Postgres, the Valkey, sinks and brokers. Only the gateways reach the Valkey.
valkey-statefulset.yamlThe Valkey the gateways share, with its headless Service. It keeps nothing on disk: everything in it can be rebuilt from Postgres.
gateway-secret.example.yamlNot applied: the keys of the two Secrets you create (see Run it).
setup-job.yaml, houradvantage-setup.tomlhourctl pkg push --activate of the bundles in the image, then hourctl apply: a listener on 8080 with endpoint office at /office.
kustomization.yamlNamespace houradvantage (created by you, not managed here), common labels, the setup ConfigMap, image name.

Exposed ports are deploy config; listeners are runtime config. Listeners and endpoints live in Postgres and change at run time. Which ports reach the pods from outside is devices-service.yaml, a plain Service with one entry per device port. One port (8080) carries every HTTP endpoint, told apart by path. So most changes (a new endpoint, package or site) need no manifest change. A listener on a new port needs an entry there too (see Adding a port). MQTT listeners connect out to their broker and need no port.

Balancing. kube-proxy spreads connections over the ready pods (round robin in IPVS mode, random in the iptables and nftables modes). Nothing is sticky and nothing needs to be: any pod handles any request (everything is in Postgres). Balancing is per connection, so a clock that keeps its connection open stays on one pod for that connection’s life.

Health. The readinessProbe is GET /api/ready on the admin port. It gives 503 while the pod starts and while it drains, which takes the pod out of the Services’ endpoints. The livenessProbe is GET /livez. It gives 200 whenever the process answers, from the moment the admin listener opens, before migrations. So there is no startupProbe. It asks nothing of the database.

The cloud balancer checks nodes, not pods. With externalTrafficPolicy: Local Kubernetes serves a check on the Service’s healthCheckNodePort. That check passes only on nodes running a ready gateway pod, so the balancer sends to those nodes only.

Readiness is the pod’s own (started, not draining), never the database’s. A slow or lost database must not take every pod out at once. While it is down, the messages that need it get 503 at once and clocks send them again. GET /api/instance and the metrics show it.

Draining. A pod being deleted leaves the Services’ endpoints at once. But kube-proxy on every node and the cloud balancer take a while to stop sending to it. With externalTrafficPolicy: Local the balancer checks nodes every few seconds and needs a few failed checks. A preStop sleep of 20 s keeps the pod serving meanwhile. Then comes SIGTERM. The gateway turns /api/ready to 503 and drains for 6 s more. terminationGracePeriodSeconds is 60. That is above the sleep, the drain, the attendance workers and the close. If your balancer takes longer to give up on a node (check interval x unhealthy threshold), raise the sleep and the grace period with it. The sleep action needs Kubernetes 1.30 or newer. Older clusters can use exec: {command: ["sleep", "20"]}.

Instance id. HOURADVANTAGE_INSTANCE_ID is the pod name (downward API). It is distinct per pod and kept across container restarts, but a replaced pod gets a new name. That is enough for HTTP clocks. MQTT client ids and persistent sessions are built from it. So with MQTT listeners turn the Deployment into a StatefulSet (stable names houradvantage-gateway-0, -1…). It needs a headless Service of its own as its serviceName. Without a StatefulSet, messages queued in a replaced pod’s broker session are left behind. Two live pods never share an id: the second refuses to start.

Secrets as files. The Secret is mounted at /run/secrets/houradvantage. The gateway reads HOURADVANTAGE_DATABASE_URL_FILE, HOURADVANTAGE_ADMIN_PASSWORD_HASH_FILE and HOURADVANTAGE_SECRET_KEY_FILE. The last one is the key that seals the secrets kept in the database: make it with houradm gen-secret-key, keep a copy. This keeps the values out of the environment (kubectl describe, /proc/<pid>/environ).

To change the key, put the new one in the Secret’s secret-key and the old one in secret-keys-old. Add it to the Deployment’s mounted items and set HOURADVANTAGE_SECRET_KEYS_OLD_FILE. The example comments show where. Then let the rolling update restart the pods. Once every pod has run with the new key, take the old one out (changing the key).

The plain admin password is in a Secret of its own, houradvantage-setup, mounted only into the setup Job (HOURADVANTAGE_ADMIN_PASSWORD_FILE).

Read-only image. The gateway writes no files. Its log goes to stdout as JSON lines (stdout is not a terminal), which the cluster’s log collector picks up. Device traffic is never in it. The root filesystem is read-only, with an emptyDir on /tmp.

Metrics. Each pod serves Prometheus metrics at :9090/metrics, which needs an install token. The pods carry no prometheus.io/* annotations on purpose: annotation-based discovery cannot send the token. Add a scrape job that does. Or, with the Prometheus Operator, add a PodMonitor that reads the token from a Secret (an install token made with hourctl token create):

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: houradvantage
spec:
selector:
matchLabels:
app.kubernetes.io/name: houradvantage
app.kubernetes.io/component: gateway
podMetricsEndpoints:
- port: admin
path: /metrics
authorization:
credentials:
name: houradvantage-metrics-token
key: token

See Operations, Metrics.

CPU. The pods have a CPU limit, and each pod sizes itself (including its database connections) by it. If you remove the limit to avoid throttling, set HOURADVANTAGE_CPUS to the request. Otherwise every pod sizes itself for the whole node.

PDB and HPA. The Deployment sets no replicas: the HPA owns the count (2..10), and a fixed number would reset it on every apply. The PDB is maxUnavailable: 1. So node drains and cluster upgrades take one pod at a time whatever the count.

Live views. hourctl wire and hourctl stream gather what every pod sees. The pod kubectl exec reaches asks the others directly on the pod network, at their POD_IP, port 9090. networkpolicy.yaml allows it.

NetworkPolicy. networkpolicy.yaml lets the device ports in from anywhere. It lets the admin port in only from the gateways, the setup Job and a monitoring namespace (edit it to where your Prometheus runs). Out, the gateways may reach DNS, Postgres on 5432, the Valkey on 6379, each other on 9090, and sinks and MQTT brokers on 443, 8883 and 1883.

A webhook sink (a tenant’s tenant_destinations or an install sink) or an MQTT broker on any other port is dropped silently, with no error in Hour Advantage. Its deliveries wait until the port is added to the gateway egress rule in networkpolicy.yaml. A database on another port needs its port added the same way, and so does a listener on a new device port. The policy takes effect only with a network plugin that enforces NetworkPolicy.

Time and Attendance. The gateway Deployment sets HOURADVANTAGE_ATTEND to off. Set it to on to run Time and Attendance on every pod, then create its tenants with hourctl attend tenants create. The pods’ egress and the database need nothing more.

  1. Add the listener at run time (hourctl listener add branch --http 0.0.0.0:8081, or the admin API). The API’s answer says when the port is new, as a reminder to expose it.

  2. Expose it: add an entry to devices-service.yaml and apply it. hourctl export lb k8s prints the whole Service from the listeners in the database:

    Terminal window
    kubectl -n houradvantage exec deploy/houradvantage-gateway -- \
    env HOURADVANTAGE_ADMIN_PASSWORD='...' hourctl export lb k8s

Each tenant’s listener needs a port of its own (a port is never shared between tenants). So each tenant with HTTP devices needs its own entry in devices-service.yaml (and in networkpolicy.yaml’s ingress).

Prefer a path on the existing port (hourctl endpoint add branch --listener devices --path /branch ...): it needs no step 2. A second port is the answer only for clocks that cannot be told apart by URL. That means firmware that takes a host and port but no path, or two vendors’ clocks that use the same paths. See Networking.

Most clouds take several ports on one LoadBalancer Service. Each is a listener (and on some, a health check) of the balancer, so keep the list short. Without a cloud balancer (bare metal), MetalLB gives the Service an address. Or use type: NodePort behind a balancer of your own (hourctl export lb haproxy or nginx).

With externalTrafficPolicy: Local a connection is delivered to a pod on the node it reached, without SNAT. So the peer a gateway sees is the clock itself, and trusted_proxies stays empty. That holds behind any passthrough network balancer: GCP and Azure network load balancers, AWS NLB, MetalLB. For AWS NLB it holds with instance targets. With the AWS Load Balancer Controller’s IP targets, turn on the target group attribute preserve_client_ip.enabled.

Some balancers end the connection and pass the address in X-Forwarded-For. Examples are AWS ALB, an ingress controller, your own HAProxy or nginx. Behind one, trust exactly that balancer’s addresses, so a clock’s own address is recorded:

Terminal window
kubectl -n houradvantage exec deploy/houradvantage-gateway -- \
env HOURADVANTAGE_ADMIN_PASSWORD='...' hourctl settings set trusted_proxies=10.0.0.0/24

It is a setting kept in Postgres, so every pod follows it. Do not trust the whole pod CIDR: any pod could then claim any address.

A TCP balancer can pass the client address with the PROXY protocol instead (service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: "*" and the like). Turn it on at the balancer and set proxy_protocol = true on the listener together, or every connection is closed. Do this only where nothing but the balancer can reach the device port. See Networking, PROXY protocol.

External, in the houradvantage-gateway Secret (database-url). Use sslmode=require or verify-full for a database across the network. Operations, Postgres, lists what the server must allow.

Each pod opens up to 4 connections per CPU. That is between 8 and 32, and 8 here. It opens two more, or three with Time and Attendance on (the session connection, and one for each log’s housekeeping while it runs). Take the HPA maximum and one surge pod during a rollout. That is 11 x (8 + 2) = 110 (11 x (8 + 3) = 121 with Time and Attendance). So max_connections needs that plus room for administration and anything else on the server (about 130, or 140, here). Raise max_connections with the HPA maximum.

The server’s role must carry the limits the program asks of its connections (Operations, Database role settings). Run the three ALTER ROLE statements there once, before the pods start.

With PgBouncer in front (transaction pool mode, version 1.21 or later, Operations, PgBouncer), the pods share fewer server connections. Put PgBouncer’s address in the Secret’s database-url, and the database’s own in a second key, database-session-url. The Deployment passes it as HOURADVANTAGE_DATABASE_SESSION_URL_FILE.

The arithmetic changes. Take the HPA maximum and one surge pod (11 pods, a pool of 8 each). The pods open 11 x 8 = 88 client connections to PgBouncer (max_client_conn at least that, with room). Postgres sees PgBouncer’s default_pool_size (say 40) plus the pods’ direct connections, 11 x 2 = 22 (11 x 3 = 33 with Time and Attendance). That is 62, or 73. You then need max_connections of about 90, with room for administration, instead of 130.

Make the Hour Advantage image from your distribution available to the cluster: push it to a registry the cluster pulls from, or load it onto every node. kustomization.yaml names it houradvantage:0.1.0. Change images there to the name your cluster pulls.

Terminal window
docker run --rm -it houradvantage:0.1.0 houradm hash-password # the admin login's hash
docker run --rm houradvantage:0.1.0 houradm gen-secret-key # keep a copy
kubectl create namespace houradvantage
kubectl -n houradvantage create secret generic houradvantage-gateway \
--from-file=database-url=./database-url \
--from-literal=admin-username=admin \
--from-file=admin-password-hash=./admin-password-hash \
--from-file=secret-key=./secret-key
kubectl -n houradvantage create secret generic houradvantage-setup \
--from-file=admin-password=./admin-password
# edit kustomization.yaml (image), houradvantage-setup.toml (endpoints),
# devices-service.yaml (annotations for your cloud, e.g. an internal balancer),
# networkpolicy.yaml (where Prometheus runs)
kubectl apply -k . # the folder with the files above
kubectl -n houradvantage get pods -o wide
kubectl -n houradvantage logs job/houradvantage-setup
kubectl -n houradvantage get service houradvantage-devices # EXTERNAL-IP
curl "http://<external-ip>:8080/office/iclock/cdata?SN=TEST0001&options=all&pushver=3.4.0"

The setup Job first pushes and activates the package bundles the image carries (/usr/share/houradvantage/packages; init container packages). Then it applies houradvantage-setup.toml, whose endpoints name those packages. The pods start with no packages: they are kept in Postgres and every pod loads the active revisions. kubectl -n houradvantage logs job/houradvantage-setup -c packages shows each line as [email protected]: revision 3 runs on 3/3 instances.

Each --from-file is a file holding just the value (a trailing line break is fine). This keeps the values out of your shell history. Delete the files afterwards. gateway-secret.example.yaml shows the same two Secrets as manifests, for Sealed Secrets or External Secrets. The namespace and the Secrets are not part of kubectl apply -k. So it never overwrites them with placeholders, and kubectl delete -k leaves them.

The Job is deleted 10 minutes after it finishes, so the next kubectl apply -k runs it again. That is safe: pushing the same bundle gives the revision it was, activating the active revision changes nothing, and applying changes only what differs. A Job’s template cannot be changed. So when the image or houradvantage-setup.toml changes, delete it first:

Terminal window
kubectl -n houradvantage delete job houradvantage-setup --ignore-not-found
kubectl apply -k . # the folder with the files above

With Argo CD or Flux, uncomment the annotations at the top of setup-job.yaml instead. Argo CD runs it as a PostSync hook (deleted before each new run). Flux replaces it when it changes.

Upgrading the packages is a new image and the Job run again. Pods of the old image still running during the rollout take the new revisions in too when their version can run them. One that cannot keeps the revision it had and says why (hourctl pkg show <name>). While a pod refuses the activated revision, the push step exits non-zero and the Job retries. So it finishes once the rollout has replaced the old pods. Rolling back a package is activating an earlier revision (hourctl pkg activate <name>@<revision>). See Packages.