Docker and Kubernetes for Agents

Agent runs are long, uneven and sometimes risky. Containers and an orchestrator help only if you design for all three.

BeginnerIntermediateExpert · 16 min read · Last updated:

In short

Put the agent's code and its pinned dependencies in a small container image, keep state outside the container, and run separate workloads for the API, the workers and any code execution. On Kubernetes, give workers time to stop cleanly, set resource requests from measurements, scale on waiting work and isolate anything that runs generated code.

What you will learn: how to build a safe image, which Kubernetes objects suit which part of an agent system, how to handle termination during long runs, how probes, resources, scaling, networking and sandboxes work together, and when a cluster is more than you need.
Prerequisites: Deploying Agents to Production and basic command-line use. Prior Kubernetes experience helps in the expert section.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library. It simulates a termination request with ticks of a pretend clock. The Dockerfile and YAML fragments are illustrative: they were not built or applied to a cluster, so check them against the current documentation for your versions.

Beginner Containers and what goes in them

Why containers for agents

A container image is a packaged filesystem holding your code, a language runtime and libraries. A container is a running instance of that image. The same image runs on a laptop, a test server and production, which removes a whole family of problems where an agent behaves differently because one machine has another library version.

That matters more for agents than for many web services. A change in a client library can alter how a tool result is serialized, which changes what the model reads, which changes behavior. If the image is identical in testing and production, your evaluation results describe the thing you actually ship.

Sourcecode and lock file
Imagebuilt once
Registrystored by digest
Runsame bytes everywhere

What a container does not give you is strong isolation from hostile code. Ordinary containers share the host's kernel. That is fine for your own service and not enough for code that a model wrote from untrusted input; see the sandbox section below and Code Execution and Sandboxing.

Building a good image

Aim for an image that is small, reproducible and boring. This fragment shows the usual shape for a Python worker:

# build stage: compile and install dependencies
FROM python:3.13-slim AS build
WORKDIR /app
COPY requirements.lock .
RUN pip install --require-hashes --prefix=/install -r requirements.lock

# runtime stage: only what is needed to run
FROM python:3.13-slim
COPY --from=build /install /usr/local
WORKDIR /app
COPY src/ ./src/
RUN useradd --system --uid 10001 agent
USER 10001
CMD ["python", "-m", "src.worker"]
HabitWhy it helps
Pin the base image, ideally by digestA rebuild does not silently change the runtime
Lock dependencies with hashesThe same packages are installed every time
Use a separate build stageCompilers and caches stay out of the shipped image
Run as a non-root userA compromised process can do less
Keep a .dockerignore fileLocal secrets and test data are not copied in by accident
Start the program directly, in list formThe process receives stop signals itself instead of a shell wrapper
Scan the image and rebuild regularlyFixed library flaws only help after a rebuild

Pinning and patching pull against each other. A pinned image is predictable but ages. Solve it with automation that proposes updates, runs your tests and lets a person merge them, rather than by using a floating tag.

What stays outside the image

An image should be safe to copy to anyone who may read your registry. Three things therefore stay out:

1. Secretskeys and tokens arrive at run time from a secret store
2. Configurationmodel names, limits and addresses differ by environment
3. Statetask progress, memory and files live in external stores

Anything written inside a running container disappears when it is replaced, and replacement is routine: releases, node maintenance, scaling down and crashes all do it. If losing the container would lose a user's work, the work is in the wrong place. Serverless, Streaming APIs, Queues and State covers the stores and queues that hold it.

Prompts are a judgment call. Keeping them in the image ties them to a tested release. Fetching them from a prompt registry lets people change them faster. If you fetch them, record the version used on every run and apply the same tests before a new version becomes live (Versioning, Registries and Evaluation-Driven Development).

Intermediate Running agents on Kubernetes

Match each part to a workload type

Kubernetes keeps a declared state: you describe what should run, and controllers work to make it so. A pod is the smallest unit it runs, usually one main container. Different parts of an agent system suit different objects:

Part of the systemTypical objectReason
Chat or task APIDeployment with a ServiceInterchangeable copies behind one address
Queue workersDeployment, or Jobs created per itemLong running pool, or one short-lived pod per task
Scheduled maintenanceCronJobIndex refresh, cleanup and report runs
Self-hosted storesStatefulSet, or a managed serviceStable identity and disks, with real operating effort
Model server on acceleratorsDeployment on a dedicated node poolSpecial hardware, slow start, separate scaling
Generated codeIsolated sandbox podsDifferent trust level from your own code

Splitting these apart is the most useful decision on this page. The API can scale with connected users, workers with waiting tasks and the model server with token demand. It also lets you give each group its own network rules and credentials.

A reference layout

Entryload balancer, TLS and authentication
API podsaccept tasks, stream progress, no long work
Queue and state storeoutside the pods, often managed services
Worker podsrun the agent loop and save progress
Gateways and sandboxesmodel and tool access, isolated code execution

Put each trust level in its own namespace: one for platform services, one per environment or team for agents and one for sandboxes. A namespace by itself is an organizing boundary, not a security wall. It becomes useful when you attach access rules, network policies and resource quotas to it.

The gateways deserve their place in the middle. A model gateway holds provider keys, applies quotas and records usage (Model Routing, Fallbacks and Gateways). A tool gateway checks permissions before an action reaches a real system (Action Guardrails and Policy Engines). Workers then need no direct credentials for either.

Stopping cleanly during long runs

A web request lasts milliseconds, so replacing a web pod is easy. An agent task can run for minutes, so replacement will often interrupt one. When Kubernetes terminates a pod, it asks the containers to stop with a TERM signal, waits for a grace period and then forces the remaining processes to end. The documented default is 30 seconds, which is shorter than many agent runs.

A worker therefore needs a rule for what to do when asked to stop:

  1. Stop taking new tasks immediately.
  2. Finish the current step if it fits inside the grace period.
  3. Save progress and hand the task back so another worker can continue.
  4. Exit before the deadline, so the exit is yours and not a forced kill.

The example compares a worker that simply keeps going with one that saves after each step:

"""A worker that finishes or hands back its task when asked to stop (invented tasks)."""


class Queue:
    def __init__(self, tasks):
        self.waiting = list(tasks)          # (name, steps)
        self.progress = {}                  # name -> steps already saved
        self.done = []


def run_worker(queue, stop_at, grace, checkpoint=True):
    """Work one step per tick. At stop_at the platform asks us to terminate."""
    clock, log = 0, []
    while queue.waiting:
        if clock >= stop_at:
            log.append(f"t={clock}: stop requested, taking no new task")
            break
        name, steps = queue.waiting.pop(0)
        completed = queue.progress.get(name, 0)
        while completed < steps:
            if clock >= stop_at + grace:
                log.append(f"t={clock}: killed during {name}")
                return log
            if clock >= stop_at and checkpoint:
                queue.waiting.insert(0, (name, steps))
                log.append(f"t={clock}: returned {name} at step {completed}/{steps}")
                return log
            clock += 1
            completed += 1
            if checkpoint:
                queue.progress[name] = completed
        queue.done.append(name)
        log.append(f"t={clock}: finished {name}")
    return log


if __name__ == "__main__":
    for checkpoint in (False, True):
        q = Queue([("report", 4), ("research", 9), ("email", 2)])
        print("with checkpoints" if checkpoint else "without checkpoints")
        for line in run_worker(q, stop_at=6, grace=3, checkpoint=checkpoint):
            print("  " + line)
        print("  saved progress:", q.progress or "none")
        print("  still queued:  ", [n for n, _ in q.waiting])

Output:

without checkpoints
  t=4: finished report
  t=9: killed during research
  saved progress: none
  still queued:   ['email']
with checkpoints
  t=4: finished report
  t=6: returned research at step 2/9
  saved progress: {'report': 4, 'research': 2}
  still queued:   ['research', 'email']

