Join our Newsletter — 33% off our NHI Course
Home› Guides› Containers vs Serverless Security: Attack Surface, Identity and…
Guide Cloud Security

Containers vs Serverless Security: Attack Surface, Identity and Runtime Controls Compared

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 13 November 2026 13 min read
On this page

Containers and serverless functions move different parts of the security job to the cloud provider, and teams that secure one as if it were the other leave predictable gaps. With containers, you own the image, the runtime configuration, much of the orchestrator and often the node. With serverless functions, the provider owns the host, the runtime patching and the isolation boundary, and your risk concentrates in code, event inputs, configuration and the identity each function runs as. This guide compares the two models side by side for attack surface, identity, secrets, runtime protection and detection, and gives decision guidance for choosing or combining them. It is for cloud architects, platform engineers and cloud security teams. It goes deeper than the Container Security Guide and the Cloud Security Guide on the comparison itself and does not repeat their baseline controls.

Key takeaways

  • Serverless shrinks the surface you patch, not the surface you own. The provider handles hosts and managed runtimes, but code, dependencies, event inputs, permissions and configuration remain yours.
  • Identity is the main attack path in both. A container's service account and a function's execution role are non-human identities; over-permissive ones turn any code flaw into cloud account access.
  • Isolation strength differs by design. Standard containers share the host kernel; major serverless platforms isolate each instance with a virtual machine boundary such as a microVM.
  • Runtime visibility moves from agents to logs. Containers support host and sidecar sensors; serverless relies on provider logs, tracing and in-function instrumentation.
  • Most estates run both. Choose per workload, then apply one identity, secrets and supply chain standard across the two.

The short answer

Choose containers when you need control over the runtime, long-running or stateful processes, custom networking, specialised hardware, portability across clouds, or deep runtime security tooling. Choose serverless functions when workloads are event driven and short lived, when you want the provider to own host and runtime patching, and when per-invocation scaling and a smaller operations footprint matter more than runtime control. From a security point of view neither is inherently safer: serverless removes host hardening, node patching and kernel escape risk from your list, while adding event injection, permission sprawl across many small functions, and reduced runtime visibility. Managed container platforms such as Amazon ECS on Fargate, Azure Container Apps and Google Cloud Run sit between the two, running container images on provider-managed infrastructure.

Side-by-side comparison

AspectContainers (self-managed nodes, for example Kubernetes)Serverless functions
Unit of deploymentContainer image run as a long-lived or batch processFunction code package or image, invoked per event
Who patches the host and kernelYou (or a managed node service you configure)Provider
Who patches the language runtimeYou, via the base imageProvider for managed runtimes; you for custom runtimes and container image functions
Isolation boundaryLinux namespaces, cgroups, seccomp and capabilities on a shared kernel; optional sandboxed runtimesProvider-enforced VM-level boundary per instance (for example Firecracker microVMs, gVisor or Linux microVMs)
Main entry pointsExposed services, ingress, orchestrator API, kubelet, registries, CI/CDHTTP triggers, queues, storage events, streams, schedules, function management APIs
Workload identityKubernetes service account with projected tokens, federated to cloud IAMExecution role, managed identity or service account bound to the function
Secrets deliveryKubernetes Secrets, external secrets operators, CSI driver, vault agentEnvironment variables (encrypted at rest) or runtime retrieval from a secrets manager
Runtime protectioneBPF or kernel sensors, admission control, Pod Security Standards, network policyProvider isolation, least-privilege roles, input validation, limited in-function instrumentation
Detection telemetryKubernetes audit log, container runtime events, node logs, flow logsCloud control plane audit logs, function logs, tracing, invocation metrics
Typical blast radius of a code flawContainer, then node and cluster if escape or over-privileged service accountFunction's permissions and any data its role or identity can reach
ForensicsPossible to snapshot containers and nodes if captured quicklyInstances are ephemeral; rely on logs and traces captured in advance

Attack surface compared

Containers

NIST SP 800-190, the Application Container Security Guide, frames container risk across the image, the registry, the orchestrator, the container itself and the host operating system. In practice the highest-value targets are an exposed or weakly authenticated orchestrator API or dashboard, privileged pods that allow escape to the host, service account tokens mounted into pods that do not need them, and secrets baked into images. Kubernetes Pod Security Standards define three cumulative profiles: Privileged, Baseline (prevents known privilege escalations) and Restricted (current pod hardening best practice). Restricted requires runAsNonRoot: true, allowPrivilegeEscalation: false, a seccomp profile of RuntimeDefault or Localhost, and dropping ALL capabilities, with only NET_BIND_SERVICE allowed back. See the Kubernetes Security Guide and the Kubernetes Admission Control Guide.

Serverless functions

