Skip to content

Kubernetes

This guide shows you how to run a workerd cluster on GKE (Google Cloud) with a GCS bucket, or on EKS (Amazon AWS) with an S3 bucket. The pods get bucket access through the cloud’s workload identity, and a cloud load balancer terminates TLS.

Clustering is experimental, and its settings can change between versions. For each setting, see Run a cluster.

To try clustering on a local Kubernetes cluster first, use the Kubernetes sample, which runs an in-cluster stand-in for the bucket.

Before you begin

To follow this guide, you need the following:

  • A Kubernetes cluster that kubectl uses.
  • A Wrangler project that meets the image’s requirements.
  • Docker with BuildKit, kubectl, OpenSSL, and curl.
  • On GKE, the Google Cloud CLI (gcloud) and a Google Cloud project.
  • On EKS, the AWS CLI version 2 and an AWS account.
  • A domain name whose DNS records you can change, for the load balancer’s TLS certificate.

The Kubernetes cluster needs the features in the following table. Pod addresses must be private, because workerd refuses a public cluster address: IPv4 in 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or 100.64.0.0/10, or IPv6 in fc00::/7. A GKE pod range in 240.0.0.0/4 and EKS with IPv6 pods don’t work. The cluster must enforce NetworkPolicy, because traffic on port 7000 isn’t encrypted.

Requirement GKE EKS
Pod addresses VPC-native cluster with a private pod range The VPC CNI assigns VPC addresses
NetworkPolicy GKE Dataplane V2 EKS Auto Mode with its network policy controller turned on
Workload identity Workload Identity Federation for GKE EKS Pod Identity
Gateway API The GKE Gateway controller, standard channel EKS Auto Mode with the Gateway API turned on

On EKS, this guide uses Auto Mode, which runs the nodes, the network policy agent, the Pod Identity agent, and the load balancer controller.

Choose names

Set the shell variables that the commands use:

export BUCKET=my-cluster-data    # Bucket names are global.
export PREFIX=demo               # Unique for each cluster in the bucket.
export HOSTNAME=app.example.com

On GKE, also set the following:

export PROJECT_ID=my-project
export REGION=us-central1
export REGISTRY=$REGION-docker.pkg.dev/$PROJECT_ID/workerd

On EKS, also set the following:

export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGION=us-west-2
export CLUSTER=my-cluster
export REGISTRY=$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com

Build and push the app image

Build an image that contains your project:

  1. In your project’s directory, create a file named Dockerfile with the following content:

    FROM docker.io/cloudflare/workerd:latest
    COPY . /app/

    To keep every pod on the same workerd version, use a release tag in place of latest.

  2. Create a file named .dockerignore that keeps local state and local secrets out of the image:

    .wrangler
    node_modules
    .git
    .dev.vars*
    .env*

    Anyone who can pull the image can read every file in it, so add any other secret files too.

  3. Create a repository for the image.

    On GKE, create an Artifact Registry repository:

    gcloud artifacts repositories create workerd --project=$PROJECT_ID \
      --location=$REGION --repository-format=docker

    On EKS, create an Amazon ECR repository:

    aws ecr create-repository --region $REGION --repository-name app \
      --image-tag-mutability IMMUTABLE
  4. Build the image for the architecture of your nodes, and push it with a tag that names the version of your project, such as its Git commit:

    export IMAGE=$REGISTRY/app:$(git rev-parse --short HEAD)
    docker buildx build --platform linux/amd64 --tag $IMAGE --push .

    Before you push to Artifact Registry, run gcloud auth configure-docker $REGION-docker.pkg.dev. Before you push to Amazon ECR, sign in to the registry:

    aws ecr get-login-password --region $REGION |
      docker login --username AWS --password-stdin $REGISTRY

    The workerd image supports linux/amd64 and linux/arm64.

Use a new tag for every build: with imagePullPolicy: IfNotPresent, a node keeps the image that it already has for a tag.

