Putting an AI agent inside a Docker container or Kubernetes Deployment does not make it sandboxed. By default, a Kubernetes pod mounts a service-account token at /var/run/secrets/kubernetes.io/serviceaccount, can reach the cloud instance metadata service (169.254.169.254), can open outbound TCP connections to any public IP on the internet, and runs with a writable filesystem and broad Linux capabilities. When an agent processes untrusted documents, runs generated code, or invokes local stdio MCP servers, that default container becomes a direct pivot into your cluster.

This guide gives platform and security engineers concrete, copy-pasteable Kubernetes and Docker hardening manifests for autonomous AI agents — and draws a clear line between what container isolation stops and what still requires application-level agent governance.

What container sandboxing stops — and what it misses

A common architectural mistake is assuming that running agents inside isolated containers solves AI agent security end to end. Infrastructure isolation and runtime agent governance protect different layers:

Threat vector Stopped by Kubernetes / Docker hardening? Stopped by runtime agent governance (gateway + policy)?
Host filesystem escape & root privilege escalation Yes — non-root UID, dropped capabilities, gVisor / Kata runtimeClass Out of scope (OS/kernel layer)
Cloud metadata SSRF (169.254.169.254) & cluster lateral movement Yes — default-deny egress NetworkPolicy + disabled SA token mount Reinforced by gateway SSRF URL validation
Malicious package / shell exfiltration to arbitrary internet IPs Yes — egress restricted solely to approved gateway/proxy endpoints Out of scope for raw socket traffic outside gateway
Prompt injection calling a legitimately allowed MCP tool with malicious arguments No — traffic travels over the permitted HTTPS egress path Yes — argument-level tool rules, intent checks, and human approvals
PII / secret leakage inside model prompts or tool outputs No — payload is encrypted inside valid HTTPS requests Yes — bidirectional content and PII redaction guardrails
Runaway agent loops burning thousands in LLM API fees No — pod stays within CPU/RAM limits while spending API tokens Yes — per-agent spend budgets and per-tool rate limits
Tamper-evident proof of why an action was allowed or denied No — container stdout logs are mutable application logs Yes — append-only, hash-chained decision logs for governed calls

1. Hardened Kubernetes Pod SecurityContext for agent workloads

For any pod running an AI agent framework (LangGraph, Google ADK, OpenAI Agents SDK, CrewAI) or a local stdio MCP server, start with zero mounted Kubernetes API credentials, a read-only root filesystem, a dedicated microVM or user-space kernel (gvisor or kata when executing generated code), and zero Linux capabilities:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: support-triage-agent
  namespace: ai-agents
spec:
  replicas: 2
  selector:
    matchLabels:
      app: support-triage-agent
  template:
    metadata:
      labels:
        app: support-triage-agent
        tier: agent-runtime
    spec:
      # Never mount the cluster service-account token into an agent pod
      automountServiceAccountToken: false
      # Use gVisor or Kata Containers whenever the agent executes code or stdio tools
      runtimeClassName: gvisor
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        fsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: agent
          image: registry.internal.example/agents/support-triage:1.4.2@sha256:REPLACE_WITH_DIGEST
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          env:
            # Scoped runtime gateway key only — never mount raw DB or SaaS admin tokens
            - name: PRAESIDIA_GATEWAY_ORIGIN
              value: "https://router.praesidia.ai"
            - name: PRAESIDIA_APPLICATION_KEY
              valueFrom:
                secretKeyRef:
                  name: support-triage-runtime-key
                  key: token
          volumeMounts:
            - name: scratch
              mountPath: /tmp
          resources:
            limits:
              cpu: "1"
              memory: "1Gi"
              ephemeral-storage: "256Mi"
      volumes:
        - name: scratch
          emptyDir:
            sizeLimit: "128Mi"

Notice two high-leverage details in the manifest above:

  • Pin images by SHA-256 digest rather than mutable :latest tags so a compromised upstream agent or MCP container image cannot roll out silently.
  • Keep raw downstream secrets out of the pod. Inject only a single scoped, revocable runtime credential (pra_…) that authenticates to your model and MCP gateways; keep upstream database, CRM, and LLM provider keys inside the gateway so a compromised agent container cannot read them from /proc/self/environ.

