Deploy CoAkka Runtime on a device or in containers

Send the same test request between two processes. Start with a Linux device, use Docker Compose to isolate the environment, or run the image on a Kubernetes test cluster.

Prepare the probe

Save probe.py in a new directory. The peer role receives a request at samples.edge.probe and sends a reply. The call role sends ping, waits for up to 2 seconds and exits. Both use Python package 3.3.2 with Core 3.3.

probe.py
probe.py
"""Send a test request to a CoAkka Runtime peer."""
import argparse
import os
from pathlib import Path
import signal
import socket
import sys
from threading import Event

from coakka_v2_connector import (
    ConnectorStartSpec,
    DeadletterError,
    EndpointSpec,
    RouteSpec,
    RouteStrategy,
    RuntimeHost,
    RuntimeNetworkConfig,
    local_route,
)

TARGET = "samples.edge.probe"
SYSTEM = "edge-probe"
DEFAULT_PORT = "19301"


def serve(system_name: str, node_id: str) -> None:
    bind_host = os.environ.get("COAKKA_BIND_HOST", "127.0.0.1")
    bind_port = int(os.environ.get("COAKKA_BIND_PORT", DEFAULT_PORT))
    advertise_host = os.environ.get("COAKKA_ADVERTISE_HOST", bind_host)
    advertise_port = int(os.environ.get("COAKKA_ADVERTISE_PORT", str(bind_port)))
    ready_path = os.environ.get("COAKKA_READY_FILE")
    ready = Path(ready_path) if ready_path else None
    if ready:
        ready.unlink(missing_ok=True)

    stop = Event()

    def request_stop(_signum: int, _frame: object) -> None:
        stop.set()

    signal.signal(signal.SIGTERM, request_stop)
    signal.signal(signal.SIGINT, request_stop)
    spec = ConnectorStartSpec(
        system_name=system_name,
        node_id=node_id,
        routes=[local_route(TARGET)],
        network=RuntimeNetworkConfig.network_node(
            bind_host=bind_host,
            bind_port=bind_port,
            advertise_host=advertise_host,
            advertise_port=advertise_port,
        ),
    )
    with RuntimeHost.start(start_spec=spec) as runtime:
        runtime.register_payload_handler(TARGET, lambda payload: b"edge-ok " + payload)
        if ready:
            ready.touch()
        print(f"peer ready: {node_id} at {advertise_host}:{advertise_port}", flush=True)
        try:
            stop.wait()
        finally:
            if ready:
                ready.unlink(missing_ok=True)
    print("peer stopped", flush=True)


def call(system_name: str, node_id: str) -> None:
    peer = os.environ.get("COAKKA_PEER_HOST", "127.0.0.1")
    port = int(os.environ.get("COAKKA_PEER_PORT", DEFAULT_PORT))
    spec = ConnectorStartSpec(
        system_name=system_name,
        node_id=node_id,
        routes=[
            RouteSpec(
                target=TARGET,
                endpoints=[EndpointSpec(host=peer, port=port)],
                strategy=RouteStrategy.SINGLE_OWNER,
            )
        ],
        network=RuntimeNetworkConfig.outbound_only(),
    )
    with RuntimeHost.start(start_spec=spec) as runtime:
        response = runtime.ask_payload(
            source="probe",
            target=TARGET,
            payload=b"ping",
            timeout_ms=2_000,
        )
        if response != b"edge-ok ping":
            raise RuntimeError(f"unexpected peer reply: {response!r}")
        print(response.decode("utf-8"), flush=True)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("role", choices=("peer", "call"))
    role = parser.parse_args().role
    system_name = os.environ.get("COAKKA_SYSTEM_NAME", SYSTEM)
    node_id = os.environ.get("COAKKA_NODE_ID", socket.gethostname())
    if role == "peer":
        serve(system_name, node_id)
    else:
        try:
            call(system_name, node_id)
        except DeadletterError as error:
            print(f"probe failed: deadletter reason={error.deadletter.reason}", file=sys.stderr)
            raise SystemExit(1) from None


if __name__ == "__main__":
    main()

Use this file in all three environments. The application defines its environment variable names. See bind, advertised addresses and routes for the connection settings.

IoT devices and bare metal

Check the device's running operating system before installing.

Check the Linux device
uname -m
getconf LONG_BIT
getconf GNU_LIBC_VERSION
python3 --version

From the directory containing probe.py, install the package and open two terminals.