Create the bucket

Each pod renews its lease in the bucket every few seconds, so turn off object versioning and soft delete, or the bucket keeps every replaced object.

On GKE, run the following command:

gcloud storage buckets create gs://$BUCKET --project=$PROJECT_ID \
  --location=$REGION --uniform-bucket-level-access \
  --public-access-prevention --soft-delete-duration=0

On EKS, run the following command, and omit --create-bucket-configuration in us-east-1:

aws s3api create-bucket --bucket $BUCKET --region $REGION \
  --create-bucket-configuration LocationConstraint=$REGION

New buckets have versioning turned off and block public access. The bucket must apply conditional writes; each pod checks this when it starts. On GKE, use a gs:// URL, because the S3-compatible API of GCS ignores the conditions.

Give the pods access to the bucket

The pods run as the Kubernetes service account workerd in the namespace default. Give it access to the bucket, and to nothing else.

GKE (Google Cloud): Use Workload Identity Federation

To give the pods access, do the following:

  1. Create a Google service account for the pods:

    gcloud iam service-accounts create workerd-pods --project=$PROJECT_ID
    export GSA=workerd-pods@$PROJECT_ID.iam.gserviceaccount.com
  2. Let the service account manage the bucket’s objects:

    gcloud storage buckets add-iam-policy-binding gs://$BUCKET \
      --member=serviceAccount:$GSA --role=roles/storage.objectAdmin
  3. Let the Kubernetes service account act as the Google service account:

    gcloud iam service-accounts add-iam-policy-binding $GSA \
      --role=roles/iam.workloadIdentityUser \
      --member="serviceAccount:$PROJECT_ID.svc.id.goog[default/workerd]"
  4. Create the Kubernetes service account with an annotation that names the Google service account:

    kubectl create serviceaccount workerd
    kubectl annotate serviceaccount workerd \
      iam.gke.io/gcp-service-account=$GSA

workerd gets tokens from the GKE metadata server, which the node pool must use. That’s the default with Workload Identity Federation for GKE.

EKS (Amazon AWS): Use EKS Pod Identity

To give the pods access, do the following:

  1. Create an IAM role that EKS Pod Identity can assume:

    aws iam create-role --role-name workerd-pods \
      --assume-role-policy-document '{
        "Version": "2012-10-17",
        "Statement": [{
          "Effect": "Allow",
          "Principal": {"Service": "pods.eks.amazonaws.com"},
          "Action": ["sts:AssumeRole", "sts:TagSession"]
        }]
      }'
  2. Let the role list the bucket and read, write, and delete its objects:

    aws iam put-role-policy --role-name workerd-pods \
      --policy-name cluster-data --policy-document '{
        "Version": "2012-10-17",
        "Statement": [
          {"Effect": "Allow", "Action": "s3:ListBucket",
           "Resource": "arn:aws:s3:::'$BUCKET'"},
          {"Effect": "Allow",
           "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
           "Resource": "arn:aws:s3:::'$BUCKET'/*"}
        ]
      }'
  3. Associate the role with the Kubernetes service account:

    aws eks create-pod-identity-association --region $REGION \
      --cluster-name $CLUSTER --namespace default --service-account workerd \
      --role-arn arn:aws:iam::$ACCOUNT_ID:role/workerd-pods
  4. Create the Kubernetes service account. It needs no annotation:

    kubectl create serviceaccount workerd

EKS gives a pod the role’s credentials when the pod is created, so create the pods after the association. workerd gets the role’s temporary keys and replaces them before they expire. Don’t set AWS_ACCESS_KEY_ID or AWS_CREDENTIALS_FILE: they take precedence. Without Auto Mode, first install the agent with aws eks create-addon --cluster-name $CLUSTER --addon-name eks-pod-identity-agent.

Create the cluster key

Every pod needs the same cluster key. Create it as a Secret:

kubectl create secret generic workerd-cluster \
  --from-literal=key="$(openssl rand -hex 32)"