The provider removes the host from your attack surface. Firecracker, the open source virtual machine monitor built to enable services such as AWS Lambda, runs each workload in a KVM microVM with a minimal device model of five emulated devices, plus a jailer process as a second barrier. Google documents Cloud Run instances as isolated by a VMM-enforced boundary with two sandboxing layers in both execution environments. What remains is application-level: every event source is an input channel, including object names, queue messages and stream records that developers often trust more than HTTP requests. Large function estates also multiply identities and configurations, and adversaries can abuse function services directly, which ATT&CK records as T1648 Serverless Execution. See MITRE ATT&CK T1648 Serverless Execution.

Threat to control mapping

ATT&CK techniqueContainersServerless functions
T1611 Escape to HostPrimary risk: block privileged pods and host mounts with Restricted profile, keep nodes patchedProvider-owned boundary; your part is applying provider updates to custom runtimes and images
T1610 Deploy ContainerAdmission control, RBAC limits on pod create, image allow listsApplies to managed container services; restrict who can create or update services
T1648 Serverless ExecutionNot applicableRestrict function create, update and role-pass permissions; alert on new functions and triggers
T1525 Implant Internal ImageSigned images, registry write controls, admission verificationSame for image-based functions; code package integrity for zip deployments
T1552.007 Container APIAuthenticate and restrict API server and kubelet access; disable anonymous accessNot applicable
T1552.005 Cloud Instance Metadata APIBlock pod access to node metadata; use workload identityCredentials come from the platform; scope the role tightly
T1496 Resource HijackingResource quotas, egress control, CPU anomaly alertsConcurrency limits, budget alerts, invocation anomaly alerts
T1078.004 Cloud AccountsFederated, short-lived workload credentials; no static keys in podsLeast-privilege execution identity; no static keys in configuration

Identity and secrets: where both models are won or lost

Both models run code as a non-human identity, and both have converged on short-lived platform-issued credentials. Since Kubernetes v1.22, pods receive a short-lived, automatically rotating, audience-bound token through the TokenRequest API mounted as a projected volume; since v1.24 long-lived Secret-based tokens are no longer created automatically. Setting automountServiceAccountToken: false stops token injection for pods that never call the API. Serverless platforms bind an identity to each function: an execution role, a managed identity or a service account.

The Tesla Kubernetes cryptojacking incident shows the container side: an unauthenticated Kubernetes console led to cloud credentials stored inside a pod, which were then used for cryptomining. The Docker Hub secrets leak shows how secrets baked into images through .env files, Dockerfiles and copied project directories outlive their removal unless the credential is revoked.

Platform settings for serverless identity and secrets

Platforms are listed alphabetically. Each row is the customer-side setting the vendor's own documentation describes, as of November 2026.

PlatformFunction identitySecrets guidanceNetwork and access controls
AWS LambdaExecution role assumed automatically on invocation; trim development permissions before production, using IAM Access Analyzer to generate a policy from CloudTrail activityEnvironment variables are always encrypted at rest with KMS (AWS managed key by default, customer managed key optional); use Secrets Manager for credentialsAPI access over TLS 1.2 or later; deny kms:Decrypt on the function's key to stop users viewing variables
Azure FunctionsSystem-assigned or user-assigned managed identity; identity-based connections for triggers and bindingsApp settings are encrypted and injected at startup; use Key Vault references for shared secretsAccess restrictions, Private Endpoints, App Service Environment; authenticate callers by identity rather than relying on function access keys
Google Cloud Run (services and functions)Assign a dedicated service account with only the permissions the workload needs (the Compute Engine default service account is used unless you specify one)Store secrets in Secret ManagerIngress settings (internal, internal and load balancing), invoker IAM with OIDC ID tokens, option to disable the default URL

For platform depth see the AWS Lambda Security Guide, the Azure Functions Security Guide and the Cloud Run and Cloud Functions Security Guide.

Runtime protection and detection

  • Containers: enforce Pod Security Standards at namespace level, default-deny network policies, admission checks for image signatures and registries, and a runtime sensor for process, file and network anomalies. Ship the Kubernetes audit log to the SIEM. See the Container Runtime Security Guide and the Kubernetes Audit Log Detection Guide.
  • Serverless: log every control plane change to functions, triggers, roles and environment configuration; capture function logs and traces centrally with retention set before you need them; alert on invocation, error and duration anomalies; set concurrency and budget limits so abuse is bounded.
  • Both: monitor the identity layer. Unusual API calls by a workload identity, use of a role from an unexpected network, and new permissions attached to a workload role are the earliest signals in either model.
MetricContainersServerless
Workloads meeting the hardening baseline% of namespaces enforcing Restricted (or documented Baseline exceptions)% of functions on supported runtimes with reviewed configuration
Identity scope% of pods using a dedicated service account; % with token automount disabled where not needed% of functions with a dedicated execution identity and no wildcard permissions
Static credentials in workloadsSecrets found in images or manifests (target 0)Secrets found in environment variables or code packages (target 0)
Vulnerability exposureCritical image vulnerabilities older than SLACritical dependency vulnerabilities older than SLA
Detection coverageClusters with audit logs and runtime sensor feeding the SIEMAccounts or projects with function control plane logs feeding the SIEM