Install on the device
python3 -m venv .venv
.venv/bin/python -m pip install coakka-runtime-python==3.3.2
Terminal A · Start the peer
COAKKA_NODE_ID=lab-peer .venv/bin/python probe.py peer

Wait for peer ready, then send a request from terminal B.

Terminal B · Send the probe
COAKKA_NODE_ID=lab-caller .venv/bin/python probe.py call
edge-ok ping

Press Ctrl+C in terminal A to close the process. In operation, run your application under the OS service manager. The application owns GPIO, I²C and serial I/O. For a device that only sends work to a gateway, select OUTBOUND_ONLY. For entirely local processing, select EMBEDDED.

Docker Compose

Install Docker and Compose. Save Dockerfile and compose.yaml next to probe.py. Compose creates a network for the project. The caller uses peer DNS on port 19301 inside it.

Dockerfile
Dockerfile
FROM python:3.12.10-slim-bookworm
WORKDIR /app
RUN python -m pip install --no-cache-dir coakka-runtime-python==3.3.2
COPY probe.py .
USER 10001:10001
ENTRYPOINT ["python", "-u", "probe.py"]
compose.yaml
compose.yaml
services:
  peer:
    image: coakka-runtime-probe:3.3.2
    build: .
    command: ["peer"]
    environment:
      COAKKA_BIND_HOST: "0.0.0.0"
      COAKKA_ADVERTISE_HOST: peer
      COAKKA_READY_FILE: /tmp/coakka-peer.ready
    healthcheck:
      test: ["CMD", "test", "-f", "/tmp/coakka-peer.ready"]
      interval: 2s
      timeout: 1s
      retries: 10
    stop_grace_period: 20s

  caller:
    image: coakka-runtime-probe:3.3.2
    profiles: ["tools"]
    command: ["call"]
    environment:
      COAKKA_PEER_HOST: peer
Build the image and check the connection
docker compose build peer
docker compose up --wait --wait-timeout 30 peer
docker compose run --rm --no-deps caller
edge-ok ping

Run docker compose stop peer and send another request. The command exits with an error. In the tested run, it prints probe failed: deadletter reason=7 when the peer is unreachable. Start the peer again with up --wait from the commands above and retry. Remove the exercise's network and containers when finished.

Stop the Compose exercise
docker compose down

Configure CoAkka Runtime on Kubernetes

Use an IPv4 kind test cluster named coakka-lab. A Deployment runs the receiving process. An internal Service gives callers a stable address. A one-shot Job reads that address from a ConfigMap. Save both manifests beside probe.py and Dockerfile.

Configuration for each process
SettingWhere to set it and how it is used
COAKKA_SYSTEM_NAMEUse edge-probe in both the Deployment and the ConfigMap for this exercise. Choose the application name and keep it stable when adding replicas.
COAKKA_NODE_IDKubernetes injects a value for each Pod through the Downward API. Use metadata.name when the Pod name is sufficient. Use metadata.uid to give replacement Pods a new identity. Both manifests use the UID.
COAKKA_BIND_HOST
COAKKA_BIND_PORT
The Deployment binds the receiver to 0.0.0.0:19301 inside the IPv4 Pod. The samples.edge.probe handler still uses a local route with port 0.
COAKKA_ADVERTISE_HOST
COAKKA_ADVERTISE_PORT
The Deployment uses status.podIP and advertises port 19301. Each replica has its own address.
COAKKA_PEER_HOST
COAKKA_PEER_PORT
The caller's ConfigMap sets coakka-runtime-peer:19301. The application uses those two variables to route samples.edge.probe. The caller uses OUTBOUND_ONLY and opens no CoAkka Runtime listener.

The application reads these values at startup and passes them to RuntimeStartSpec. After changing a ConfigMap exposed as environment variables, recreate the Job or restart the caller Deployment. If the application updates routes while running, supply a complete route snapshot with a newer generation.

When to use Service DNS or per-Pod DNS

Service DNS. Give the caller one stable endpoint, such as coakka-runtime-peer:19301 in the same namespace. Kubernetes chooses a ready Pod for the connection. CoAkka Runtime sees one endpoint. This is the example used in the lab.

Per-Pod DNS. When CoAkka Runtime needs to choose among replicas, configure a StatefulSet and headless Service, then list the individual addresses in the route snapshot. A billing StatefulSet served by a headless billing Service in the payments namespace can expose the addresses below. Use the cluster's DNS domain and keep the listener port consistent across replicas.

