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
| Aspect | Containers (self-managed nodes, for example Kubernetes) | Serverless functions |
|---|---|---|
| Unit of deployment | Container image run as a long-lived or batch process | Function code package or image, invoked per event |
| Who patches the host and kernel | You (or a managed node service you configure) | Provider |
| Who patches the language runtime | You, via the base image | Provider for managed runtimes; you for custom runtimes and container image functions |
| Isolation boundary | Linux namespaces, cgroups, seccomp and capabilities on a shared kernel; optional sandboxed runtimes | Provider-enforced VM-level boundary per instance (for example Firecracker microVMs, gVisor or Linux microVMs) |
| Main entry points | Exposed services, ingress, orchestrator API, kubelet, registries, CI/CD | HTTP triggers, queues, storage events, streams, schedules, function management APIs |
| Workload identity | Kubernetes service account with projected tokens, federated to cloud IAM | Execution role, managed identity or service account bound to the function |
| Secrets delivery | Kubernetes Secrets, external secrets operators, CSI driver, vault agent | Environment variables (encrypted at rest) or runtime retrieval from a secrets manager |
| Runtime protection | eBPF or kernel sensors, admission control, Pod Security Standards, network policy | Provider isolation, least-privilege roles, input validation, limited in-function instrumentation |
| Detection telemetry | Kubernetes audit log, container runtime events, node logs, flow logs | Cloud control plane audit logs, function logs, tracing, invocation metrics |
| Typical blast radius of a code flaw | Container, then node and cluster if escape or over-privileged service account | Function's permissions and any data its role or identity can reach |
| Forensics | Possible to snapshot containers and nodes if captured quickly | Instances 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 technique | Containers | Serverless functions |
|---|---|---|
| T1611 Escape to Host | Primary risk: block privileged pods and host mounts with Restricted profile, keep nodes patched | Provider-owned boundary; your part is applying provider updates to custom runtimes and images |
| T1610 Deploy Container | Admission control, RBAC limits on pod create, image allow lists | Applies to managed container services; restrict who can create or update services |
| T1648 Serverless Execution | Not applicable | Restrict function create, update and role-pass permissions; alert on new functions and triggers |
| T1525 Implant Internal Image | Signed images, registry write controls, admission verification | Same for image-based functions; code package integrity for zip deployments |
| T1552.007 Container API | Authenticate and restrict API server and kubelet access; disable anonymous access | Not applicable |
| T1552.005 Cloud Instance Metadata API | Block pod access to node metadata; use workload identity | Credentials come from the platform; scope the role tightly |
| T1496 Resource Hijacking | Resource quotas, egress control, CPU anomaly alerts | Concurrency limits, budget alerts, invocation anomaly alerts |
| T1078.004 Cloud Accounts | Federated, short-lived workload credentials; no static keys in pods | Least-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.
- One identity per workload: shared roles across many functions or a namespace-wide service account make every flaw reach everything. See How to find unused Kubernetes service accounts.
- Federate rather than store keys: map Kubernetes service accounts to cloud IAM through workload identity federation instead of mounting cloud access keys. See the Cloud Workload Identity Guide.
- Keep secrets out of images and environment variables: retrieve them at runtime from a secrets manager. See How to find hard-coded secrets in container images and How to find secrets in Lambda environment variables.
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.
| Platform | Function identity | Secrets guidance | Network and access controls |
|---|---|---|---|
| AWS Lambda | Execution role assumed automatically on invocation; trim development permissions before production, using IAM Access Analyzer to generate a policy from CloudTrail activity | Environment variables are always encrypted at rest with KMS (AWS managed key by default, customer managed key optional); use Secrets Manager for credentials | API access over TLS 1.2 or later; deny kms:Decrypt on the function's key to stop users viewing variables |
| Azure Functions | System-assigned or user-assigned managed identity; identity-based connections for triggers and bindings | App settings are encrypted and injected at startup; use Key Vault references for shared secrets | Access 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 Manager | Ingress 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.
| Metric | Containers | Serverless |
|---|---|---|
| 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 workloads | Secrets found in images or manifests (target 0) | Secrets found in environment variables or code packages (target 0) |
| Vulnerability exposure | Critical image vulnerabilities older than SLA | Critical dependency vulnerabilities older than SLA |
| Detection coverage | Clusters with audit logs and runtime sensor feeding the SIEM | Accounts or projects with function control plane logs feeding the SIEM |
How to implement a common standard across both
- Inventory workloads and identities. List clusters, namespaces, functions and managed container services, each with its runtime identity, owner and data access.
- Set one supply chain baseline. Approved base images, dependency scanning, signing and SBOMs for container images and function packages alike. See the SBOM Guide.
- 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.
- 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.
- Centralise telemetry. Kubernetes audit logs, runtime sensor alerts, cloud control plane logs and function logs into one detection pipeline with tested rules.
- 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 towards | Security reason |
|---|---|---|
| Is event driven, short lived and stateless | Serverless | No host or runtime patching; small per-function identity scope |
| Needs custom kernels, privileged access, GPUs or host networking | Containers | Control over isolation and runtime tooling, with hardening owned by you |
| Must run deep runtime detection or third-party security agents | Containers or managed containers | Sensors and sidecars are supported; function runtimes limit them |
| Handles untrusted multi-tenant input at high volume | Either, with sandboxed runtime for containers | Shared-kernel containers need extra isolation for hostile input |
| Is owned by a small team without platform engineering | Serverless or managed containers | Fewer components to misconfigure |
| Must be portable across clouds or on premises | Containers | Same 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 area | NIST SP 800-53 Rev. 5 | NIST CSF 2.0 |
|---|---|---|
| Hardened baselines (Pod Security Standards, function configuration) | CM-2, CM-7 | PR.PS-01 |
| Workload identity least privilege | AC-6 | PR.AA-05 |
| Isolation (namespaces, sandboxes, microVMs) | SC-39 | PR.PS-01 |
| Image and package integrity | SI-7 | PR.PS-02 |
| Vulnerability scanning of images and dependencies | RA-5 | PR.PS-02 |
| Runtime and control plane monitoring | SI-4 | DE.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
- NIST: SP 800-190, Application Container Security Guide
- Kubernetes: Pod Security Standards
- Kubernetes: Service Accounts
- Firecracker: Secure and fast microVMs for serverless computing
- AWS: Defining Lambda function permissions with an execution role
- Microsoft: Securing Azure Functions
- Google Cloud: Cloud Run security design overview
- MITRE ATT&CK: Serverless Execution
Related NHI Mgmt Group resources: Container Security Guide · Kubernetes Security Guide · Cloud Workload Identity Guide · CNAPP Guide