Serverless and Containers
Lambda, ECS, EKS and Fargate: running code without managing servers, and choosing the right compute.
What is it?
Serverless does not mean no servers. It means you don't provision, patch or scale them. You provide code; the service runs it when needed and bills for use.
AWS Lambda runs a function in response to events (an HTTP request, a queue message, a file upload, a schedule). You pay per invocation and duration, it scales automatically, and each run is short. Limits apply, such as a 15-minute maximum run time and configurable memory, so long, heavy jobs belong elsewhere.
Containers package an app with its dependencies so it runs the same everywhere.
- Amazon ECS: AWS's own container orchestrator, simple and tightly integrated.
- Amazon EKS: managed Kubernetes, for teams that want the Kubernetes API and ecosystem.
- AWS Fargate: serverless compute for containers. You set CPU and memory; it runs tasks without EC2 hosts for you to manage (works with ECS and EKS).
- Amazon ECR (Elastic Container Registry): a managed registry to store, scan and share container images for ECS, EKS and Fargate.
More compute options
- AWS Batch: runs batch jobs at any scale. You submit jobs; Batch queues them and provisions the right EC2 or Fargate capacity (including Spot), so you don't manage a scheduler.
- Amazon Lightsail: simple virtual servers, containers, databases, storage and static IPs with predictable monthly pricing and a friendly console. Good for small websites, blogs and learning projects.
- AWS Outposts: AWS infrastructure and services in your own data center for hybrid needs.
Choosing compute:
- EC2: full control of virtual servers.
- Containers (ECS/EKS/Fargate): portable, packaged applications.
- Lambda: short, event-driven code.
- Elastic Beanstalk: deploy web apps without managing infrastructure details.
- Lightsail: a simple fixed-price start.
Virtual machines vs containers
- A VM runs on a hypervisor with its own full guest OS. You usually size it with spare headroom that you pay for even when unused. Apps sharing one VM are not isolated: one can hog resources or break another's configuration.
- A container runs on a container runtime (such as Docker Engine) and shares the host's OS kernel. Each bundles its own libraries and dependencies, is isolated from its neighbours, packs more densely and starts much faster than a VM.
Docker popularised containers: a Dockerfile describes how to build an image, Docker Compose runs multi-container apps, and Docker Hub is a public image registry. The Open Container Initiative (OCI) standardises image formats and runtimes, so OCI images run with any compatible tool.
Kubernetes (K8s) is the open-source orchestration standard, originally from Google and now run by the CNCF. It runs containers across many nodes in pods (one or more containers sharing network and storage) and shines with many microservices. Bottlerocket is AWS's open-source Linux OS built just for hosting containers.
Monolith vs microservices: a monolith is one tightly coupled app doing everything. Microservices split it into small, independently deployable (often stateless) services, each doing one job, often built from managed pieces such as containers, Lambda, SQS, ELB and RDS.
ECS building blocks
- A cluster provides capacity: Fargate, EC2 instances you manage, or a mix through capacity providers.
- A task definition is the blueprint: image, CPU and memory, ports and IAM roles.
- A task runs containers until they finish (good for one-off jobs). A service keeps a desired number of tasks running long term, such as a web server, and replaces failed ones using health checks.
- Images come from Amazon ECR or a public registry such as Docker Hub. Container logs normally go to CloudWatch Logs.
Cost trap: an ECS cluster on EC2 instances bills for them all the time, even with no tasks running (the upside: no cold start). A Fargate-only cluster with nothing running costs nothing, because Fargate bills for the vCPU and memory running tasks request.
Lambda details: you pick a runtime (Node.js, Python, Java, .NET, Ruby, Go, or a custom runtime), memory and a timeout. Billing is requests plus duration, measured in 1 ms increments (older material says 'rounded up to 100 ms'; that changed in December 2020).
Edit small functions in the console's built-in VS Code-based editor. Upload bigger ones as a .zip file, from S3, or as a container image. Test by sending a JSON test event and reading the output in CloudWatch Logs. For longer-running serverless container work, use Fargate.
Other container helpers:
- AWS App Runner: deploys containerised web apps and APIs from an image or source code, with no underlying resources for you to see (unlike Elastic Beanstalk, which shows the EC2 instances and load balancer it creates).
- AWS Step Functions: orchestrates Lambda functions and ECS/Fargate tasks as state machines.
- AWS X-Ray: traces requests across microservices.
Serverless is a spectrum, not a yes/no. Typical traits: high elasticity and availability, durable, secure by default, no infrastructure to see, scale to zero (no cost when idle), and paying for value instead of idle servers. Services often called serverless: Lambda, Fargate, S3, DynamoDB, Aurora Serverless, Step Functions, API Gateway, AppSync, Amplify, SQS and SNS.
Explain like I'm 10
EC2 is renting a whole kitchen: full control, but you clean and maintain it. Containers are meal-prep boxes you can reheat in any kitchen. Lambda is ordering one dish from a ghost kitchen: it appears when you ask, and you pay just for that dish.
Examples
A Lambda handler
// Pure logic you can run here: the handler shape Lambda expects.
async function handler(event) {
const name = (event && event.name) || "world";
const message = "Hello, " + name + "!";
console.log("handled event", JSON.stringify(event));
return { statusCode: 200, body: JSON.stringify({ message }) };
}
handler({ name: "Zykit" }).then((res) => console.log(res));On AWS you would export this as the handler. The function receives an event and returns a response; the runtime and servers are not your concern.
Deploying a function (CLI)
zip function.zip index.js
aws lambda create-function \
--function-name hello \
--runtime nodejs22.x \
--handler index.handler \
--zip-file fileb://function.zip \
--role arn:aws:iam::111122223333:role/lambda-basic-execution
aws lambda invoke --function-name hello --payload '{"name":"Zykit"}' \
--cli-binary-format raw-in-base64-out out.json && cat out.jsonCheck the currently supported runtime names before deploying; they change as versions retire.
Which compute service?
Situation Pick
----------------------------------------------- ----------------
Legacy app needing OS access EC2
Short event-driven task (resize an upload) Lambda
Microservices, want AWS-native simplicity ECS (+ Fargate)
Team standardised on Kubernetes EKS
Containers but no hosts to patch FargateHow it works
When an event arrives, Lambda finds or creates an execution environment, loads your code and runs the handler. The first call in a new environment has a cold start delay. Lambda scales out by adding environments. You pay for requests and run time.
ECS and EKS schedule containers onto capacity. With the EC2 launch type you manage the hosts; with Fargate AWS supplies capacity per task.
Event (HTTP, S3, SQS, schedule)
|
v
[ Lambda ] -- scales per event, short-lived
Container image (ECR) --> [ ECS or EKS ] --> capacity:
|-- EC2 hosts you manage
'-- Fargate (managed)Why does it exist?
Managing servers is undifferentiated work. Serverless and managed containers let teams focus on code, scale to zero when idle, and pay for useful work instead of idle hosts.
When to use it
- Lambda: APIs, glue code, file processing, scheduled jobs, event handlers.
- Containers: long-running services, portable workloads, microservices.
- Fargate: containers without hosts to manage.
When not to use it
Avoid Lambda for jobs longer than its time limit, steady heavy compute where reserved servers cost less, or workloads needing a special OS or hardware. Skip EKS if your team doesn't need Kubernetes; ECS is simpler.
Common mistakes
Treating Lambda as stateful - local memory and disk do not persist reliably between invocations.
Giving the function an over-broad IAM role.
Ignoring cold-start impact on latency-sensitive paths.
Choosing Kubernetes for a handful of services without needing it.
Forgetting that unbounded Lambda concurrency can overwhelm a downstream database.
Running an ECS cluster on EC2 instances for an occasional job and paying for idle instances; Fargate charges nothing when no tasks run.
Creating an ECS service for a container that prints something and exits; that is a one-off task.
Reaching for containers or Kubernetes when a single EC2 instance or a Lambda function would be simpler.
Believing containers each need their own full OS like VMs; they share the host kernel.
Using Batch for a latency-sensitive web request path; it is for queued, asynchronous jobs.
Practice exercises
- Easy:
Run the handler example here and change the event to include a different name.
- Medium:
Decide between Lambda, Fargate, and EC2 for: nightly 30-minute ETL, image thumbnailing on upload, a Windows legacy app.
- Medium:
Explain the difference between ECS on EC2 and ECS on Fargate in terms of who patches the hosts.
- Hard:
A Lambda connected to a relational database causes connection exhaustion at peak. Propose two mitigations.
- Easy:
List three differences between a virtual machine and a container.
- Medium:
Write down the ECS task definition settings you would need for a small web container, and decide whether it should run as a task or a service.
Interview questions
What is AWS Lambda?
A serverless compute service that runs code in response to events and bills by invocations and duration, scaling automatically.
ECS vs EKS?
ECS is AWS's proprietary orchestrator; EKS is managed Kubernetes. EKS suits teams that want Kubernetes portability and tooling.
What does Fargate remove?
The need to provision and manage the underlying servers for your containers.
Exam-style: A company wants to run code without managing servers, only when an event occurs. Which service?
AWS Lambda.
Exam-style: Which service stores Docker container images?
Amazon Elastic Container Registry (ECR).
Exam-style: Which service is best for a small business that wants a simple WordPress site with predictable monthly cost?
Amazon Lightsail.
Which service runs queued batch computing jobs without you managing a scheduler?
AWS Batch.
Exam-style: A team already runs Kubernetes on premises and wants a managed equivalent on AWS. Which service?
Amazon EKS.
Exam-style: Which service runs containers without provisioning or patching servers, and works with both ECS and EKS?
AWS Fargate.
How is Lambda billed?
By the number of requests plus duration (memory allocated multiplied by run time), measured in 1 ms increments.
Why might an ECS cluster cost money when no containers are running?
If it uses the EC2 launch type, you pay for the EC2 instances the whole time. With Fargate you pay only for running tasks.
Task vs service in ECS?
A task runs containers once until they exit; a service keeps a desired number of tasks running and replaces failed ones.
Exam-style: Which service orchestrates several Lambda functions into a workflow with retries and branching?
AWS Step Functions.