billing-0.billing.payments.svc.cluster.local:19301
billing-1.billing.payments.svc.cluster.local:19301

Read the container configuration in CoAkka Publish.

kubernetes.yaml
kubernetes.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coakka-runtime-peer
spec:
  replicas: 1
  selector:
    matchLabels:
      app: coakka-runtime-peer
  template:
    metadata:
      labels:
        app: coakka-runtime-peer
    spec:
      terminationGracePeriodSeconds: 20
      containers:
        - name: peer
          image: coakka-runtime-probe:3.3.2
          imagePullPolicy: Never
          args: ["peer"]
          ports:
            - name: runtime
              containerPort: 19301
          env:
            - name: COAKKA_SYSTEM_NAME
              value: edge-probe
            - name: COAKKA_BIND_HOST
              value: "0.0.0.0"
            - name: COAKKA_BIND_PORT
              value: "19301"
            - name: COAKKA_NODE_ID
              valueFrom:
                fieldRef:
                  fieldPath: metadata.uid
            - name: COAKKA_ADVERTISE_HOST
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: COAKKA_ADVERTISE_PORT
              value: "19301"
            - name: COAKKA_READY_FILE
              value: /tmp/coakka-peer.ready
          readinessProbe:
            exec:
              command: ["test", "-f", "/tmp/coakka-peer.ready"]
            periodSeconds: 2
---
apiVersion: v1
kind: Service
metadata:
  name: coakka-runtime-peer
spec:
  type: ClusterIP
  selector:
    app: coakka-runtime-peer
  ports:
    - name: runtime
      port: 19301
      targetPort: runtime
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coakka-runtime-route
data:
  COAKKA_SYSTEM_NAME: edge-probe
  COAKKA_PEER_HOST: coakka-runtime-peer
  COAKKA_PEER_PORT: "19301"
kubernetes-caller.yaml
kubernetes-caller.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: coakka-runtime-probe
spec:
  backoffLimit: 0
  activeDeadlineSeconds: 60
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: caller
          image: coakka-runtime-probe:3.3.2
          imagePullPolicy: Never
          args: ["call"]
          envFrom:
            - configMapRef:
                name: coakka-runtime-route
          env:
            - name: COAKKA_NODE_ID
              valueFrom:
                fieldRef:
                  fieldPath: metadata.uid

Create the namespace once. If the exercise namespace already exists, continue at apply.

Load the image and start the Service
docker build -t coakka-runtime-probe:3.3.2 .
kind load docker-image coakka-runtime-probe:3.3.2 --name coakka-lab
kubectl --context kind-coakka-lab create namespace coakka-lab
kubectl --context kind-coakka-lab -n coakka-lab apply -f kubernetes.yaml
kubectl --context kind-coakka-lab -n coakka-lab rollout status deployment/coakka-runtime-peer --timeout=60s

Once the Deployment is ready, create the Job. Its logs should contain the line below. To repeat the exercise after changing the ConfigMap, remove the exercise Job and create it again.

Run the connection check Job
kubectl --context kind-coakka-lab -n coakka-lab create -f kubernetes-caller.yaml
kubectl --context kind-coakka-lab -n coakka-lab wait --for=condition=complete job/coakka-runtime-probe --timeout=70s
kubectl --context kind-coakka-lab -n coakka-lab logs job/coakka-runtime-probe
edge-ok ping

If the Job does not finish, check the Service's ready endpoints, then inspect the Job's logs and state.

Check EndpointSlices and logs
Check EndpointSlices and logs
kubectl --context kind-coakka-lab -n coakka-lab get pods,services
kubectl --context kind-coakka-lab -n coakka-lab get endpointslices -l kubernetes.io/service-name=coakka-runtime-peer
kubectl --context kind-coakka-lab -n coakka-lab logs deployment/coakka-runtime-peer
kubectl --context kind-coakka-lab -n coakka-lab describe job coakka-runtime-probe

The manifests passed structural checks. The request succeeded with the equivalent configuration in Docker Compose. Live Kubernetes execution remains open.

Remove the exercise resources
kubectl --context kind-coakka-lab -n coakka-lab delete -f kubernetes-caller.yaml --ignore-not-found
kubectl --context kind-coakka-lab -n coakka-lab delete -f kubernetes.yaml

Create a kind test cluster.

If the probe has no reply

Look up deadletter reasons · Check configuration and shutdown responsibilities · Container configuration reference on GitHub.

Measure load and choose replicas.