# Docker

> Running cairnflow from the container image, and a two-node cluster on SeaweedFS with Docker Compose.

Source: https://cairnflow.dev/docs/self-hosting/docker

:::note
The official image is published on GitHub Container Registry:
`ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0`. To build an image yourself from the `Dockerfile` at
the root of the [source repository](https://github.com/cairnflowdev/cairnflow) instead:

```sh
git submodule update --init        # the Dockerfile copies vendor/; the build fails without it
docker build -t cairnflow:local .
```
:::

## The image

- Contains `cairnflow`, `cairn`, `cairn-ctl` and `cairn-query-worker`, built together, so their
  versions match. `cairn-query-worker` sits next to `cairnflow`, so SQL queries run in a child
  process by default.
- Runs as a non-root user (uid and gid `10001`).
- `ENTRYPOINT ["cairnflow"]`: every argument after the image name is passed to `cairnflow`.
- Defaults to a single node on `file:///var/lib/cairnflow`, listening on `0.0.0.0:8080`
  (`CAIRNFLOW_HOST=0.0.0.0`, `CAIRNFLOW_PORT=8080`, `CAIRNFLOW_DATA_DIR=/var/lib/cairnflow`).
- Exposes `8080` (clients) and `8081` (internal, node to node). Publish only `8080`.
- Includes `curl`, so a health check can call `GET /health`.
- Carries its license and notice files under `/usr/share/doc/cairnflow/`.

Authentication is on: pass a bootstrap key, or `--no-auth` for a quick local try.

```sh
# one node, data in a named volume
docker run --rm -p 8080:8080 \
  -e CAIRNFLOW_ADMIN_KEY="$CAIRNFLOW_ADMIN_KEY" \
  -v cairnflow-data:/var/lib/cairnflow \
  ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0

# one node on S3; s3.env holds the AWS_* variables
docker run --rm -p 8080:8080 \
  -e CAIRNFLOW_ADMIN_KEY="$CAIRNFLOW_ADMIN_KEY" \
  --env-file s3.env \
  ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --main-store s3://bucket/prefix
```

Keep `s3.env` limited to the variables you need; the S3 client reads every variable of the
process (see [Object stores](/docs/self-hosting/storage)).

### Reaching your service from the container

The runtime calls your service, so register it at an address the container can reach. With Docker
Desktop and a service running on the host:

```sh
cairn register http://host.docker.internal:9080
```

On Linux, use the host's IP on the Docker bridge, or run your service in the same Compose project.

### Running `cairn-ctl`

`cairn-ctl` reads the bucket directly, with the same S3 environment as the node. Override the
entrypoint:

```sh
docker run --rm --env-file s3.env --entrypoint cairn-ctl \
  ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --main-store s3://bucket/prefix verify
```

Anyone who can run it with those credentials can change the bucket: hand it only to people who are
allowed to.

## Clusters in containers

The image sets `CAIRNFLOW_HOST=0.0.0.0`, which is right for one node and **wrong for a cluster**: a
node advertises the address it binds to, and peers cannot reach `0.0.0.0`. In a cluster, pass
`--host` with the container's own hostname or IP, or bind on all interfaces and set
`--advertise-host` (see [Running a cluster](/docs/self-hosting/cluster)).

## Compose example: two nodes on SeaweedFS

This example runs SeaweedFS as the S3 store, creates a bucket, and starts two nodes sharing
`s3://cairnflow/demo` with four ranges. The S3 keys are samples for a local trial, not secrets.
There are no default API keys or cluster secret: Compose stops at once unless you set them.

`seaweed-s3.json`, the SeaweedFS S3 identities:

```json title="seaweed-s3.json"
{
  "identities": [
    {
      "name": "cairnflow",
      "credentials": [{ "accessKey": "dev-only-access-key", "secretKey": "dev-only-not-a-secret" }],
      "actions": ["Admin", "Read", "Write", "List", "Tagging"]
    }
  ]
}
```

Set the bootstrap key (at least 32 bytes) and the cluster secret in the shell that runs
`docker compose` (or put their values in a `.env` file next to the Compose file):

```sh
export CAIRNFLOW_ADMIN_KEY="cf_$(openssl rand -hex 24)"
export CAIRNFLOW_CLUSTER_SECRET="$(openssl rand -hex 32)"
```

```yaml title="docker-compose.yml"
name: cairnflow

x-s3-env: &s3-env
  AWS_ENDPOINT: http://seaweedfs:8333
  AWS_ACCESS_KEY_ID: dev-only-access-key
  AWS_SECRET_ACCESS_KEY: dev-only-not-a-secret
  AWS_REGION: us-east-1
  AWS_ALLOW_HTTP: "true"
  AWS_VIRTUAL_HOSTED_STYLE_REQUEST: "false"

x-auth-env: &auth-env
  CAIRNFLOW_ADMIN_KEY: ${CAIRNFLOW_ADMIN_KEY:?set CAIRNFLOW_ADMIN_KEY}
  CAIRNFLOW_TOKEN: ${CAIRNFLOW_ADMIN_KEY:?set CAIRNFLOW_ADMIN_KEY}   # lets `cairn` inside the container authenticate
  CAIRNFLOW_CLUSTER_SECRET: ${CAIRNFLOW_CLUSTER_SECRET:?set CAIRNFLOW_CLUSTER_SECRET}

x-cairn: &cairn
  image: ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0
  restart: unless-stopped
  stop_grace_period: 30s          # longer than the 20 s graceful shutdown
  depends_on:
    create-bucket:
      condition: service_completed_successfully
  healthcheck:
    test: ["CMD-SHELL", "curl -fsS http://$$(hostname):8080/health || exit 1"]
    interval: 5s
    timeout: 3s
    retries: 20

services:
  seaweedfs:
    image: chrislusf/seaweedfs:latest   # pin a version in production
    command: >
      server -dir=/data -s3 -s3.config=/etc/seaweed/s3.json
      -volume.max=0 -master.volumeSizeLimitMB=1024
    volumes:
      - ./seaweed-s3.json:/etc/seaweed/s3.json:ro
      - seaweed-data:/data
    healthcheck:
      test: ["CMD", "curl", "-s", "-o", "/dev/null", "http://localhost:8333"]
      interval: 3s
      timeout: 2s
      retries: 30

  create-bucket:
    image: amazon/aws-cli:latest
    environment:
      AWS_ACCESS_KEY_ID: dev-only-access-key
      AWS_SECRET_ACCESS_KEY: dev-only-not-a-secret
      AWS_DEFAULT_REGION: us-east-1
    entrypoint: ["/bin/sh", "-c"]
    command:
      - >
        aws --endpoint-url http://seaweedfs:8333 s3api head-bucket --bucket cairnflow 2>/dev/null
        || aws --endpoint-url http://seaweedfs:8333 s3api create-bucket --bucket cairnflow
    depends_on:
      seaweedfs:
        condition: service_healthy

  cairn-1:
    <<: *cairn
    hostname: cairn-1
    environment:
      <<: [*s3-env, *auth-env]
    command: [--main-store, s3://cairnflow/demo, --node-id, cairn-1, --partitions, "4",
              --host, cairn-1, --port, "8080",
              --disk-cache-dir, /var/lib/cairnflow/disk-cache, --disk-cache-bytes, "2147483648"]
    volumes:
      - cairn-1-cache:/var/lib/cairnflow
    ports:
      - "127.0.0.1:8080:8080"

  cairn-2:
    <<: *cairn
    hostname: cairn-2
    environment:
      <<: [*s3-env, *auth-env]
    command: [--main-store, s3://cairnflow/demo, --node-id, cairn-2, --partitions, "4",
              --host, cairn-2, --port, "8080",
              --disk-cache-dir, /var/lib/cairnflow/disk-cache, --disk-cache-bytes, "2147483648"]
    volumes:
      - cairn-2-cache:/var/lib/cairnflow
    ports:
      - "127.0.0.1:8081:8080"

volumes:
  seaweed-data:
  cairn-1-cache:
  cairn-2-cache:
```

```sh
docker compose up -d
docker compose exec cairn-1 cairn --server http://cairn-1:8080 cluster
```

Node 1 answers on `127.0.0.1:8080` and node 2 on `127.0.0.1:8081` (each container's ingress port;
the internal port stays inside the Compose network). Points to know:

- Published ports listen on the host's loopback only: a port Docker publishes on `0.0.0.0` goes
  around the host's firewall. To open the cluster to the network, put a TLS proxy in front.
- The cluster secret comes from the environment, so it is never stored in the bucket, and a leaked
  S3 key cannot be used to forge internal requests or console cookies.

- `--host` is the container's hostname, which resolves to its IP on the Compose network. That is
  the address the node advertises to its peer.
- Advertised addresses are Compose-network IPs. From the host machine, a `503` pointing at the
  other node cannot be followed. Call from inside the network, run your service as a Compose
  service, or send `x-cairn-forward: leader` so the receiving node forwards the request.
- Each node has its own volume for the SST disk cache. The cache holds copies of customer data;
  delete the volume when a node leaves (see [Operations](/docs/self-hosting/operations)).
- This setup has no TLS, and SeaweedFS runs as one process on one disk. It is a starting point,
  not a production layout.

## Kubernetes notes

No persistent volume is needed: nodes keep no state. A workable layout:

- a StatefulSet, only so that pods have stable names to use as `--node-id`;
- `--host` set to the pod IP (from the downward API, `status.podIP`). Do not use the pod's DNS name
  through a headless service: the record may not exist yet when the container starts, and a node
  that cannot resolve its own address exits;
- a headless service for the internal port between pods, and a regular service for the ingress
  port;
- `terminationGracePeriodSeconds` longer than `--shutdown-timeout-ms`, so `SIGTERM` has time to
  hand ranges over;
- the optional SST disk cache on a size-limited `emptyDir`, which is discarded with the pod;
- S3 credentials and the bootstrap key in Secrets, exposed as environment variables.