Keep the key out of source control: anyone who has it and can reach port 7000 can call every service in a pod.

Deploy the pods

The manifest is the same on GKE and EKS, except for the bucket settings. To deploy the pods, do the following:

  1. Create a file named workerd.yaml with the following content:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: workerd
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: workerd
      minReadySeconds: 10
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1
          maxUnavailable: 0
      template:
        metadata:
          labels:
            app: workerd
        spec:
          serviceAccountName: workerd
          automountServiceAccountToken: false
          terminationGracePeriodSeconds: 40
          securityContext:
            runAsNonRoot: true
            runAsUser: 65532
            runAsGroup: 65532
            fsGroup: 65532
            seccompProfile:
              type: RuntimeDefault
          topologySpreadConstraints:
            - maxSkew: 1
              topologyKey: kubernetes.io/hostname
              whenUnsatisfiable: ScheduleAnyway
              labelSelector:
                matchLabels:
                  app: workerd
          containers:
            - name: workerd
              image: IMAGE
              imagePullPolicy: IfNotPresent
              args:
                - --experimental
                - --cluster-addr=$(POD_IP):7000
                - --data-dir=/data
              ports:
                - name: http
                  containerPort: 8787
                - name: cluster
                  containerPort: 7000
              securityContext:
                allowPrivilegeEscalation: false
                readOnlyRootFilesystem: true
                capabilities:
                  drop: [ALL]
              resources:
                requests:
                  cpu: 100m
                  memory: 128Mi
              env:
                - name: POD_IP
                  valueFrom:
                    fieldRef:
                      fieldPath: status.podIP
                - name: WORKERD_CLUSTER_KEY_FILE
                  value: /etc/workerd-cluster/key
                - name: WORKERD_SHUTDOWN_DELAY_MS
                  value: "20000"
                - name: WORKERD_CLUSTER_STOP_TIMEOUT_MS
                  value: "8000"
              readinessProbe:
                httpGet:
                  path: /ready
                  port: cluster
                periodSeconds: 2
              volumeMounts:
                - name: data
                  mountPath: /data
                - name: cluster-key
                  mountPath: /etc/workerd-cluster
                  readOnly: true
          volumes:
            - name: data
              emptyDir: {}
            - name: cluster-key
              secret:
                secretName: workerd-cluster
    ---
    apiVersion: policy/v1
    kind: PodDisruptionBudget
    metadata:
      name: workerd
    spec:
      maxUnavailable: 1
      selector:
        matchLabels:
          app: workerd
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: workerd
    spec:
      selector:
        app: workerd
      ports:
        - name: http
          port: 80
          targetPort: http
    ---
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: workerd-cluster-port
    spec:
      podSelector:
        matchLabels:
          app: workerd
      policyTypes:
        - Ingress
      ingress:
        - ports:
            - port: 8787
        - from:
            - podSelector:
                matchLabels:
                  app: workerd
          ports:
            - port: 7000

    Replace IMAGE with the value of $IMAGE from Build and push the app image.

  2. Add the bucket settings for your cloud, as the next sections describe.

  3. Apply the manifest, and wait for the rollout:

    kubectl apply -f workerd.yaml
    kubectl rollout status deployment/workerd

After SIGTERM, a pod keeps serving for WORKERD_SHUTDOWN_DELAY_MS while the load balancer stops sending it requests, and then hands its Durable Objects to the other pods within WORKERD_CLUSTER_STOP_TIMEOUT_MS. If you change either, keep terminationGracePeriodSeconds longer than both together.

GKE (Google Cloud): Add the bucket settings

In workerd.yaml, add the following variable to the env list of the workerd container:

- name: WORKERD_CLUSTER_BUCKET
  value: gs://BUCKET/PREFIX

Replace BUCKET and PREFIX with the values of $BUCKET and $PREFIX.

EKS (Amazon AWS): Add the bucket settings