2. Default-deny Kubernetes NetworkPolicy (block metadata & lateral egress)

Indirect prompt injection often attempts to exfiltrate data by persuading an agent to fetch an attacker-controlled URL (https://evil.example/?leak=...) or query the cloud metadata service (169.254.169.254). Enforce a default-deny egress NetworkPolicy that permits only cluster DNS and your explicit egress proxy or gateway CIDR:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: agent-default-deny-egress
  namespace: ai-agents
spec:
  podSelector:
    matchLabels:
      tier: agent-runtime
  policyTypes:
    - Ingress
    - Egress
  ingress: []
  egress:
    # Allow DNS resolution inside the cluster
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    # Allow HTTPS only to your managed egress proxy / AI & MCP gateway subnet
    - to:
        - ipBlock:
            cidr: 10.42.10.0/24
      ports:
        - protocol: TCP
          port: 443

If your cluster uses Cilium or Envoy-based FQDN egress policies, restrict outbound TLS explicitly to your model gateway (router.praesidia.ai) and approved internal API hosts so a hijacked agent cannot exfiltrate data to arbitrary domains even over port 443.

3. Hardening local Docker runs for MCP servers and coding agents

When developers test MCP servers or coding agents locally in Docker, avoid bare docker run -v /:/host or --network host flags. Use a minimal hardened invocation:

docker run --rm \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --cap-drop=ALL \
  --security-opt=no-new-privileges:true \
  --user 10001:10001 \
  --pids-limit=128 \
  --memory=512m \
  --cpus=1.0 \
  --network=agent-egress-only \
  registry.internal.example/mcp/readonly-docs@sha256:REPLACE_WITH_DIGEST

Before deploying any MCP client or server container config, scan it locally in your browser with the MCP config security checker to flag shell-wrapper args, hardcoded tokens, and SSRF targets before runtime.

4. Closing the layer above the container

Once the container and network perimeter are locked down, every remaining high-impact agent failure happens inside legitimate HTTPS calls to LLMs and MCP servers. Pair your hardened Kubernetes pods with:

  1. Governed model & MCP gateways: Route LLM traffic through the model gateway for hard spend caps and bidirectional guardrails, and route tool traffic through the Praesidia MCP gateway for per-connection tool allow-lists and rate limits.
  2. Instant revocation & kill switches: Enroll each agent environment with its own revocable credential so an incident cuts one agent without redeploying the entire namespace — see runtime installation and credentials and runtime security controls.
  3. Deployment residency & architecture fit: Review managed and dedicated deployment topologies on the deployment options page and evaluate your full agent risk posture with the OWASP Agentic Top 10 readiness scorecard.

Common questions

Is a standard Docker container enough to sandbox an AI agent that executes untrusted code? No. Standard containers share the host Linux kernel; an agent running untrusted generated code or shell commands should use stronger kernel isolation such as gVisor (runsc), Kata Containers, or Firecracker microVMs, paired with --cap-drop=ALL, --read-only, and strict egress controls.

Why must automountServiceAccountToken: false be set on Kubernetes agent pods? By default, Kubernetes mounts a service-account JWT inside every pod. If an agent suffers from indirect prompt injection, path traversal, or a tool-execution bug, an attacker can read that token and query the Kubernetes API server directly.

Can Kubernetes NetworkPolicy stop indirect prompt-injection data exfiltration? A strict egress NetworkPolicy stops exfiltration to arbitrary attacker domains and blocks cloud metadata SSRF, which dramatically narrows the attack surface. However, it cannot stop exfiltration sent through an allowed destination (such as a connected email or CRM MCP tool) — that requires argument-level policy and output guardrails on the MCP and model gateway layer.

Should upstream LLM and SaaS API keys be stored as Kubernetes Secrets inside the agent pod? Keep raw provider and SaaS admin credentials out of the agent pod whenever possible. Instead, hold upstream credentials in your model and MCP gateways and issue the agent pod a single scoped, revocable runtime credential (pra_…).