Without saved progress, the long task is killed and nothing records where it was. In this toy queue the task is removed as soon as a worker takes it, so it is also lost; a real queue that waits for an acknowledgment would deliver it again, and the work would restart from the beginning, repeating any actions already taken. With saved progress, the worker returns the task after the current step and the next worker can start at step 2.

Repeated actions

A kill can happen between performing an action and recording it. Saved progress reduces repetition but cannot remove it. Actions that change real systems need an idempotency key or a check before retrying. See Reliable Tool Execution and Error Recovery and Durable Execution, Checkpoints and Approvals.

The matching settings look like this. Choose the grace period from your longest single step, not your longest task:

spec:
  terminationGracePeriodSeconds: 120
  automountServiceAccountToken: false
  containers:
    - name: worker
      image: registry.example.com/agent-worker@sha256:REPLACE_ME
      resources:
        requests: { cpu: "250m", memory: "512Mi" }
        limits: { memory: "1Gi" }
      securityContext:
        runAsNonRoot: true
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities: { drop: ["ALL"] }

If a program is started through a shell script, check that the signal reaches it. A common surprise is a worker that never notices the request, runs until it is killed and appears to fail at random during releases. Test it: stop a pod while a task is running and read what happened.

Health probes that tell the truth

Probes let the cluster decide whether to restart a container or send it traffic.

ProbeQuestionAgent advice
StartupHas it finished starting?Allow generous time for model weights or large indexes
ReadinessShould it receive work now?Report not ready while draining or missing essential configuration
LivenessIs it stuck beyond recovery?Check only the process itself, never an external provider

The liveness rule prevents a bad cascade. If every worker's liveness check calls the model provider, a provider outage makes the cluster restart every worker, throwing away work in progress and adding load when the provider returns. Report dependency trouble through metrics and circuit breakers instead (What to Measure: Metrics, Dashboards and SLOs).

A worker waiting thirty seconds for a model reply is healthy. Make sure the liveness check is served independently of the task loop, or measure a heartbeat that advances during waits.

Resource requests and limits

A request is what the scheduler reserves when placing a pod. A limit is the most the container may use. Exceeding a memory limit gets the process killed. Exceeding a CPU limit slows it down.

Agent workers often spend most of their time waiting for models and tools, so CPU use is low while memory grows with context, documents and retrieved results. Measure a realistic run before choosing numbers:

SymptomLikely causeDirection
Pods killed for memoryLarge inputs or many concurrent tasks per podCap input size, lower concurrency, then raise the limit
Cluster full but idleRequests far above real useLower requests to a high percentile of observed use
Slow parsing or rankingCPU throttlingRaise or remove the CPU limit and watch neighbors
Pods pendingNo node satisfies the request or the hardware labelAdjust requests or node pools

Set a resource quota per namespace so one team's runaway scale-out cannot consume the cluster. Remember that the cluster may be able to start far more workers than your model provider allows you to use; see Scaling, Hardware, Quotas and Caching.

Expert Scaling, isolation and operating the cluster

Scale on waiting work

Scaling on CPU use suits services that are busy computing. A worker blocked on a model call looks idle even with a long queue. Better signals are the number of waiting tasks, the age of the oldest task and the number of tasks in progress.

KEDA is an add-on for event-driven scaling. It can scale a workload from an external signal such as queue length, scale it down to zero, work alongside the Kubernetes horizontal autoscaler and create Jobs for individual items through its ScaledJob resource.

PatternGood forWatch out for
Warm worker poolMany short or medium tasksScale-down interrupting work
One Job per taskLong, heavy or isolated tasksStart-up delay and many finished objects to clean
Scale to zeroRare, patient workloadsThe first task waits for a cold start

Always set a maximum. It should come from the smallest downstream limit: provider quota, database connections or a tool's own rate limit. More workers past that point only create more rejected calls. Give scale-down a delay so a brief lull does not remove workers you need a minute later.

Surviving planned and unplanned disruption

Nodes are drained for upgrades and removed to save money. Several settings reduce the effect:

  • Run at least two API replicas spread across nodes or zones.
  • Use a PodDisruptionBudget to limit how many pods voluntary maintenance may remove at once. It does not protect against hardware failure.
  • Keep interruptible, cheaper capacity for work that saves progress often, and steady capacity for the API and gateways.
  • Make rollouts gradual, and keep old workers running until their current steps finish.
  • Version saved task state, so a new worker can read what an old one wrote.

