Containers

Kubernetes Agent Sandbox: Isolate AI Coding Agents with gVisor

A warm SandboxClaim handed our coding agent a ready gVisor pod in 522 ms, while a cold claim on the same node took 11.4 s. About 8.5 of those cold seconds came from the default 10 s readiness probe period rather than from gVisor, and one field change cut the cold path to 2.2 to 3.2 s.

Original content from computingforgeeks.com - post 189175

We ran Kubernetes Agent Sandbox v1.0.10 on K3s (tested November 2026 on Ubuntu 26.04) with the OpenCode agent inside a Sandbox that had no ServiceAccount token and no route to the API server. Its egress was then cut to public TCP 443, and blocked requests failed in under 15 ms instead of hanging.

One default needed real work. The router ships with a NetworkPolicy that allows TCP 443 and 6443 to any address, which made it an open proxy to the internet in our tests until we patched that rule down to a single /32.

Agent Sandbox on K3s: measured results

Every number below came from one 4 vCPU node, timed from kubectl create to the Ready condition on the claim with date +%s%N. Isolation rows show the curl exit code the sandbox got back for each target.

MeasurementResultRuns
Warm claim, pool of 2514 to 642 ms, median 522 ms10
Warm claim, controller-side histogram41 ms mean, 15 of 16 under 100 ms16
Cold claim, default probe (periodSeconds 10)11.33 to 11.81 s, median 11.37 s5
Cold claim, periodSeconds 12.16 to 3.17 s, median 2.88 s5
Sandbox pod footprint at rest56 Mi memory, 15 to 24 m CPU3 pods
API server ClusterIP from the sandboxcurl exit 7 after 0 ms5
Cloud metadata 169.254.169.254curl exit 7 after 1 ms2
Router to arbitrary IP:443, default policyreachable (HTTP 400 from target)1
Router to arbitrary IP:443, patched policyblocked (HTTP 502)1

Interactive agents live on the warm row. Half a second of client time is mostly two kubectl process starts and their API round trips, because the controller finished each adoption in 41 ms on average. The cold rows are a warning about defaults, since a probe period copied from a web service template adds 8 to 9 seconds per sandbox. A warm pool hides that cost only until the pool runs dry, so the probe is worth fixing even when you run a pool.

What Agent Sandbox adds over a plain Pod

A plain Pod with runtimeClassName: gvisor already gives you the kernel boundary. Agent Sandbox wraps lifecycle and network objects around it, so an agent platform can hand out isolated, stateful workspaces on demand without writing its own controller. The project has five pieces: the release manifest installs the first four as CRDs plus the controller, and the router is a separate install in Step 7.

  • Sandbox (agents.x-k8s.io/v1beta1). One pod with a stable identity, which is what an agent session holds on to.
  • SandboxTemplate. The pod spec plus a managed NetworkPolicy. Patching the template updated the live policy within 5 s in our runs.
  • SandboxWarmPool. Keeps N sandboxes booted and Ready. Our pool of 2 reached Ready in 11.8 s with the default probe.
  • SandboxClaim. A request for a sandbox from a pool. A claim adopts a warm pod and the pool starts a replacement at once.
  • sandbox-router. An HTTP proxy that routes on an X-Sandbox-ID header, which is how clients reach a gVisor sandbox when kubectl port-forward cannot.

Security decisions sit in the template and the router, so most of this guide is about those two. The diagram shows where each piece ended up in the finished lab.

Kubernetes Agent Sandbox architecture diagram on K3s with gVisor: sandbox-router on port 8080 and a SandboxWarmPool feed an OpenCode sandbox pod on 8888, the pod reaches public TCP 443 plus DNS to two resolvers and is denied cluster and metadata IPs, the router reaches kube-apiserver on 6443

Traffic into a sandbox enters only through the router on port 8080, and the warm pool hands out pods that already passed readiness. Outbound, the sandbox leaves the node only on TCP 443 to public addresses plus DNS to two public resolvers, because every private, link-local and carrier-grade NAT range is excluded. Only the router may still dial the API server, and only on one address.

Lab and versions tested

Our lab was a single-node K3s server on a 4 vCPU, 15 GB cloud VM, hostname bench-sbx. Treat that as a floor for a demo. A node that serves a pool for real users is sized by sandbox requests multiplied by peak concurrent claims, and Step 8 works through that arithmetic with measured numbers.

ComponentVersion on the test box
OS and kernelUbuntu 26.04.1 LTS, 7.0.0-1017-gcp
K3sv1.37.2+k3s1 (containerd v2.3.7-k3s1)
gVisorrunsc release-20261109.0
Agent Sandbox controller and routerv1.0.10
Coding agentOpenCode 1.19.5, free big-pickle model
Network policy engineK3s embedded kube-router

K3s matters here for one reason. Its embedded kube-router controller enforced egress rules on runsc pods in every test, so no Calico or Cilium install was needed. If you build on kubeadm on Ubuntu 26.04 instead, pick a CNI that enforces NetworkPolicy egress, because otherwise every policy in this guide is accepted by the API and silently ignored on the wire.