The pods need the bucket settings and a scheduling rule for Auto Mode. To add them, do the following:

  1. In workerd.yaml, add the following variables to the env list of the workerd container:

    - name: WORKERD_CLUSTER_BUCKET
      value: s3://BUCKET/PREFIX
    - name: AWS_REGION
      value: REGION

    Replace BUCKET, PREFIX, and REGION with the values of $BUCKET, $PREFIX, and $REGION.

  2. Replace the pod’s topologySpreadConstraints with the following settings:

    affinity:
      podAntiAffinity:
        requiredDuringSchedulingIgnoredDuringExecution:
          - topologyKey: kubernetes.io/hostname
            labelSelector:
              matchLabels:
                app: workerd
    topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: ScheduleAnyway
        labelSelector:
          matchLabels:
            app: workerd

    Auto Mode otherwise packs every pod onto the first node that’s ready, so one node failure stops the whole cluster.

  3. Turn on NetworkPolicy enforcement. Auto Mode accepts NetworkPolicies but ignores them until you turn on its network policy controller:

    kubectl apply -f - <<'EOF'
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: amazon-vpc-cni
      namespace: kube-system
    data:
      enable-network-policy-controller: "true"
    EOF

    Without Auto Mode, set enableNetworkPolicy to "true" in the Amazon VPC CNI add-on configuration.

Expose the app

A Gateway creates a cloud load balancer, and an HTTPRoute sends requests for your host name to the pods. The load balancer health-checks GET / on port 8787, so your app must return 200 for it.

GKE (Google Cloud): Create a Gateway

The Gateway is a global external Application Load Balancer with a certificate from Certificate Manager. To create it, do the following:

  1. Reserve a global static IP address, and point your host name’s DNS A record at it:

    gcloud compute addresses create workerd-gateway --project=$PROJECT_ID \
      --global
    gcloud compute addresses describe workerd-gateway --project=$PROJECT_ID \
      --global --format='value(address)'
  2. Create a Google-managed certificate for your host name and a certificate map that serves it. For the steps, see Deploy a global external Application Load Balancer with Certificate Manager. This guide names the certificate map workerd-certmap.

  3. Create a file named gateway.yaml with the following content:

    apiVersion: gateway.networking.k8s.io/v1
    kind: Gateway
    metadata:
      name: workerd
      annotations:
        networking.gke.io/certmap: workerd-certmap
    spec:
      gatewayClassName: gke-l7-global-external-managed
      addresses:
        - type: NamedAddress
          value: workerd-gateway
      listeners:
        - name: https
          protocol: HTTPS
          port: 443
        - name: http
          protocol: HTTP
          port: 80
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: workerd-http-redirect
    spec:
      parentRefs:
        - name: workerd
          sectionName: http
      rules:
        - filters:
            - type: RequestRedirect
              requestRedirect:
                scheme: https
                statusCode: 301
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: workerd
    spec:
      parentRefs:
        - name: workerd
          sectionName: https
      hostnames:
        - HOSTNAME
      rules:
        - backendRefs:
            - name: workerd
              port: 80

    Replace HOSTNAME with the value of $HOSTNAME.

  4. Apply the manifest, and wait for the load balancer:

    kubectl apply -f gateway.yaml
    kubectl wait --for=condition=Programmed --timeout=15m gateway/workerd

    The load balancer takes several minutes to start.

EKS (Amazon AWS): Create a Gateway