That last point is easy to miss. During every rollout, old and new versions run together. A new field in the checkpoint must be optional until every old worker is gone.

Network and identity

By default, pods in a cluster can usually reach each other. Add network policies that deny traffic first and then allow named paths: workers to the queue, the state store and the gateways, and nothing else. Network policies take effect only if the cluster's networking plug-in enforces them, so test with a connection that should fail.

ControlPractice
Service identityOne service account per workload with only the rights it needs
Cluster tokenDo not mount it in pods that never call the cluster interface
Cloud accessUse workload identity instead of long-lived keys
SecretsKubernetes Secrets are not encrypted at rest unless configured; consider an external secret manager
Outbound trafficAllow listed destinations, which limits data theft after a prompt injection
Pod hardeningApply a restricted pod security profile and an image policy

An agent that reads untrusted content can be persuaded to attempt things its authors never intended. Network and identity limits hold even when the model is fooled, which is why they belong outside the prompt (Prompt Injection Attacks and Defenses).

Sandboxes for generated code

Running model-written code in a normal pod next to your services is a serious risk. Stronger isolation uses a runtime that adds a barrier between the container and the host kernel, such as gVisor or Kata Containers, together with no credentials, no cluster token, tight network rules, resource caps and a short lifetime.

The Kubernetes community is building a dedicated abstraction for this. In March 2026 the project blog described Agent Sandbox, developed under SIG Apps, with a Sandbox resource for single, stateful agent runtimes and support for isolation runtimes such as gVisor and Kata. It was described as early development, and its documentation lists Kubernetes 1.25 or later. Check its current maturity before depending on it.

Whatever you use, test the boundary: from inside a sandbox, try to read the cloud metadata address, reach an internal service and write outside the working directory. Each attempt should fail.

When you do not need a cluster

Kubernetes rewards teams that already run it. For one small agent, it can add more operating work than value.

SituationOften a better fit
One service, spiky and light trafficServerless containers or functions (Serverless, Streaming APIs, Queues and State)
Want sessions and isolation providedA managed agent runtime (Managed vs Custom Platforms and Total Cost)
Many services, shared platform teamKubernetes
Self-hosted models on acceleratorsKubernetes or a managed model service (NVIDIA, vLLM and GPU Sizing)
Strict on-premises or portability needsKubernetes, with the staff to run it

Containers remain worthwhile in every row, because most of these options accept an image.

Common mistakes

MistakeBetter approach
Keeping task state in container memory or diskSave progress to an external store
Leaving the default grace period for long stepsMeasure the longest step and handle the stop signal
Liveness checks that call a modelCheck only the local process
Autoscaling workers on CPU aloneUse queue depth and age with a maximum
Running generated code beside the serviceUse isolated sandboxes without credentials
Deploying a floating image tagDeploy a digest you tested

Checklist

  • Images are pinned, scanned, non-root and free of secrets.
  • API, workers, model serving and sandboxes are separate workloads.
  • Workers stop taking tasks, save progress and exit within the grace period.
  • A pod has been stopped mid-task in testing and the task completed correctly.
  • Probes never depend on an outside provider for liveness.
  • Requests come from measurements and namespaces have quotas.
  • Network policies deny by default and have been tested.
  • Autoscaling has a maximum tied to downstream limits.

Frequently asked questions

Should each agent run in its own container?

Not necessarily; separate containers by scaling, security and release needs, and share a worker when those match.

How long should the termination grace period be?

Long enough to finish and save the longest single step, with a margin, while longer tasks resume from saved progress.

Can model weights go inside the image?

They can, but large images start slowly, so many teams load weights from fast storage or a node cache and pin their version.

Is a container a sufficient sandbox?

Not for untrusted code; add a stronger isolation runtime, remove credentials, restrict the network and limit lifetime.

References and further reading

Next steps