Step 1: Confirm the gVisor RuntimeClass works

Start from a node that already has K3s, runsc and a RuntimeClass named gvisor with handler runsc. A fresh K3s install on Ubuntu 26.04 plus Steps 4 to 6 of our gVisor vs Kata Containers vs runc benchmark gets you there, so this guide does not repeat the runtime setup. Step 3 also builds an image with Docker, so install docker.io on the node if it is not there yet. One pod proves the runtime chain end to end.

kubectl run gv-check --image=busybox:1.37 --restart=Never --overrides='{"spec":{"runtimeClassName":"gvisor"}}' -- dmesg
kubectl logs gv-check

Under runsc, dmesg shows the boot log of the gVisor Sentry instead of the host kernel, so this output can only come from a sandboxed pod.

[   0.000000] Starting gVisor...
[   0.390084] Preparing for the zombie uprising...
[   0.477753] Segmenting fault lines...
[   0.950381] Checking naughty and nice process list...
[   1.304127] Politicking the oom killer...
[   1.568176] Synthesizing system calls...
[   1.812154] Gathering forks...
[   2.096027] Granting licence to kill(2)...
[   2.449576] Creating bureaucratic processes...
[   2.577603] Deleting VFS and rebuilding it from scratch...
[   2.866881] Verifying that no non-zero bytes made their way into /dev/zero...
[   3.348606] Ready!

Here the Sentry reached Ready! 3.3 s into the life of the pod. Nothing here falls back to runc. A missing RuntimeClass makes kubectl run refuse the pod at once, and a class whose runsc handler K3s never loaded from config-v3.toml.tmpl leaves the pod failing with an event that kubectl describe pod gv-check shows. Fix that first, because every sandbox later in this guide uses the same class, then delete the test pod with kubectl delete pod gv-check. gVisor is one layer of pod isolation; default deny NetworkPolicy, seccomp and AppArmor are the others, and our CKS practice questions drill each of them on a kubeadm cluster.

Step 2: Install the Agent Sandbox controller and CRDs

Upstream publishes one manifest with the core CRD, the extension CRDs and the controller. Read the latest tag from the GitHub API, so the install here and the source checkout in Step 3 use the same version.