How to implement a common standard across both

  1. Inventory workloads and identities. List clusters, namespaces, functions and managed container services, each with its runtime identity, owner and data access.
  2. Set one supply chain baseline. Approved base images, dependency scanning, signing and SBOMs for container images and function packages alike. See the SBOM Guide.
  3. Fix identity first. Split shared roles, remove static keys, move to federated or platform-issued credentials, and run policy generation from observed activity. Keep old credentials disabled, not deleted, for one release cycle so you can roll back.
  4. Apply runtime guardrails in audit mode. Label namespaces with Pod Security Standards in warn and audit modes, and put function configuration rules in a cloud posture tool in report-only mode; fix violations, then enforce.
  5. Centralise telemetry. Kubernetes audit logs, runtime sensor alerts, cloud control plane logs and function logs into one detection pipeline with tested rules.
  6. Exercise incident response for each model. Practise containment for a compromised pod (isolate, snapshot, revoke service account) and a compromised function (revoke role sessions, freeze versions, rotate secrets). See the Container and Kubernetes Forensics Guide.

Decision guidance

If the workload...Lean towardsSecurity reason
Is event driven, short lived and statelessServerlessNo host or runtime patching; small per-function identity scope
Needs custom kernels, privileged access, GPUs or host networkingContainersControl over isolation and runtime tooling, with hardening owned by you
Must run deep runtime detection or third-party security agentsContainers or managed containersSensors and sidecars are supported; function runtimes limit them
Handles untrusted multi-tenant input at high volumeEither, with sandboxed runtime for containersShared-kernel containers need extra isolation for hostile input
Is owned by a small team without platform engineeringServerless or managed containersFewer components to misconfigure
Must be portable across clouds or on premisesContainersSame controls everywhere; serverless controls are provider specific

Small organisations usually gain most from serverless or managed containers, because they remove cluster and node security work. Large organisations run both and should invest in a shared identity, secrets and supply chain standard plus a platform team that owns cluster hardening, rather than letting each product team secure its own model differently.

Common failure patterns

  • Assuming serverless means secure by the provider. The provider secures the host; function permissions, inputs, dependencies and configuration are customer-side.
  • Exposed orchestrator interfaces. Dashboards and API servers reachable without strong authentication, as in the Tesla case.
  • One role for many functions or pods. Convenience roles with broad wildcards give every flaw the same large blast radius.
  • Secrets in images and environment variables. Visible to anyone who can pull the image or read function configuration, and still valid after the image is deleted.
  • Trusting non-HTTP events. File names, queue messages and stream records reach code paths without the validation applied to web requests.
  • No logs when needed. Ephemeral containers and functions leave nothing to examine unless logs and traces were shipped and retained beforehand.

Framework mapping

Control areaNIST SP 800-53 Rev. 5NIST CSF 2.0
Hardened baselines (Pod Security Standards, function configuration)CM-2, CM-7PR.PS-01
Workload identity least privilegeAC-6PR.AA-05
Isolation (namespaces, sandboxes, microVMs)SC-39PR.PS-01
Image and package integritySI-7PR.PS-02
Vulnerability scanning of images and dependenciesRA-5PR.PS-02
Runtime and control plane monitoringSI-4DE.CM-09

Decision checklist

  • Does the workload need runtime control, special hardware or portability that only containers give?
  • If serverless, are all event sources treated as untrusted input?
  • Does every pod and function run as its own identity with permissions generated from real activity?
  • Are there zero static cloud keys in images, manifests, environment variables or code packages?
  • Is the isolation boundary sufficient for the input (sandboxed runtime or VM boundary for hostile multi-tenant input)?
  • Will you have logs, traces and audit events if the workload is compromised and gone in minutes?

Practitioner checklist

  • Enforce Pod Security Standards Restricted on application namespaces, with documented exceptions.
  • Disable service account token automount for pods that do not call the Kubernetes API.
  • Give every function and pod a dedicated, least-privilege identity; remove wildcard permissions.
  • Replace static cloud keys with workload identity federation or platform-issued credentials.
  • Move secrets from images and environment variables to a secrets manager with runtime retrieval.
  • Authenticate and restrict orchestrator APIs, dashboards and function management APIs.
  • Sign and scan images and function packages; verify at admission or deployment.
  • Ship Kubernetes audit logs, runtime alerts and function control plane logs to the SIEM.
  • Set concurrency, quota and budget limits to bound resource hijacking.

Standards and references

Related NHI Mgmt Group resources: Container Security Guide · Kubernetes Security Guide · Cloud Workload Identity Guide · CNAPP Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 13 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.