The Gateway is an internet-facing Application Load Balancer (ALB) with a certificate from AWS Certificate Manager (ACM). To create it, do the following:

  1. Turn on the Gateway API for the cluster:

    aws eks update-cluster-config --region $REGION --name $CLUSTER \
      --kubernetes-network-config '{"elasticLoadBalancing":{"enabled":true,"gatewayApi":{"crds":{"managed":true}}}}'
  2. Check that the cluster’s public subnets have the tag kubernetes.io/role/elb with the value 1. EKS puts the load balancer in these subnets.

  3. Request a certificate for your host name, and validate it with DNS:

    aws acm request-certificate --region $REGION --domain-name $HOSTNAME \
      --validation-method DNS

    Create the validation record that aws acm describe-certificate shows, and wait until the certificate’s status is ISSUED.

  4. Create a file named gateway.yaml with the following content:

    apiVersion: gateway.networking.k8s.io/v1
    kind: GatewayClass
    metadata:
      name: eks-auto-alb
    spec:
      controllerName: eks.amazonaws.com/gateway-alb
    ---
    apiVersion: gateway.k8s.aws/v1
    kind: LoadBalancerConfiguration
    metadata:
      name: workerd
    spec:
      scheme: internet-facing
      loadBalancerName: workerd
      listenerConfigurations:
        - protocolPort: HTTPS:443
          defaultCertificate: CERTIFICATE_ARN
          sslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: Gateway
    metadata:
      name: workerd
    spec:
      gatewayClassName: eks-auto-alb
      infrastructure:
        parametersRef:
          group: gateway.k8s.aws
          kind: LoadBalancerConfiguration
          name: workerd
      listeners:
        - name: https
          protocol: HTTPS
          port: 443
        - name: http
          protocol: HTTP
          port: 80
    ---
    apiVersion: gateway.k8s.aws/v1
    kind: TargetGroupConfiguration
    metadata:
      name: workerd
    spec:
      targetReference:
        name: workerd
      defaultConfiguration:
        targetType: ip
        healthCheckConfig:
          healthCheckPath: /
          healthCheckProtocol: HTTP
          healthCheckInterval: 5
          healthCheckTimeout: 2
          healthyThresholdCount: 2
          unhealthyThresholdCount: 2
        targetGroupAttributes:
          - key: deregistration_delay.timeout_seconds
            value: "15"
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: workerd-http-redirect
    spec:
      parentRefs:
        - name: workerd
          sectionName: http
      rules:
        - filters:
            - type: RequestRedirect
              requestRedirect:
                scheme: https
                statusCode: 301
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: workerd
    spec:
      parentRefs:
        - name: workerd
          sectionName: https
      hostnames:
        - HOSTNAME
      rules:
        - backendRefs:
            - name: workerd
              port: 80

    Replace the following:

    • CERTIFICATE_ARN: the ARN of the certificate from the previous step
    • HOSTNAME: the value of $HOSTNAME
  5. Label the namespace, so that a rollout stops an old pod only after the ALB sends requests to its replacement:

    kubectl label namespace default \
      eks.amazonaws.com/pod-readiness-gate-inject=enabled
  6. Apply the manifest, and wait for the load balancer:

    kubectl apply -f gateway.yaml
    kubectl wait --for=condition=Programmed --timeout=15m gateway/workerd
  7. Restart the pods, so that they get the readiness gate:

    kubectl rollout restart deployment/workerd
    kubectl rollout status deployment/workerd
  8. Point your host name at the load balancer. Get the load balancer’s DNS name:

    kubectl get gateway workerd -o jsonpath='{.status.addresses[0].value}'

    Create a CNAME record for your host name with this value as its target. If your zone is in Amazon Route 53, create an alias A record instead.

Verify the cluster

Send a request to the app, and check that each pod has a record under v1/nodes/ in the bucket:

curl -s https://$HOSTNAME/
gcloud storage ls gs://$BUCKET/$PREFIX/v1/nodes/   # GKE
aws s3 ls s3://$BUCKET/$PREFIX/v1/nodes/           # EKS

Roll out a new version

Build and push an image with a new tag, set the tag in workerd.yaml, and run kubectl apply -f workerd.yaml. Old and new pods serve side by side during a rollout, so keep each version compatible with the previous one; see Roll out a new version in the sample. While clustering is experimental, a rollout to a new workerd version can fail requests between old and new pods.

What’s next

Type to search…

↑↓ navigate↵ selectEsc close