export AS_VERSION=$(curl -s https://api.github.com/repos/kubernetes-sigs/agent-sandbox/releases/latest | grep tag_name | cut -d '"' -f 4)
echo $AS_VERSION

On our test day it returned v1.0.10. Apply the manifest with extensions, since templates, pools and claims are all extension types, and wait for the rollout.

kubectl apply -f https://github.com/kubernetes-sigs/agent-sandbox/releases/download/${AS_VERSION}/sandbox-with-extensions.yaml
kubectl -n agent-sandbox-system rollout status deploy/agent-sandbox-controller --timeout=180s
kubectl get crd | grep agents.x-k8s.io
kubectl -n agent-sandbox-system get pods

Four CRDs land at v1beta1, each served from the storage version, and the controller runs as a single pod.

Agent Sandbox v1.0.10 install on K3s showing four agents.x-k8s.io CRDs at v1beta1 and the controller pod Running

Our controller pod was Running 3 s after the apply. Its deployment runs with --extensions, the flag that makes it reconcile SandboxTemplate, SandboxWarmPool and SandboxClaim objects, so keep that flag if you ever template the controller yourself. Without it the extension CRDs still install, and claims simply sit there unreconciled.

Step 3: Build the OpenCode image and write a SandboxTemplate

Upstream ships an OpenCode sandbox example whose image wraps the agent in a small Python runtime server on port 8888. Clone the tag that matches the controller and build the image on the node with Docker.

git clone --branch ${AS_VERSION} --depth 1 https://github.com/kubernetes-sigs/agent-sandbox.git ~/agent-sandbox
cd ~/agent-sandbox/examples/opencode-sandbox
sudo docker build -q -t opencode-sandbox:v1 .

K3s runs its own containerd, so an image in the Docker store is invisible to the kubelet. Pipe it across and check that the CRI sees it.

sudo docker save opencode-sandbox:v1 | sudo k3s ctr images import -
sudo k3s crictl images | grep -E "opencode|IMAGE"

Importing the 628 MB image took 49.8 s. On a multi-node cluster you would push to a registry instead, because a ctr import lands on one node only and a sandbox scheduled anywhere else fails to pull.

IMAGE                                                    TAG                     IMAGE ID            SIZE
docker.io/library/opencode-sandbox                       v1                      e7d29f1f9086c       628MB

Runtime class, resources and the workspace volume all live in the template. Create a namespace for agents and open the manifest.

kubectl create namespace agents
mkdir -p ~/manifests
vim ~/manifests/coding-agent-template.yaml

Below is the exact file we applied. It sets no networkPolicy block yet, on purpose, so you can see what the controller generates on its own before you replace it in Step 6.

apiVersion: extensions.agents.x-k8s.io/v1beta1
kind: SandboxTemplate
metadata:
  name: coding-agent
  namespace: agents
spec:
  podTemplate:
    metadata:
      labels:
        app: coding-agent
    spec:
      runtimeClassName: gvisor
      restartPolicy: OnFailure
      securityContext:
        fsGroup: 1000
      containers:
      - name: opencode
        image: opencode-sandbox:v1
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8888
        readinessProbe:
          httpGet:
            path: "/"
            port: 8888
        resources:
          requests:
            cpu: "250m"
            memory: "512Mi"
          limits:
            memory: "2Gi"
        volumeMounts:
        - name: workspace
          mountPath: /workspace
      volumes:
      - name: workspace
        emptyDir:
          sizeLimit: 2Gi

Apply it and list what appeared in the namespace.

kubectl apply -f ~/manifests/coding-agent-template.yaml
kubectl -n agents get sandboxtemplate,networkpolicy

A NetworkPolicy you never wrote shows up next to the template, keyed on a template hash label.

NAME           AGE
coding-agent   4s
NAME                          POD-SELECTOR                                         AGE
coding-agent-network-policy   agents.x-k8s.io/sandbox-template-ref-hash=49ff95ab   4s

Without a networkPolicy block, the controller manages a default policy for every template. Step 6 prints its contents, which turn out to be looser than the name suggests, so do not treat its presence as a finished egress story.

Step 4: Fill a warm pool and claim a sandbox

A SandboxWarmPool keeps booted sandboxes waiting, so a claim skips both the gVisor start and the readiness probe. Two replicas are enough to see the adopt and refill behaviour.

apiVersion: extensions.agents.x-k8s.io/v1beta1
kind: SandboxWarmPool
metadata:
  name: coding-agent-pool
  namespace: agents
spec:
  replicas: 2
  sandboxTemplateRef:
    name: coding-agent

Save it as ~/manifests/warmpool.yaml, apply it and time how long the pool takes to go Ready.

kubectl apply -f ~/manifests/warmpool.yaml

Then wrap the wait in time, which gives the pool fill latency without any extra tooling.

time kubectl -n agents wait --for=condition=Ready sandbox --all --timeout=180s
kubectl -n agents get sandboxwarmpool,sandbox

Both sandboxes went Ready together after 11.8 s. Two pods finishing in lockstep at just over 10 s already hinted at the probe period we measured later.

sandbox.agents.x-k8s.io/coding-agent-pool-b599g condition met
sandbox.agents.x-k8s.io/coding-agent-pool-z996p condition met

real	0m11.773s
user	0m0.209s
sys	0m0.059s
NAME                                                           READY   DESIRED   TEMPLATE       AGE
sandboxwarmpool.extensions.agents.x-k8s.io/coding-agent-pool   2       2         coding-agent   11s

NAME                                              READY   REASON              AGE
sandbox.agents.x-k8s.io/coding-agent-pool-b599g   True    DependenciesReady   11s
sandbox.agents.x-k8s.io/coding-agent-pool-z996p   True    DependenciesReady   11s

A claim names the pool, not the template. In v1.0.10 spec.warmPoolRef is the only required field of a SandboxClaim, so even a cold claim goes through a pool.

apiVersion: extensions.agents.x-k8s.io/v1beta1
kind: SandboxClaim
metadata:
  name: task-1
  namespace: agents
spec:
  warmPoolRef:
    name: coding-agent-pool

With that file at ~/manifests/claim.yaml, apply it and look at the pool straight away.

kubectl apply -f ~/manifests/claim.yaml
kubectl -n agents wait --for=condition=Ready sandboxclaim/task-1 --timeout=60s
kubectl -n agents get sandbox,pods

Our claim took over coding-agent-pool-z996p, which keeps its pool-generated name, and a third sandbox was already in ContainerCreating one second later.

sandboxclaim.extensions.agents.x-k8s.io/task-1 created
sandboxclaim.extensions.agents.x-k8s.io/task-1 condition met
NAME                                              READY   REASON                 AGE
sandbox.agents.x-k8s.io/coding-agent-pool-6s9qq   False   DependenciesNotReady   1s
sandbox.agents.x-k8s.io/coding-agent-pool-b599g   True    DependenciesReady      17s
sandbox.agents.x-k8s.io/coding-agent-pool-z996p   True    DependenciesReady      17s

NAME                          READY   STATUS              RESTARTS   AGE
pod/coding-agent-pool-6s9qq   0/1     ContainerCreating   0          1s
pod/coding-agent-pool-b599g   1/1     Running             0          17s
pod/coding-agent-pool-z996p   1/1     Running             0          17s

Read the sandbox name from status.sandbox.name on the claim rather than guessing it, because the router headers and every kubectl exec below need it. Claims get adopted pods in no fixed order, so a script that assumes the newest or oldest pod will eventually talk to the wrong sandbox. Ours was coding-agent-pool-z996p; the next steps keep it in P, so set that variable again if you open a new shell, along with AS_VERSION from Step 2.

Step 5: Prove the agent has no cluster access

An agent that can read a ServiceAccount token can talk to the API server with whatever rights that account holds. Check the pod spec first, then look from inside the sandbox, since a spec that says the right thing proves nothing if a mount or route slips through.

P=$(kubectl -n agents get sandboxclaim task-1 -o jsonpath='{.status.sandbox.name}'); echo $P
kubectl -n agents get pod $P -o jsonpath="runtimeClassName={.spec.runtimeClassName} automountServiceAccountToken={.spec.automountServiceAccountToken} serviceAccount={.spec.serviceAccountName}{\"\n\"}"
kubectl -n agents exec $P -- sh -c "uname -r; dmesg | head -2; ls /var/run/secrets/kubernetes.io/serviceaccount 2>&1; env | grep ^KUBERNETES_SERVICE_HOST; id"
kubectl -n agents exec $P -- curl -sSk -m 5 https://10.43.0.1:443/version
kubectl -n agents exec $P -- curl -sS -m 5 http://169.254.169.254/computeMetadata/v1/

Our template never mentioned automountServiceAccountToken, yet the controller set it to false on the pod. No token directory exists, and both the API server ClusterIP and the metadata endpoint refuse the connection.

gVisor sandbox pod with automountServiceAccountToken false, no service account directory, and curl exit 7 to the API server and metadata IP

Two separate controls produced that result, and knowing which is which matters when you change one. The missing token comes from the pod spec. Refused connections come from the generated NetworkPolicy, because 10.43.0.1 sits inside 10.0.0.0/8 and 169.254.169.254 inside 169.254.0.0/16, so loosening egress later would reopen the API path even with no token. The process also runs as uid 1000, not root.

Even a leaked token would buy little here. Ask the API what the default account in agents may do.

kubectl auth can-i --list --as=system:serviceaccount:agents:default -n agents

Its list stops at the built-in self-review verbs and the discovery URLs, with no access to pods, secrets or any other namespaced resource.

Resources                                       Non-Resource URLs                      Resource Names   Verbs
selfsubjectreviews.authentication.k8s.io        []                                     []               [create]
selfsubjectaccessreviews.authorization.k8s.io   []                                     []               [create]
selfsubjectrulesreviews.authorization.k8s.io    []                                     []               [create]
clustertrustbundles.certificates.k8s.io         []                                     []               [get list watch]
                                                [/.well-known/openid-configuration/]   []               [get]
                                                [/.well-known/openid-configuration]    []               [get]
                                                [/api/*]                               []               [get]

Keep it that way. Never bind a role to the default account in the agents namespace, because every sandbox in it would inherit that role the day someone turns token mounting back on. If a tool inside the sandbox needs cluster data, give it a narrow proxy rather than a token. Our Pod Security Standards guide covers enforcing the restricted profile on the namespace as a second layer.

Run the agent and let it try

OpenCode in this image defaults to the free big-pickle model on OpenCode Zen, which needs no API key. Upstream warns against sending private code to that free model, so use it for tests only. Give the agent a small task.

kubectl -n agents exec $P -- sh -c "cd /workspace && opencode --version && opencode run \"Write fizzbuzz.py that prints FizzBuzz for 1 to 15, run it with python3 and show the output\""

In 7 s of wall time the agent wrote a 182 byte file, ran it under gVisor and printed the right sequence.

OpenCode 1.19.5 running inside a gVisor Agent Sandbox pod, writing fizzbuzz.py and printing FizzBuzz output

Next we asked the agent itself to look for a token under /var/run/secrets and to curl https://$KUBERNETES_SERVICE_HOST/api. It reported No such file or directory and curl: (7) Failed to connect to 10.43.0.1 port 443 after 0 ms, the same results as our manual checks. Matching results are the point, because a boundary that only holds when a human types the commands is no boundary for an agent.

Step 6: Lock egress down with the template NetworkPolicy

Our generated policy blocks private ranges and allows everything else. Print its spec to see exactly what the agent can reach.

kubectl -n agents get networkpolicy coding-agent-network-policy -o yaml | sed -n "/^spec:/,\$p"

Egress covers every IPv4 and IPv6 address outside RFC 1918, link-local and ULA space, on every port. Ingress is limited to pods labelled app: sandbox-router in agent-sandbox-system.

spec:
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.0.0.0/8
        - 172.16.0.0/12
        - 192.168.0.0/16
        - 169.254.0.0/16
    - ipBlock:
        cidr: ::/0
        except:
        - fc00::/7
        - fe80::/10
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: agent-sandbox-system
      podSelector:
        matchLabels:
          app: sandbox-router
  podSelector:
    matchLabels:
      agents.x-k8s.io/sandbox-template-ref-hash: 49ff95ab
  policyTypes:
  - Ingress
  - Egress

No DNS rule appears in it, and cluster DNS sits inside 10.0.0.0/8. The controller works around that by giving sandbox pods dnsPolicy: None with public resolvers, which we confirmed on the running pod.

kubectl -n agents get pod $P -o jsonpath="{.spec.dnsPolicy} {.spec.dnsConfig}{\"\n\"}"

A sandbox therefore resolves names through 8.8.8.8 and 1.1.1.1 and cannot resolve *.svc.cluster.local at all, which showed up as getent exit 2 in our test.

None {"nameservers":["8.8.8.8","1.1.1.1"]}

Under that default policy, https://1.1.1.1/ answered 301 and https://opencode.ai/ answered 200 from inside the sandbox. Any public port was open too, so an agent could exfiltrate over SSH, plain HTTP or a raw socket to a host it picked. We closed that in two passes, deny first and then a narrow allow, so each change could be checked on its own.

Deny all egress first

An empty egress list in a NetworkPolicy means deny all. Our patch keeps the router ingress rule, because a networkPolicy block replaces the whole generated policy, and leaving ingress out would also cut the router off.

spec:
  networkPolicy:
    ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: agent-sandbox-system
        podSelector:
          matchLabels:
            app: sandbox-router
    egress: []

Save that as ~/manifests/deny-egress.yaml and merge it into the template. Running sandboxes pick it up without a restart, since the controller rewrites the existing NetworkPolicy in place.

kubectl -n agents patch sandboxtemplate coding-agent --type merge --patch-file ~/manifests/deny-egress.yaml
kubectl -n agents get networkpolicy coding-agent-network-policy -o jsonpath="{.spec.egress}{\"\n\"}{.spec.policyTypes}{\"\n\"}"
kubectl -n agents exec $P -- curl -sS -m 5 -o /dev/null -w "%{http_code}\n" https://1.1.1.1/
kubectl -n agents exec $P -- sh -c "cd /workspace && timeout 120 opencode run \"print hello\""

Egress prints as an empty line while policyTypes still lists Egress, which is how deny-all looks. Curl failed in 0 ms and the agent could not even resolve its model endpoint.

SandboxTemplate patched to an empty egress list, curl to 1.1.1.1 port 443 refused and OpenCode failing with getaddrinfo EAI_AGAIN

Deny-all is the right state for a sandbox that runs untrusted code against a local model. OpenCode, though, retried for 100 s before printing EAI_AGAIN, so anything that calls a hosted model needs a narrow allow rule instead, or every task stalls for minutes before failing.

Allow DNS to the two resolvers and public TCP 443 only

Our second patch opens port 53 to the two resolvers the controller injected, and TCP 443 to public addresses. We also excluded 100.64.0.0/10, which the default policy misses even though carrier-grade NAT and Tailscale both use it, so a node on a tailnet would otherwise expose its peers.

spec:
  networkPolicy:
    ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: agent-sandbox-system
        podSelector:
          matchLabels:
            app: sandbox-router
    egress:
    - to:
      - ipBlock:
          cidr: 8.8.8.8/32
      - ipBlock:
          cidr: 1.1.1.1/32
      ports:
      - protocol: UDP
        port: 53
      - protocol: TCP
        port: 53
    - to:
      - ipBlock:
          cidr: 0.0.0.0/0
          except:
          - 10.0.0.0/8
          - 172.16.0.0/12
          - 192.168.0.0/16
          - 169.254.0.0/16
          - 100.64.0.0/10
      ports:
      - protocol: TCP
        port: 443

Write it to ~/manifests/allow-https-only.yaml, apply it the same way and probe four kinds of traffic.

kubectl -n agents patch sandboxtemplate coding-agent --type merge --patch-file ~/manifests/allow-https-only.yaml
kubectl -n agents exec $P -- curl -sS -m 8 -o /dev/null -w "%{http_code}\n" https://opencode.ai/
kubectl -n agents exec $P -- curl -sS -m 5 -o /dev/null -w "%{http_code}\n" http://example.com/
kubectl -n agents exec $P -- curl -sS -m 5 telnet://github.com:22
kubectl -n agents exec $P -- curl -sSk -m 5 https://10.43.0.1/version

HTTPS to the model endpoint works, while plain HTTP, SSH and the API server all fail fast.

200
curl: (7) Failed to connect to example.com port 80 after 13 ms: Could not connect to server
000
curl: (7) Failed to connect to github.com port 22 after 5 ms: Could not connect to server
curl: (7) Failed to connect to 10.43.0.1 port 443 after 0 ms: Could not connect to server

With this policy in place the agent wrote test_fizzbuzz.py, ran it and printed All assertions passed in 11 s. Blocked calls came back in 0 to 13 ms rather than hanging to a timeout. Kube-router rejects instead of dropping, so agent loops get a clean error and move on. For a tighter build, replace 0.0.0.0/0 in the 443 rule with the published ranges of your model provider.

Step 7: Reach the sandbox through the router and tighten its policy

Clients need a way into port 8888 on the sandbox, and with gVisor kubectl port-forward is not that way. The v1.0.10 release notes describe the router path as the fix for Kata and gVisor sandboxes, where Pod port-forward cannot reach the guest network stack. We reproduced the failure on an unclaimed warm pod, coding-agent-pool-b599g; any runsc sandbox pod behaves the same, so the block below uses $P.

kubectl -n agents port-forward pod/$P 18888:8888 >/tmp/pf.log 2>&1 &
curl -sS -m 5 http://127.0.0.1:18888/
kill %1
cat /tmp/pf.log
kubectl -n agents exec $P -- curl -sS -m 5 http://127.0.0.1:8888/

Port-forward accepts the local connection, then dials port 8888 on loopback in the host-side network namespace of the pod. Nothing listens there, because the runtime server lives inside the network stack of the Sentry. Run from inside the sandbox, the same URL answers.

kubectl port-forward to a gVisor sandbox pod returning Empty reply and connection refused while in-pod curl to port 8888 works

Upstream keeps the router as a kustomize directory in the repository. Pin its image to the controller tag so the two always move together. Its default NetworkPolicy also needs a patch, for a reason the next test shows, and that patch needs your API server endpoint.

kubectl get endpointslice -n default -l kubernetes.io/service-name=kubernetes

On a single-node K3s server the endpoint is the node IP on 6443. An HA control plane returns one address per server, and each needs its own ipBlock.

NAME         ADDRESSTYPE   PORTS   ENDPOINTS     AGE
kubernetes   IPv4          6443    10.0.1.50     11m

Create a kustomization that pulls the upstream router, pins the image and replaces the fourth egress rule.

mkdir -p ~/manifests/router
vim ~/manifests/router/kustomization.yaml

Set cidr to the endpoint from the previous command, and keep both v1.0.10 pins equal to $AS_VERSION.

# https://github.com/kubernetes-sigs/agent-sandbox/releases/tag/v1.0.10
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- https://github.com/kubernetes-sigs/agent-sandbox//sandbox-router/deploy?ref=v1.0.10
images:
- name: registry.k8s.io/agent-sandbox/sandbox-router-go
  newTag: v1.0.10
patches:
- target:
    kind: NetworkPolicy
    name: sandbox-router
  patch: |-
    - op: replace
      path: /spec/egress/3
      value:
        to:
        - ipBlock:
            cidr: 10.0.1.50/32
        ports:
        - protocol: TCP
          port: 6443

We first applied the directory without the patches block to measure the shipped policy. Its fourth egress rule allows TCP 443 and 6443 to any destination, and the router honours an X-Sandbox-Pod-IP header naming the address to dial while it runs with authz allow-all. Through that header, a client in the cluster reached 1.1.1.1 on 443 (HTTP 400 from the target) and the API server on 6443 (Client sent an HTTP request to an HTTPS server.). Unpatched, then, the router works as a TCP proxy to the internet for any pod that can reach its Service.

Helm users get the same fix through networkPolicy.apiServerCIDRs, which is empty by default. The lab installed the router with kustomize, so the JSON patch above on egress[3] stood in for that value, and the Helm route itself was not run here. With kustomize, apply the patched directory, restart the router and repeat the probes from a client pod.

kubectl apply -k ~/manifests/router
kubectl -n agent-sandbox-system rollout restart deploy/sandbox-router
kubectl -n agent-sandbox-system rollout status deploy/sandbox-router --timeout=120s
kubectl run client --image=curlimages/curl:8.17.0 --restart=Never --command -- tail -f /dev/null
kubectl wait --for=condition=Ready pod/client --timeout=90s
R=http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080/
for t in 1.1.1.1:443 10.0.1.50:6443; do printf "%s -> " $t; kubectl exec client -- curl -s -m 10 -o /dev/null -w "%{http_code}\n" -H "X-Sandbox-ID: $P" -H "X-Sandbox-Namespace: agents" -H "X-Sandbox-Pod-IP: ${t%:*}" -H "X-Sandbox-Port: ${t#*:}" $R; done
kubectl exec client -- curl -sS -m 10 -H "X-Sandbox-ID: $P" -H "X-Sandbox-Namespace: agents" $R

Now the internet target returns 502 because the router cannot dial it. The API server stays reachable for the pod cache of the router, and the sandbox still answers through the router.

sandbox-router NetworkPolicy egress rule limited to the API server /32 on 6443, router to 1.1.1.1:443 now 502 and the sandbox still reachable

After the restart the router logged pod cache synced with 3 entries and served the request in 6 ms, so dropping 443 to any address did not break its watch on K3s. On kube-router the node IP /32 alone was enough. Upstream notes that a CNI evaluating policy before that rewrite matches the ClusterIP instead (10.43.0.1 on K3s), so list both peers on Cilium-style dataplanes.

Two gaps remain after this patch, and we did not close them in the lab. The shipped policy keeps a port-only egress rule for UDP and TCP 53 to any address, and with allow-all the caller picks the port through X-Sandbox-Port, so the router can still reach DNS servers anywhere. Its ingress rule also admits port 8080 from every namespace, and NetworkPolicies are additive, so a second policy cannot narrow it. The upstream networkpolicy.yaml recommends tightening that from: namespaceSelector in place and switching --authz-mode to tokenreview or scoped-token, which is the change to make before the router serves more than one team. Neither mode is a flag flip alone: tokenreview also needs the rbac-tokenreview.yaml from the deploy directory, and scoped tokens come as a separate overlay, both described in the router deploy README.

Step 8: Size the warm pool from measured claim latency

One script timed both warm and cold claims, so both paths pay the same kubectl overhead. It waits for the pool to be full, creates a claim, waits for Ready, prints the milliseconds and deletes the claim.

#!/bin/bash
# claim-latency.sh <label> <runs>: create SandboxClaims against coding-agent-pool, time apply -> Ready
label=$1; runs=${2:-5}
for i in $(seq 1 "$runs"); do
  until [ "$(kubectl -n agents get sandboxwarmpool coding-agent-pool -o jsonpath='{.status.readyReplicas}')" = \
          "$(kubectl -n agents get sandboxwarmpool coding-agent-pool -o jsonpath='{.spec.replicas}')" ]; do sleep 1; done
  name="$label-$i"
  t0=$(date +%s%N)
  printf 'apiVersion: extensions.agents.x-k8s.io/v1beta1\nkind: SandboxClaim\nmetadata:\n  name: %s\n  namespace: agents\nspec:\n  warmPoolRef:\n    name: coding-agent-pool\n' "$name" | kubectl create -f - >/dev/null
  kubectl -n agents wait --for=condition=Ready "sandboxclaim/$name" --timeout=120s >/dev/null
  t1=$(date +%s%N)
  sb=$(kubectl -n agents get sandboxclaim "$name" -o jsonpath='{.status.sandbox.name}')
  echo "$name sandbox=$sb ms=$(( (t1 - t0) / 1000000 ))"
  kubectl -n agents delete sandboxclaim "$name" --wait=true >/dev/null
done

Save it as ~/manifests/claim-latency.sh and make it executable with chmod +x ~/manifests/claim-latency.sh. The cold variant, ~/manifests/claim-latency-cold.sh, patches the pool to replicas: 0 first, so every claim makes the controller start a fresh gVisor pod, and it restores 2 replicas at the end.

#!/bin/bash
# claim-latency-cold.sh <runs>: pool at replicas 0, each claim provisions a fresh gVisor pod
runs=${1:-5}
kubectl -n agents patch sandboxwarmpool coding-agent-pool --type merge -p '{"spec":{"replicas":0}}' >/dev/null
until [ -z "$(kubectl -n agents get sandbox -l agents.x-k8s.io/warm-pool-sandbox -o name)" ]; do sleep 1; done
for i in $(seq 1 "$runs"); do
  name="cold-$i"
  t0=$(date +%s%N)
  printf 'apiVersion: extensions.agents.x-k8s.io/v1beta1\nkind: SandboxClaim\nmetadata:\n  name: %s\n  namespace: agents\nspec:\n  warmPoolRef:\n    name: coding-agent-pool\n' "$name" | kubectl create -f - >/dev/null
  kubectl -n agents wait --for=condition=Ready "sandboxclaim/$name" --timeout=180s >/dev/null
  t1=$(date +%s%N)
  sb=$(kubectl -n agents get sandboxclaim "$name" -o jsonpath='{.status.sandbox.name}')
  echo "$name sandbox=$sb ms=$(( (t1 - t0) / 1000000 ))"
  kubectl -n agents delete sandboxclaim "$name" --wait=true >/dev/null
  until [ -z "$(kubectl -n agents get pod -o name | grep "$sb")" ]; do sleep 1; done
done
kubectl -n agents patch sandboxwarmpool coding-agent-pool --type merge -p '{"spec":{"replicas":2}}' >/dev/null

After a chmod +x on that one too, we ran ~/manifests/claim-latency.sh warm 10 and ~/manifests/claim-latency-cold.sh 5, then repeated both after setting the probe period to 1 s with a JSON patch.

- op: add
  path: /spec/podTemplate/spec/containers/0/readinessProbe/periodSeconds
  value: 1

Saved as ~/manifests/probe-period.yaml, it goes in with kubectl -n agents patch sandboxtemplate coding-agent --type json --patch-file ~/manifests/probe-period.yaml. Here are the three runs side by side.

SandboxWarmPool claim latency: warm claims 514 to 642 ms, cold claims about 11.4 s, cold claims 2.2 to 3.2 s after readiness periodSeconds 1

Conditions on one cold pod explain the 11.4 s. Kubernetes scheduled it and started the container 1 s after creation, but Ready flipped 11 s after that. With a 10 s period, a first probe that lands before the server listens leaves the pod unready until the next one. So the tuned cold median of 2.88 s is what scheduling, the gVisor boot and the runtime server cost together once the probe stops adding its own wait.

Those numbers turn sizing into arithmetic. Three inputs decide it.

  • Refill window. Set replicas to the claims you expect inside one refill, about 3 s with the tuned probe and about 12 s with the default.
  • Requests, not idle use. Each warm pod used 56 Mi and 15 to 24 m CPU at rest, but the scheduler reserves its full 512 Mi and 250 m.
  • Node ceiling. On this 4 vCPU node, CPU requests cap the pool at 16 sandboxes before memory runs out, minus what K3s system pods already hold. A RuntimeClass with overhead.podFixed adds to every pod; the 64 Mi and 100 m in our runtime guide would drop that ceiling to about 11.

Tune the probe before you grow the pool. A shorter period shrinks the refill window by a factor of four, so the same burst needs a quarter of the warm replicas and a quarter of the reserved memory.

Errors we hit in the lab

Each of these came from the runs above, quoted with the exact text the tools printed.

“failed to connect to localhost:8888 inside namespace … connect: connection refused”

Running kubectl port-forward against a gVisor pod gives the client curl: (52) Empty reply from server, and the forwarder logs dial tcp4 127.0.0.1:8888: connect: connection refused. With runsc that is expected behaviour, not a broken app. Test from inside the pod with kubectl exec, and give clients the router path from Step 7.

“Error: getaddrinfo EAI_AGAIN opencode.ai”

OpenCode printed this after 100 s of retries once egress was empty, because port 53 to the injected resolvers was gone too. If DNS fails when you meant to allow it, check that your allow rule names 8.8.8.8/32 and 1.1.1.1/32 on UDP and TCP 53. An allow to cluster DNS does nothing while the pod runs with dnsPolicy: None, so that rule is a common dead end.

getent hosts kubernetes.default.svc.cluster.local exits 2

Service names do not resolve in a sandbox even under the default policy, since the controller points DNS at public resolvers. Code that expects to call an in-cluster service by name fails here by design. Expose that service through a public endpoint or an explicit egress rule to its ClusterIP, and accept that you just widened the boundary.

Error from server (NotFound): deployments.apps “sandbox-router-deployment” not found

Upstream names the router deployment sandbox-router and its Service sandbox-router-svc, so rollout status on any other name fails. Run kubectl -n agent-sandbox-system get deploy to read the real name before scripting against it.

“permission requested: external_directory (/tmp/*); auto-rejecting”

Because opencode run has no human to approve prompts, it rejects tool calls outside the working directory, here a write to /tmp. Treat that as a useful second fence, not a sandbox fault. Keep tasks inside /workspace, or widen the OpenCode permissions in its config if a task really needs another path.

Step 9: Clean up the lab

Delete in reverse order of creation, so the pool does not refill sandboxes while you remove the template behind it.

kubectl -n agents delete sandboxclaim --all
kubectl -n agents delete sandboxwarmpool coding-agent-pool
kubectl -n agents delete sandboxtemplate coding-agent
kubectl delete namespace agents
kubectl delete pod client
kubectl delete -k ~/manifests/router
kubectl delete -f https://github.com/kubernetes-sigs/agent-sandbox/releases/download/${AS_VERSION}/sandbox-with-extensions.yaml
kubectl get crd | grep agents.x-k8s.io || echo "no agent-sandbox CRDs left"

Our last line printed no agent-sandbox CRDs left, and the generated NetworkPolicy went with the namespace. Remove the OpenCode image with sudo k3s crictl rmi opencode-sandbox:v1 to recover its 628 MB.

What to watch in the controller metrics

Prometheus metrics come from the controller Service on port 8080, and one histogram answers the sizing question in production. We read it from a throwaway curl pod after all the timed runs.

kubectl run metrics-probe -n default --rm -i --restart=Never --image=curlimages/curl:8.17.0 --quiet -- curl -s http://agent-sandbox-controller.agent-sandbox-system:8080/metrics | grep -E "^agent_sandbox_claim_controller_startup_latency_ms_(sum|count)"

A launch_type label splits claims served from the pool from claims that started a pod.

agent_sandbox_claim_controller_startup_latency_ms_sum{launch_type="cold",sandbox_template="coding-agent"} 80523
agent_sandbox_claim_controller_startup_latency_ms_count{launch_type="cold",sandbox_template="coding-agent"} 11
agent_sandbox_claim_controller_startup_latency_ms_sum{launch_type="warm",sandbox_template="coding-agent"} 660
agent_sandbox_claim_controller_startup_latency_ms_count{launch_type="warm",sandbox_template="coding-agent"} 16

Warm claims averaged 41 ms inside the controller, and the 11 cold ones averaged 7.3 s across the default and tuned probe runs. Alert on the rate of launch_type="cold" rather than on latency, because a non-zero cold rate means the pool ran dry and users waited seconds instead of milliseconds. When it climbs, raise replicas or shorten the probe period before anyone reports it. Watch the cold buckets as well, since a regression in image start time shows up there long before a user notices.

For a node layout that spreads these pools over more than one machine, our 3-node Kubernetes home cluster build is a good base. If a full kernel per agent suits you better than a user-space one, the Hyperlight micro-VM walkthrough measures that trade from the other side.

Keep reading

Best UI Applications for Managing Docker Containers Containers Best UI Applications for Managing Docker Containers Install Docker and Run Containers on Ubuntu 24.04|22.04 Containers Install Docker and Run Containers on Ubuntu 24.04|22.04 Install UniFi OS Server on Ubuntu 26.04 / 24.04 LTS Containers Install UniFi OS Server on Ubuntu 26.04 / 24.04 LTS Traefik 3.8 Upgrade: Breaking Changes, Yaegi v2 and Helm Test Containers Traefik 3.8 Upgrade: Breaking Changes, Yaegi v2 and Helm Test magpie: One AI Gateway for Claude Code and Codex on Linux AI magpie: One AI Gateway for Claude Code and Codex on Linux Grant Users Access to Project/Namespace in OpenShift Openshift Grant Users Access to Project/Namespace in OpenShift

Leave a Comment

Press ESC to close