AWS Elastic Beanstalk
LearningTree ยท AWS ยท Compute

AWS Elastic Beanstalk โ€”
Platform as a Service

Deploy and scale web applications without managing infrastructure. Upload your code โ€” Beanstalk provisions EC2 instances, load balancers, auto scaling, and monitoring automatically.

โšก Elastic Beanstalk in 30 Seconds

  • PaaS for AWS โ€” upload your code, Beanstalk creates and manages the infrastructure
  • Provisions EC2, Auto Scaling, ELB, CloudWatch, Security Groups automatically
  • You retain full control โ€” you can SSH into instances, customize configs, pick instance types
  • Supports Java, .NET, Node.js, Python, Ruby, Go, PHP, Docker โ€” and custom platforms
  • No additional charge โ€” you pay only for the underlying AWS resources (EC2, RDS, ELB, etc.)
01
Chapter One

What is Elastic Beanstalk

What is Platform as a Service (PaaS) Introductory

Cloud computing offers different levels of control vs. convenience. At the lowest level, Infrastructure as a Service (IaaS) gives you raw servers โ€” you install the OS, configure networking, deploy your app. At the highest level, Software as a Service (SaaS) gives you a finished product โ€” Gmail, Slack. In between sits Platform as a Service (PaaS).

PaaS takes care of the platform layer: operating system, runtime, middleware, and scaling infrastructure. You focus only on your application code. You don't patch servers, configure load balancers, or set up monitoring โ€” the platform does it for you.

๐Ÿ”ง

IaaS โ€” You Manage Most

  • Raw EC2 instances
  • You install OS, runtime
  • You configure networking
  • You set up monitoring
  • Maximum control
๐Ÿš€

PaaS โ€” Balanced

  • Elastic Beanstalk, Heroku
  • Platform manages servers
  • You deploy code + config
  • Auto scaling built in
  • Control when you need it
โšก

Serverless โ€” Least Mgmt

  • Lambda, Fargate
  • No servers visible at all
  • Pay per invocation/second
  • Event-driven model
  • Least operational overhead

๐Ÿ‘‰ Key insight: Elastic Beanstalk is PaaS on top of IaaS. It uses EC2, Auto Scaling, ELB, and CloudWatch underneath. The difference is that Beanstalk creates and configures those resources automatically. You still own them โ€” you can inspect, customize, and SSH into them. Beanstalk is the convenience layer, not a black box.

Why Elastic Beanstalk Exists Introductory

Imagine you want to deploy a simple Node.js web app on AWS. Without Beanstalk, you would need to:

๐Ÿ˜ฐ

Manual Approach (EC2)

  • Launch EC2 instances
  • Install Node.js runtime
  • Configure security groups
  • Set up an ALB + target groups
  • Create an Auto Scaling Group
  • Configure CloudWatch alarms
  • Set up deployment pipeline
  • Manage OS patches & updates

~15 services, hours of setup

๐Ÿ˜Œ

Beanstalk Approach

  • Select "Node.js" platform
  • Upload your ZIP/WAR
  • Choose instance type (optional)
  • Click "Create Environment"
  • Done. Everything provisioned.

Same result: ALB + ASG + EC2 + CloudWatch โ€” created in minutes.

Beanstalk exists because most developers want to deploy code, not configure infrastructure. It bridges the gap between "I have a ZIP file" and "I have a production-grade, load-balanced, auto-scaling deployment."

EC2 vs Elastic Beanstalk vs Lambda Core

The three most common AWS compute options for applications โ€” each with a different tradeoff between control and convenience:

FeatureEC2 (IaaS)Elastic Beanstalk (PaaS)Lambda (Serverless)
What you deployAMI + config scriptsZIP/WAR/Docker imageFunction code
Server managementFull (you manage everything)Automated (but accessible)None (invisible)
ScalingManual ASG configurationAuto (built-in ASG)Automatic per-request
Load balancingYou create ALBAuto (creates ALB for you)API Gateway
OS accessFull SSHSSH availableNo OS access
RuntimeAny (you install)Supported platformsSupported runtimes
Execution modelAlways runningAlways runningEvent-driven (on-demand)
Max execution timeUnlimitedUnlimited15 minutes
PricingPer instance-hourPer underlying resourcesPer request + duration
Best forFull control, custom setupsStandard web apps, quick deployShort tasks, event handlers

๐Ÿ‘‰ Rule of thumb: Use EC2 when you need full control over the OS and custom configurations. Use Elastic Beanstalk when you want a standard web application deployed quickly with auto-scaling. Use Lambda when your workload is event-driven, short-lived, and you want zero server management.

What Beanstalk IS and IS NOT Core
โœ…

Beanstalk IS

  • An orchestration service โ€” it creates and manages other AWS services for you
  • A free abstraction โ€” no charge for Beanstalk itself (you pay for EC2, ELB, etc.)
  • An opinionated deployer โ€” provides best-practice defaults
  • Transparent โ€” you can see and access everything it creates
  • Built on CloudFormation under the hood
โŒ

Beanstalk IS NOT

  • A separate compute service โ€” it uses EC2 instances
  • A black box โ€” you retain full access to all resources
  • Serverless โ€” your instances run 24/7 (unlike Lambda)
  • A container orchestrator โ€” use ECS/EKS for that
  • Free infrastructure โ€” you pay for the underlying resources
Mental Model โ€” The Valet Parking Analogy Introductory

Think of deploying your app like arriving at a hotel:

๐Ÿ…ฟ๏ธ

EC2 = Self-Parking

You drive your own car, find a spot, park it, lock it, remember where you parked. Full control โ€” but you do all the work.

๐ŸŽฉ

Beanstalk = Valet Parking

You hand your keys to the valet. They park your car, but you can still go see it, move it yourself, or tell them which floor. Convenient + accessible.

๐Ÿš•

Lambda = Taxi / Uber

You don't have a car at all. Someone drives you when you need it, and you pay per ride. No car to manage โ€” but you can't customize the vehicle.

๐Ÿ”‘ Key Mental Model

Elastic Beanstalk = Valet Parking for your code.

  • You provide the car (application code)
  • The valet handles parking (EC2, ASG, ELB, CloudWatch)
  • You can still access, inspect, and customize everything
  • You pay for the parking spot โ€” not the valet service
How Beanstalk Works โ€” High Level Core

When you create a Beanstalk environment, here is what happens behind the scenes:

1๏ธโƒฃ

You Provide

  • Application code (ZIP, WAR, or Docker)
  • Platform choice (Node.js, Java, Python, etc.)
  • Optional: instance type, scaling rules, env vars
2๏ธโƒฃ

Beanstalk Creates

  • EC2 instances with your platform runtime
  • Auto Scaling Group for scaling
  • Elastic Load Balancer for traffic distribution
  • Security Groups for network access
  • CloudWatch alarms for monitoring
  • S3 bucket for version storage

Under the hood, Beanstalk generates a CloudFormation template that describes all these resources. When you update your code or change configuration, Beanstalk updates the CloudFormation stack. This is why Beanstalk is not magic โ€” it's automation on top of services you already know.

Concept Diagram โ€” Cloud Service Models Introductory
IaaS vs PaaS vs Serverless โ€” What You Manage
IaaS (EC2) PaaS (Beanstalk) Serverless (Lambda) Application Data Runtime OS Networking Servers You manage You manage You manage You manage You manage AWS manages You manage You manage Beanstalk Beanstalk Beanstalk AWS manages You manage AWS manages AWS manages AWS manages AWS manages AWS manages = You manage = Beanstalk manages = AWS fully manages
AWS Diagram โ€” What Beanstalk Creates for You Core
Elastic Beanstalk โ€” Underlying AWS Services
Elastic Beanstalk Environment
Beanstalk
Beanstalk
Orchestrator
โ†’
CloudFormation
CloudFormation
Infra Templates
โ†’
EC2
EC2
App Servers
ASG
Auto Scaling
Scale In/Out
ELB
ELB
Load Balancer
CloudWatch
CloudWatch
Monitoring
S3
S3
Version Storage
SNS
SNS
Notifications

You provide code โ†’ Beanstalk generates CloudFormation โ†’ CloudFormation provisions EC2, ASG, ELB, CloudWatch, S3, SNS

Architecture Diagram โ€” Beanstalk Web App Deployment Core
Elastic Beanstalk โ€” Standard Web Server Environment
๐Ÿ‘จโ€๐Ÿ’ป DEVELOPER eb deploy upload BEANSTALK Orchestrator (free) VPC ๐ŸŒ Users Elastic Load Balancer HTTPS :443 AUTO SCALING GROUP EC2 Instance Node.js Runtime Your App Code AZ-a EC2 Instance Node.js Runtime Your App Code AZ-b +N scales out CloudWatch โ€” Logs + Metrics S3 โ€” App Versions RDS (optional) โ†’ = traffic/deploy flow Developer uploads code โ†’ Beanstalk โ†’ EC2 + ELB + ASG + CloudWatch
๐ŸŽฏ Chapter 01 Summary

Elastic Beanstalk is AWS's PaaS โ€” the fastest path from code to production.

  • PaaS sits between IaaS (EC2) and Serverless (Lambda) โ€” you manage code, Beanstalk manages infrastructure
  • Beanstalk creates real AWS resources โ€” EC2, ASG, ELB, CloudWatch, S3 โ€” you can see and access them all
  • Built on CloudFormation under the hood โ€” every environment is an infra-as-code stack
  • Free service โ€” you pay only for the underlying resources (EC2, ELB, etc.)
  • Mental model: Valet Parking โ€” you hand over the keys, but you can always go check on your car
02
Chapter Two

Core Concepts

The Beanstalk Hierarchy Introductory

Elastic Beanstalk organizes everything into a clear hierarchy. Understanding these five building blocks is essential before you deploy anything:

๐Ÿ“ฆ

Application

The top-level container. An application is a logical collection โ€” it groups all environments, versions, and configurations for one project. Think of it as a folder label: "my-web-app."

One application can have multiple environments (dev, staging, prod) and multiple versions (v1, v2, v3).

๐Ÿท๏ธ

Application Version

A specific, labeled release of your code. When you upload a ZIP/WAR, Beanstalk stores it in S3 and labels it as a version (e.g., "v1.2.3"). Versions are immutable โ€” once uploaded, they don't change.

You can deploy any version to any environment. Rollback = deploy a previous version.

๐ŸŒ

Environment

A running instance of your application. Each environment is a collection of AWS resources (EC2, ELB, ASG) running one version of your code. You typically have separate environments for dev, staging, and production.

โš™๏ธ

Environment Configuration

The settings that define how the environment behaves: instance type, scaling rules, environment variables, security groups, load balancer type. Saved as configuration templates for reuse.

๐Ÿ—๏ธ

Platform

The OS + runtime combination. Beanstalk provides managed platforms: "Python 3.11 on Amazon Linux 2023", "Node.js 18 on Amazon Linux 2023", "Docker on Amazon Linux 2023", etc.

๐Ÿ‘‰ How they relate: An Application contains many Versions. You deploy one Version into an Environment. The Environment runs on a Platform and is configured via an Environment Configuration. Simple hierarchy โ€” Application โ†’ Version โ†’ Environment.

Environment Types โ€” Web Server vs Worker Core

Beanstalk offers two environment types, each designed for a different workload pattern:

๐ŸŒ

Web Server Environment

  • Handles HTTP/HTTPS requests from users
  • Creates an ELB (load balancer) + ASG (auto scaling)
  • EC2 instances run a web server (Nginx/Apache) + your app
  • ELB distributes traffic across instances
  • Health checks ensure only healthy instances receive traffic
  • Use case: APIs, websites, web applications
โš™๏ธ

Worker Environment

  • Processes background tasks from an SQS queue
  • No load balancer โ€” not internet-facing
  • Beanstalk creates an SQS queue automatically
  • A daemon on each instance polls SQS and POSTs messages to localhost
  • Auto scales based on queue depth
  • Use case: Email sending, image processing, report generation
FeatureWeb Server EnvironmentWorker Environment
Traffic sourceHTTP/HTTPS from internetSQS messages
Load balancerYes (ALB, CLB, or NLB)No
Auto scaling triggerCPU, latency, requestsSQS queue depth
Entry pointELB DNS endpointSQS queue URL
DaemonWeb server (Nginx)SQS daemon โ†’ POST to localhost
Typical useAPIs, websitesBackground jobs, async tasks

๐Ÿ‘‰ Common pattern: Use a Web Server environment for your API (receives user requests) and a Worker environment for heavy processing. The web tier sends messages to SQS, the worker tier processes them. Decoupled, scalable, and each tier scales independently.

Supported Platforms Core

Beanstalk provides managed platforms โ€” pre-configured AMIs with the OS, runtime, and web server already installed. You don't need to install Node.js or configure Nginx โ€” the platform handles it.

โ˜•

Java

Corretto 8/11/17/21 with Tomcat or standalone JAR. Deploy WAR files or fat JARs.

๐ŸŸข

Node.js

Node.js 16/18/20 with Nginx reverse proxy. Deploy ZIP with package.json.

๐Ÿ

Python

Python 3.8โ€“3.12 with WSGI (Gunicorn). Deploy ZIP with requirements.txt.

๐Ÿ’Ž

Ruby

Ruby 3.0โ€“3.2 with Puma. Deploy ZIP with Gemfile.

๐Ÿ˜

PHP

PHP 8.0โ€“8.3 with Apache/Nginx. Deploy ZIP with composer.json.

๐Ÿน

Go

Go 1.20+. Deploy a compiled binary or source with go.mod.

๐Ÿ”ท

.NET

.NET 6/8 on Linux or Windows. Deploy ZIP or publish output.

๐Ÿณ

Docker

Single or multi-container Docker. Deploy Dockerfile or docker-compose.yml. Most flexible option.

๐Ÿ”ง

Custom Platform

Build your own AMI with Packer. Use any language or runtime Beanstalk doesn't natively support.

๐Ÿ‘‰ Platform versions: Beanstalk supports Amazon Linux 2023 (current, recommended) and Amazon Linux 2 (maintenance mode). New environments should always use AL2023. Amazon Linux 1 (AL1) was retired December 31, 2023. If you have AL1 or AL2 environments, plan migration to AL2023 โ€” platform behavior, hook paths, and Nginx configuration differ between versions.

Concept Diagram โ€” Beanstalk Object Hierarchy Introductory
Elastic Beanstalk โ€” Application โ†’ Version โ†’ Environment
APPLICATION "my-web-app" Version v1.0 app-v1.0.zip โ†’ S3 Version v2.0 app-v2.0.zip โ†’ S3 Version v3.0 app-v3.0.zip โ†’ S3 deploy v2.0 deploy v3.0 ENV: dev Running: v2.0 t3.small ยท 1 instance No ELB (single instance) Web Server Env ENV: prod Running: v3.0 t3.large ยท 2โ€“6 instances ALB + Auto Scaling Web Server Env PLATFORM: Node.js 18 on Amazon Linux 2023 OS + Runtime + Web Server (Nginx) โ€” managed by AWS Application Versions (in S3) Environments (running) Platform (managed AMI)
AWS Diagram โ€” Web Server vs Worker Environment Core
Environment Types โ€” How Traffic Flows
๐ŸŒ Web Server Environment
USERS โ†’ HTTPS
ELB
ELB
โ†“
EC2
EC2
App
EC2
EC2
App
Auto Scaling Group
โš™๏ธ Worker Environment
SQS MESSAGES
SQS
SQS Queue
โ†“
EC2
EC2
Worker
EC2
EC2
Worker
No Load Balancer ยท Scales on queue depth

Web Server = internet-facing (ELB + ASG) ยท Worker = queue-driven (SQS + ASG, no ELB)

Architecture Diagram โ€” Decoupled Web + Worker Pattern Deep
Production Pattern โ€” Web Tier + Worker Tier via SQS
๐ŸŒ Users WEB SERVER ENV ALB EC2 API App EC2 API App send msg SQS Queue poll WORKER ENV EC2 Worker EC2 Worker Process: resize, email, report Amazon RDS Shared Database CloudWatch โ€” Monitoring both tiers โ†’ = data flow Web tier handles requests ยท sends heavy work to SQS ยท Worker tier processes async
๐ŸŽฏ Chapter 02 Summary

Beanstalk organizes resources into Application โ†’ Versions โ†’ Environments.

  • Application โ†’ top-level container. Version โ†’ immutable code snapshot in S3. Environment โ†’ running resources.
  • Web Server Env = ELB + EC2 + ASG (HTTP traffic). Worker Env = SQS + EC2 + ASG (background tasks).
  • Platforms are managed AMIs โ€” Java, Node.js, Python, Ruby, PHP, Go, .NET, Docker, or Custom.
  • Decoupled pattern: Web tier โ†’ SQS โ†’ Worker tier. Each scales independently.
  • Configuration templates allow reuse โ€” same settings across dev/staging/prod.
03
Chapter Three

Deployment Models

Why Deployment Strategy Matters Introductory

When you push a new version of your application, how should Beanstalk update the running instances? Replace all at once? Replace them gradually? Spin up brand new ones? The choice affects downtime, risk, speed, and cost.

Beanstalk provides five deployment policies. Each makes a different tradeoff โ€” there is no "best" option, only the right one for your situation.

1. All at Once Core
๐Ÿ’ฅ

All at Once

Deploy the new version to all instances simultaneously. Every instance goes down, receives the update, and comes back up.

  • Downtime: Yes โ€” all instances updating at the same time
  • Deploy speed: Fastest
  • Rollback: Re-deploy previous version (slow)
  • Cost: No additional instances
  • Best for: Dev/test environments where downtime is acceptable
ALL AT ONCE Before v1 v1 v1 v1 During (โš ๏ธ downtime) โณ โณ โณ โณ After v2 v2 v2 v2
2. Rolling Core
๐Ÿ”„

Rolling

Update instances in batches. First batch goes down, gets updated, comes back healthy. Then the next batch. Capacity is temporarily reduced.

  • Downtime: No (but reduced capacity during update)
  • Deploy speed: Moderate โ€” depends on batch size
  • Rollback: Re-deploy previous version (slow)
  • Cost: No additional instances
  • Best for: Cost-sensitive production where brief reduced capacity is fine
ROLLING (batch=2) Step 1: batch 1 updating โณ โณ v1 v1 Step 2: batch 2 updating v2 v2 โณ โณ Done โœ“ v2 v2 v2 v2
3. Rolling with Additional Batch Core
โž•

Rolling with Additional Batch

Like Rolling, but first launches new instances with the new version before taking any old ones out. Full capacity maintained throughout.

  • Downtime: No (full capacity maintained)
  • Deploy speed: Moderate (slower than Rolling โ€” must launch extra instances)
  • Rollback: Re-deploy previous version (slow)
  • Cost: Temporary extra instances during deploy
  • Best for: Production where you can't afford reduced capacity
ROLLING + ADDITIONAL BATCH Step 1: Launch extra batch v1 v1 v1 v1 v2 v2 +new Step 2: Update old, keep capacity โณ โณ v1 v1 v2 v2 Done: remove extras โœ“ v2 v2 v2 v2
4. Immutable Core
๐Ÿ†•

Immutable

Launch an entirely new set of instances in a new ASG with the new version. Once healthy, swap them in and terminate the old ones. Old instances are never modified.

  • Downtime: No (full capacity + new instances running before swap)
  • Deploy speed: Slow (full new ASG must launch)
  • Rollback: Fast โ€” just terminate the new ASG
  • Cost: Doubles capacity during deploy
  • Best for: Production where fast rollback is critical
IMMUTABLE Old ASG v1 v1 still serving New ASG v2 v2 health checks โœ“ SWAP โ†’ New ASG replaces Old Result: only v2 instances remain v2 v2 Old terminated โœ—
5. Blue/Green Deep
๐Ÿ”ต๐ŸŸข

Blue/Green Deployment

Create a completely separate environment (Green) with the new version. Test it independently. When ready, swap the environment URLs (DNS CNAME swap). Traffic instantly shifts from Blue to Green.

  • Downtime: Near-zero (DNS swap takes seconds)
  • Deploy speed: Slowest (full new environment)
  • Rollback: Instant โ€” swap URLs back
  • Cost: Full duplicate environment during deploy
  • Best for: Critical production with zero-downtime requirements and instant rollback
BLUE / GREEN ๐Ÿ”ต Blue (prod) app.example.com Running v1 ELB + ASG + EC2 ๐ŸŸข Green (new) app-new.example.com Running v2 ELB + ASG + EC2 ๐Ÿ”„ SWAP URLs (CNAME) app.example.com โ†’ v2 Green is now prod โœ“ Blue โ†’ standby Rollback = swap back

๐Ÿ‘‰ Important distinction: Blue/Green is not a Beanstalk deployment policy โ€” it's a strategy you implement using Beanstalk's "Swap Environment URLs" feature. Beanstalk's built-in policies are: All at Once, Rolling, Rolling with Batch, and Immutable. Blue/Green is done manually or via automation by creating a second environment.

โš ๏ธ Cost warning: Blue/Green uses two complete environments. You pay for both during the transition period. For cost-sensitive workloads, Immutable deployment provides similar safety (fast rollback, no downtime) with only temporary extra capacity instead of a full duplicate environment.

Deployment Comparison โ€” All Five Strategies Core
StrategyDowntimeDeploy SpeedRollbackCostCapacity During Deploy
All at Onceโš ๏ธ Yesโšก Fastest๐Ÿข Slow (re-deploy)๐Ÿ’ฐ NoneโŒ Zero (all updating)
Rollingโœ… Noโฑ๏ธ Moderate๐Ÿข Slow (re-deploy)๐Ÿ’ฐ Noneโš ๏ธ Reduced
Rolling + Batchโœ… Noโฑ๏ธ Moderate๐Ÿข Slow (re-deploy)๐Ÿ’ฐ๐Ÿ’ฐ Temp extraโœ… Full
Immutableโœ… No๐Ÿข Slowโšก Fast (kill new ASG)๐Ÿ’ฐ๐Ÿ’ฐ๐Ÿ’ฐ Doublesโœ… Full + extra
Blue/Greenโœ… Near-zero๐Ÿข Slowestโšก Instant (URL swap)๐Ÿ’ฐ๐Ÿ’ฐ๐Ÿ’ฐ๐Ÿ’ฐ Full dupโœ… Full + duplicate
Concept Diagram โ€” Choosing a Deployment Strategy Introductory
Deployment Strategy Decision Flow
Is downtime acceptable? YES โ†’ All at Once โšก NO Need fast rollback? NO Need full capacity during deploy? NO โ†’ Rolling ๐Ÿ”„ YES โ†’ Rolling + Batch โž• YES Need instant rollback? NO โ†’ Immutable ๐Ÿ†• YES โ†’ Blue/Green ๐Ÿ”ต๐ŸŸข Cost increases left โ†’ right. Safety increases left โ†’ right. Choose based on your tolerance for downtime, rollback speed, and budget.
AWS Diagram โ€” Immutable Deployment in Action Deep
Immutable Deploy โ€” New ASG alongside Old ASG
Old ASG (v1)
EC2
EC2
v1 โœ“
EC2
EC2
v1 โœ“

Serving traffic

โ†’
SWAP
New ASG (v2)
EC2
EC2
v2 โœ“
EC2
EC2
v2 โœ“

Health checks pass โ†’ take over

ELB
ELB
Routes to new ASG after health check

Old ASG serves traffic while new ASG launches ยท Once v2 healthy โ†’ ELB switches ยท Old ASG terminates

Architecture Diagram โ€” Blue/Green CNAME Swap Deep
Blue/Green โ€” Two Environments, Swap URLs
๐ŸŒ app.example.com Route 53 (CNAME) Before swap After swap ๐Ÿ”ต BLUE ENVIRONMENT (v1) ELB (Blue) EC2 v1 EC2 v1 ASG ยท CloudWatch ๐ŸŸข GREEN ENVIRONMENT (v2) ELB (Green) EC2 v2 EC2 v2 ASG ยท CloudWatch ๐Ÿ”„ Swap Environment URLs
๐ŸŽฏ Chapter 03 Summary

Five deployment strategies โ€” choose based on downtime tolerance, rollback speed, and budget.

  • All at Once โ†’ fastest, but causes downtime. Use for dev/test only.
  • Rolling โ†’ no downtime but reduced capacity. Cost-efficient for non-critical prod.
  • Rolling + Batch โ†’ no downtime, full capacity. Slightly more expensive.
  • Immutable โ†’ no downtime, fast rollback (kill new ASG). Doubles cost during deploy.
  • Blue/Green โ†’ near-zero downtime, instant rollback (swap URLs). Full duplicate cost. Best for critical production.
  • Exam tip: know all five, know which has downtime (All at Once only), know which supports instant rollback (Immutable + Blue/Green).
04
Chapter Four

Architecture & Components

Beanstalk as an Orchestrator Introductory

Elastic Beanstalk is not a separate compute engine. It is an orchestration layer that creates, configures, and manages real AWS services on your behalf. When you create a Beanstalk environment, it generates a CloudFormation stack that provisions the following resources:

๐Ÿ–ฅ๏ธ

EC2 Instances

The actual compute. Each instance runs the platform runtime (e.g., Node.js, Java) and your application code. Beanstalk selects the AMI, installs the runtime, deploys your code, and configures the web server (Nginx/Apache).

โš–๏ธ

Elastic Load Balancer

Distributes incoming traffic across EC2 instances. Beanstalk supports ALB (HTTP/HTTPS, path-based routing), NLB (TCP, ultra-low latency), or CLB (legacy). For single-instance environments, no ELB is created.

๐Ÿ“ˆ

Auto Scaling Group

Manages the fleet of EC2 instances. Defines min, max, desired count. Launches new instances when demand rises, terminates when demand falls. Replaces unhealthy instances automatically.

๐Ÿ“Š

CloudWatch

Monitoring & alarms. Beanstalk creates CloudWatch alarms for CPU, latency, and health. Logs from instances stream to CloudWatch Logs. Enhanced health reporting provides real-time status.

๐Ÿ”’

Security Groups

Firewall rules for your instances and load balancer. Beanstalk creates SGs that allow ELB โ†’ EC2 traffic on app ports and optionally SSH access. You can customize by adding rules.

๐Ÿ“

S3 Bucket

Stores your application versions (ZIP/WAR files), logs, and configuration. Each Beanstalk application has its own S3 bucket. Versions are immutable snapshots.

Optional Services โ€” RDS, SNS, SQS Core

Beyond the core resources, Beanstalk can optionally create or integrate with additional services:

๐Ÿ—„๏ธ

Amazon RDS

  • Beanstalk can create an RDS instance inside the environment
  • Connection details auto-injected as env vars: RDS_HOSTNAME, RDS_PORT, RDS_DB_NAME, RDS_USERNAME, RDS_PASSWORD
  • โš ๏ธ Warning: If you delete the environment, the RDS instance is deleted too!
  • โœ… Best practice: Create RDS outside Beanstalk and pass the connection string as an environment variable. This decouples the database from the deployment lifecycle.
๐Ÿ””

SNS & SQS

  • SNS: Beanstalk creates an SNS topic for environment notifications (deployment events, health changes). You can subscribe your email or Lambda functions.
  • SQS: Worker environments automatically get an SQS queue. The daemon polls messages and POSTs them to your app at http://localhost/.
  • Dead letter queue support for failed messages

๐Ÿ‘‰ Exam tip: If an exam question mentions "database deleted when environment terminated" โ€” the RDS was created inside Beanstalk. The solution is always: create RDS outside the environment and reference it via environment variables.

๐Ÿšจ Critical Warning: RDS created inside Beanstalk is deleted when the environment terminates. For production, always create RDS outside Beanstalk and pass connection details via environment variables. This is a common exam question โ€” and a real-world disaster waiting to happen. There is no recovery if you accidentally terminate an environment with an embedded RDS and no snapshots.

CloudFormation Under the Hood Deep

Every Beanstalk environment is backed by a CloudFormation stack. When you create or update an environment, Beanstalk:

1๏ธโƒฃ

Generates a CFN Template

  • Defines EC2 instances, ASG, ELB, SGs, IAM roles
  • Based on your environment type + configuration
  • Template is deterministic โ€” same config = same resources
2๏ธโƒฃ

Executes the Stack

  • CloudFormation provisions all resources in order
  • Updates use stack update โ€” rolling change sets
  • Failures trigger automatic rollback
  • You can view the stack in the CloudFormation console

This means: everything Beanstalk does, you could do manually with CloudFormation. Beanstalk is a convenience layer that generates and manages CloudFormation stacks. Understanding this helps demystify what happens when something goes wrong โ€” you can always inspect the CloudFormation events for detailed error logs.

Load Balancer Types in Beanstalk Core
TypeWhen to UseFeaturesBeanstalk Config
ALB (Application)HTTP/HTTPS web apps (default)Path-based routing, HTTP/2, WebSocket, sticky sessionsLoadBalancerType: application
NLB (Network)TCP/UDP, ultra-low latency, static IPMillions of requests/sec, TLS termination, preserve source IPLoadBalancerType: network
CLB (Classic)Legacy only โ€” avoid for new projectsBasic HTTP/TCP, limited routingLoadBalancerType: classic
None (Single Instance)Dev/test, low-cost environmentsNo ELB, public IP on the EC2 instance directlyEnvironment type: single instance

๐Ÿ‘‰ Important: You cannot change the load balancer type after environment creation. If you need to switch from CLB to ALB, you must create a new environment. Plan your LB type before creating the environment.

Single Instance vs Load Balanced Core
1๏ธโƒฃ

Single Instance

  • 1 EC2 instance โ€” no ELB, no ASG
  • Public Elastic IP assigned directly
  • Cheapest option (no ELB cost)
  • No high availability โ€” if instance fails, environment is down
  • Use for: Dev, test, small personal projects
โš–๏ธ

Load Balanced

  • Multiple EC2 instances behind an ELB in an ASG
  • Traffic distributed across instances and AZs
  • Auto Scaling adds/removes instances
  • High availability โ€” survives instance failures
  • Use for: Staging, production, anything requiring uptime
Concept Diagram โ€” Resource Provisioning Flow Introductory
How Beanstalk Provisions Resources โ€” Step by Step
STEP 1 Upload code + choose platform + set config STEP 2 Store ZIP in S3 Label as version Beanstalk STEP 3 Generate CFN template CloudFormation STEP 4 โ€” Provision โœ“ EC2 instances + AMI โœ“ Auto Scaling Group โœ“ Load Balancer (ELB) โœ“ Security Groups โœ“ CloudWatch alarms โœ“ SNS topic STEP 5 Deploy code from S3 โ†’ EC2 โœ… Environment READY ELB DNS โ†’ ALB โ†’ ASG โ†’ EC2 (your code running) You upload code once โ†’ Beanstalk handles all 5 steps automatically. Future deploys repeat steps 2 + 5 only (much faster).
AWS Diagram โ€” Complete Environment Architecture Core
Beanstalk Environment โ€” All Managed Components
Elastic Beanstalk Environment
ELB
ELB
ALB / NLB / CLB
โ†’
Auto Scaling Group
EC2
EC2
Platform + App
EC2
EC2
Platform + App
EC2
+N
Scales
CloudWatch
CloudWatch
Logs + Alarms
S3
S3
App Versions
SNS
SNS
Notifications
CFN
CloudFormation
Stack Mgmt
RDS
RDS
Optional DB
SQS
SQS
Worker Queues
ElastiCache
ElastiCache
Session Store
Route 53
Route 53
Custom Domain

Solid = created by Beanstalk ยท Dashed = optional / external integration

Architecture Diagram โ€” Multi-AZ Production Environment Deep
Production Beanstalk โ€” Multi-AZ with External RDS
๐ŸŒ Users โ†’ app.example.com Route 53 (DNS) Application Load Balancer (ALB) VPC BEANSTALK ENVIRONMENT (ASG) AZ-a (us-east-1a) EC2 ยท t3.large Nginx + Node.js + App EC2 ยท t3.large Nginx + Node.js + App AZ-b (us-east-1b) EC2 ยท t3.large Nginx + Node.js + App +N (scale) on demand Amazon RDS (External) Multi-AZ PostgreSQL Primary (AZ-a) + Standby (AZ-b) โœ“ Survives env deletion ElastiCache Redis โ€” Sessions Multi-AZ replica CloudWatch Metrics + Logs + Alarms Enhanced Health S3 โ€” App Versions + Logs โ†’ = traffic flow RDS + ElastiCache external to Beanstalk (persist across env deletes)
๐ŸŽฏ Chapter 04 Summary

Beanstalk orchestrates real AWS services โ€” it's not a black box.

  • Core resources: EC2 + ASG + ELB + CloudWatch + Security Groups + S3 โ€” created automatically via CloudFormation
  • Optional: RDS (โš ๏ธ create outside env for persistence), SQS (worker envs), SNS (notifications), ElastiCache
  • Load Balancer types: ALB (HTTP, default), NLB (TCP, low latency), CLB (legacy), or None (single instance)
  • Cannot change LB type after creation โ€” plan ahead
  • Single Instance = cheapest, no HA. Load Balanced = production-grade, multi-AZ
  • Everything is a CloudFormation stack โ€” inspect it for debugging
05
Chapter Five

Scaling & High Availability

Auto Scaling in Beanstalk Introductory

Every load-balanced Beanstalk environment includes an Auto Scaling Group (ASG). The ASG manages the fleet of EC2 instances and automatically adjusts the count based on demand. You configure three key parameters:

โฌ‡๏ธ

Minimum Instances

The floor. ASG will never scale below this number. Set to at least 2 for production (one per AZ for high availability).

๐ŸŽฏ

Desired Instances

The target count ASG tries to maintain. Auto Scaling adjusts this value automatically based on scaling policies. Usually starts at minimum.

โฌ†๏ธ

Maximum Instances

The ceiling. ASG will never scale above this number. Protects against runaway scaling and unexpected costs. Set based on budget.

Scaling Triggers & Policies Core

Beanstalk uses CloudWatch metrics to decide when to scale. You can configure scaling policies based on several triggers:

MetricScales Out WhenScales In WhenBest For
CPUUtilizationCPU > 70% (avg 5 min)CPU < 30%CPU-bound workloads (image processing, computation)
NetworkOutNetwork > thresholdNetwork < thresholdData-heavy APIs, file transfers
LatencyResponse time > thresholdResponse < thresholdWeb apps where user experience matters
RequestCountRequests/instance > thresholdRequests < thresholdRequest-driven APIs, even load distribution
HealthyHostCountHealthy hosts < desiredโ€”Maintaining minimum healthy capacity
SQS Queue DepthMessages > thresholdQueue emptyWorker environments processing async jobs

๐Ÿ‘‰ Default scaling metric: NetworkOut. For most web apps, CPUUtilization or RequestCount are better choices. Always tune the scaling metric for your specific workload โ€” don't rely on defaults.

โš ๏ธ What NOT to scale on: Avoid scaling on NetworkIn โ€” it measures incoming data volume, not application load. A single large file upload can trigger unnecessary scale-out. Also avoid DiskReadOps unless your workload is explicitly disk-bound. Stick with CPU, RequestCount, or Latency for most web applications.

Scaling Policy Types Core
๐ŸŽฏ

Target Tracking (Recommended)

  • Set a target value (e.g., "keep CPU at 50%")
  • ASG automatically adjusts to maintain the target
  • Simplest to configure โ€” AWS handles the math
  • Similar to a thermostat: set the temp, system adjusts
๐Ÿ“

Step Scaling

  • Define specific thresholds and how many instances to add/remove
  • E.g., "CPU > 60%: +1", "CPU > 80%: +3"
  • More control than target tracking
  • Useful when you need different scale amounts at different thresholds
โฐ

Scheduled Scaling

  • Scale at specific times (cron-based)
  • E.g., "scale to 10 instances at 9 AM, scale to 2 at 10 PM"
  • Best for predictable traffic patterns (business hours, marketing events)
  • Can combine with target tracking for hybrid approach
โฑ๏ธ

Cooldown Period

  • After a scaling action, ASG waits before scaling again
  • Default: 300 seconds (5 minutes)
  • Prevents "thrashing" โ€” rapidly adding/removing instances
  • Tune shorter for fast-changing workloads, longer for gradual changes
Health Checks โ€” Basic vs Enhanced Core

Beanstalk uses health checks to determine if instances are working correctly. There are two levels:

๐Ÿ’š

Basic Health

  • Checks ELB health check endpoint (default: HTTP 200 on /)
  • Binary: Healthy or Unhealthy
  • EC2 instance status checks
  • Limited information โ€” only tells you "up or down"
  • Free โ€” included by default
๐Ÿ’š๐Ÿ’›๐Ÿ”ด

Enhanced Health (Recommended)

  • Beanstalk agent on each instance reports detailed metrics
  • Color-coded: Green (Ok), Yellow (Warning), Red (Degraded), Grey (Unknown)
  • Monitors: CPU, requests, latency, 2xx/3xx/4xx/5xx counts
  • Application-level health โ€” not just "port open"
  • Health history and dashboard in Beanstalk console
  • Requires Beanstalk enhanced health reporting IAM role
Health ColorMeaningAction
๐ŸŸข GreenAll instances healthy, passing health checksNo action needed
๐ŸŸก YellowSome requests failing or latency highInvestigate โ€” may self-resolve
๐Ÿ”ด RedMultiple instances unhealthy, service degradedImmediate investigation. Check app logs
โšช GreyUpdating, initializing, or insufficient dataWait โ€” usually resolves after deployment

Enhanced Health requires the service role aws-elasticbeanstalk-service-role with the AWSElasticBeanstalkEnhancedHealth managed policy attached. Beanstalk creates this automatically when you launch an environment with enhanced health enabled via the console or EB CLI.

High Availability โ€” Multi-AZ Best Practices Deep

To achieve true high availability with Beanstalk, your environment should survive the failure of an entire Availability Zone:

โœ…

HA Best Practices

  • Use Load Balanced environment (not single instance)
  • Set minimum 2 instances across 2+ AZs
  • Use ALB โ€” it routes to healthy instances across AZs
  • Enable cross-zone load balancing (default with ALB)
  • Use external RDS with Multi-AZ deployment
  • Enable Enhanced Health for faster failure detection
  • Store sessions in ElastiCache (not in-memory on EC2)
  • Set appropriate health check grace period (give instances time to boot)
โŒ

Common HA Mistakes

  • Single instance environment in production
  • All instances in one AZ
  • RDS inside Beanstalk (deleted with env)
  • Sticky sessions without external session store
  • No health check path configured (using default /)
  • Max instances = min instances (no room to scale)
  • Cooldown too long โ€” can't react to sudden traffic
Concept Diagram โ€” Scaling Decision Flow Introductory
Auto Scaling โ€” How Beanstalk Decides to Scale
CloudWatch CPU: 85% Requests: 2000/min Latency: 450ms โš ๏ธ Threshold breached ALARM ๐Ÿ”” CPU > 70% ASG Policy Current: 2 instances Max: 6 instances Action: +2 instances Cooldown: 300s SCALE OUT Launch 2 new EC2 Register with ELB Health check passes โœ“ Now 4 instances SCALE IN (later, when demand drops) CPU < 30% โ†’ Alarm โ†’ ASG โ†’ Terminate 2 instances โ†’ Back to 2 Monitor (CloudWatch) โ†’ Alarm (threshold) โ†’ Scaling Policy (action) โ†’ Launch/Terminate (EC2) โ†’ Cooldown โ†’ Repeat
AWS Diagram โ€” Auto Scaling Components Core
Beanstalk Auto Scaling โ€” Services Involved
CloudWatch
CloudWatch
Metrics + Alarms
โ†’
Auto Scaling
Auto Scaling
Scaling Policies
โ†’
EC2
EC2
Launch / Terminate
โ†’
ELB
ELB
Register / Deregister

Scaling Flow

๐Ÿ“Š
1. CloudWatch
Detects CPU > 70%
๐Ÿ””
2. Alarm Fires
Triggers policy
๐Ÿš€
3. ASG Launches
New EC2 instance
โœ…
4. ELB Registers
Receives traffic

CloudWatch monitors โ†’ Alarm triggers scaling policy โ†’ ASG launches/terminates EC2 โ†’ ELB registers/deregisters targets

Architecture Diagram โ€” High Availability Scaling Deep
HA Beanstalk โ€” Scaling Across Availability Zones
๐ŸŒ Peak Traffic โ€” 10,000 req/min ALB โ€” Cross-Zone Load Balancing Distributes evenly across all AZs ASG: min=2, max=8, desired=6 AZ-a (us-east-1a) EC2 ๐Ÿ’š Healthy EC2 ๐Ÿ’š Healthy EC2 NEW ๐Ÿ†• Scaled out AZ-b (us-east-1b) EC2 ๐Ÿ’š Healthy EC2 ๐Ÿ’š Healthy EC2 NEW ๐Ÿ†• Scaled out AZ-c (us-east-1c) Available for scaling max=8, currently 6 Room for 2 more CloudWatch โ†’ CPU 85% โ†’ Alarm โ†’ ASG scaled 4โ†’6 ASG distributes instances across AZs ยท ALB routes traffic evenly ยท If AZ-a fails, AZ-b + AZ-c continue serving
๐ŸŽฏ Chapter 05 Summary

Beanstalk Auto Scaling keeps your app responsive under any load.

  • ASG parameters: min (floor), desired (target), max (ceiling) โ€” always set min โ‰ฅ 2 for HA
  • Scaling triggers: CPUUtilization, RequestCount, Latency, NetworkOut, SQS queue depth
  • Policy types: Target Tracking (simplest), Step Scaling (granular), Scheduled (predictable patterns)
  • Health checks: Basic (up/down) vs Enhanced (color-coded, detailed metrics โ€” recommended)
  • HA best practices: Multi-AZ, external RDS (Multi-AZ), ElastiCache for sessions, min 2 instances
  • Exam tip: Know scaling policies, health check types, and why external RDS is critical for HA
06
Chapter Six

Configuration & Customization

Configuration Layers โ€” Priority Order Introductory

Beanstalk applies configuration from multiple sources. When settings conflict, higher-priority sources override lower ones. Understanding this order prevents "why isn't my setting applied?" confusion:

๐Ÿ†

Priority Order (Highest โ†’ Lowest)

  1. Direct environment settings โ€” Console, CLI, API changes
  2. Saved configurations โ€” Reusable config templates
  3. .ebextensions โ€” Config files inside your source bundle
  4. Platform defaults โ€” What the platform provides out of the box

If you set an instance type in the console AND in .ebextensions, the console value wins.

๐Ÿ’ก

Why This Matters

  • Use .ebextensions for version-controlled defaults (lives in your code repo)
  • Use saved configurations for environment-specific overrides (prod vs dev)
  • Use direct settings for quick one-off changes (hotfixes, debugging)
  • Platform defaults handle things you usually don't need to change
Environment Variables Core

Environment variables are the simplest and most common way to configure your application in Beanstalk. They inject runtime configuration without changing your code โ€” database URLs, API keys, feature flags.

โš™๏ธ

How to Set Them

  • Console: Configuration โ†’ Software โ†’ Environment properties
  • CLI: eb setenv DB_HOST=mydb.123.rds.amazonaws.com
  • .ebextensions: In YAML config files (version-controlled)
  • EB CLI: eb config to edit interactively
๐Ÿ“‹

Common Env Vars

  • NODE_ENV=production
  • DATABASE_URL=postgres://...
  • API_KEY=sk-xxxxx
  • LOG_LEVEL=info
  • PORT=8080 (Beanstalk sets this automatically)

๐Ÿ‘‰ Security tip: For sensitive values (API keys, database passwords), use AWS Secrets Manager or SSM Parameter Store instead of environment variables. Env vars are visible in the console and in CloudFormation templates. Secrets Manager encrypts values at rest and supports automatic rotation.

.ebextensions โ€” Infrastructure as Code Core

The .ebextensions directory is the most powerful customization tool in Beanstalk. It contains YAML or JSON config files that execute during deployment. You place this directory in the root of your source bundle:

๐Ÿ“

File Structure

my-app/
โ”œโ”€โ”€ .ebextensions/
โ”‚   โ”œโ”€โ”€ 01-env-vars.config
โ”‚   โ”œโ”€โ”€ 02-packages.config
โ”‚   โ”œโ”€โ”€ 03-nginx.config
โ”‚   โ””โ”€โ”€ 04-custom-logs.config
โ”œโ”€โ”€ app.js
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ ...

Files execute in alphabetical order. Prefix with numbers to control ordering.

๐Ÿ”ง

What You Can Configure

  • option_settings โ€” Set any Beanstalk configuration option
  • packages โ€” Install yum/apt packages (e.g., ImageMagick)
  • sources โ€” Download and extract archives
  • files โ€” Create files on the instance (configs, scripts)
  • commands โ€” Run shell commands before app deploys
  • container_commands โ€” Run after app code extracted but before launch
  • Resources โ€” Create additional CloudFormation resources (RDS, DynamoDB, SQS)

Example โ€” 01-env-vars.config:

option_settings:
  aws:elasticbeanstalk:application:environment:
    NODE_ENV: production
    LOG_LEVEL: info

  aws:autoscaling:asg:
    MinSize: 2
    MaxSize: 6

  aws:autoscaling:launchconfiguration:
    InstanceType: t3.medium

  aws:elasticbeanstalk:environment:
    LoadBalancerType: application

Example โ€” 02-packages.config:

packages:
  yum:
    ImageMagick: []
    git: []

commands:
  01_setup_timezone:
    command: "ln -sf /usr/share/zoneinfo/UTC /etc/localtime"

container_commands:
  01_run_migrations:
    command: "npm run migrate"
    leader_only: true          # Only runs on ONE instance
  02_seed_data:
    command: "npm run seed"
    leader_only: true          # Only runs on ONE instance
  03_clear_cache:
    command: "npm run cache:clear"
    leader_only: false         # Runs on EVERY instance

๐Ÿ‘‰ leader_only: true ensures a container_command runs on only one instance โ€” essential for database migrations. Without it, every instance would run the migration simultaneously, causing conflicts.

Platform Hooks โ€” Modern Customization Deep

Platform hooks are the newer, recommended way to run scripts during the deployment lifecycle. They replace the older commands and container_commands in .ebextensions with a clearer, lifecycle-based structure:

๐Ÿ“

Hook Directories

.platform/
โ”œโ”€โ”€ hooks/
โ”‚   โ”œโ”€โ”€ prebuild/    โ† Before build
โ”‚   โ”œโ”€โ”€ predeploy/   โ† Before app starts
โ”‚   โ””โ”€โ”€ postdeploy/  โ† After app starts
โ”œโ”€โ”€ confighooks/
โ”‚   โ”œโ”€โ”€ prebuild/
โ”‚   โ”œโ”€โ”€ predeploy/
โ”‚   โ””โ”€โ”€ postdeploy/
โ””โ”€โ”€ nginx/
    โ””โ”€โ”€ conf.d/
        โ””โ”€โ”€ custom.conf
๐Ÿ”„

Lifecycle Stages

  • prebuild/ โ€” Before source code is built. Install dependencies, set up tools.
  • predeploy/ โ€” After build, before app launches. Run DB migrations, compile assets.
  • postdeploy/ โ€” After app is running and healthy. Send notifications, warm caches.
  • confighooks/ โ€” Same stages, but triggered on config changes (not deploys)
  • Scripts must be executable (chmod +x) and use a shebang (#!/bin/bash)
Feature.ebextensionsPlatform Hooks
IntroducedOriginal (legacy)Amazon Linux 2+ (modern)
Execution orderAlphabetical file orderAlphabetical within lifecycle stage
Lifecycle claritycommands vs container_commands (confusing)Clear: prebuild / predeploy / postdeploy
Config changesNo separate stageconfighooks/ for config-only changes
CloudFormation resourcesโœ… Supported (Resources key)โŒ Not supported โ€” still use .ebextensions
RecommendationUse for option_settings + Resources onlyUse for all scripts and commands
Custom AMI โ€” Pre-baked Images Deep

If your .ebextensions or platform hooks install many packages or take a long time, you can bake a custom AMI โ€” an image with everything pre-installed. This dramatically reduces deployment time because instances boot with all dependencies already present.

๐Ÿ–ผ๏ธ

When to Use Custom AMIs

  • Large package installations (ML libraries, native compilers)
  • Deployment time is too slow (> 10 minutes per instance)
  • Need custom OS configuration (kernel tuning, security hardening)
  • Compliance requirements (pre-approved base images)
โš ๏ธ

Considerations

  • Start from the Beanstalk platform AMI โ€” don't build from scratch
  • You must maintain and update the AMI yourself (OS patches, runtime updates)
  • Set via: aws:autoscaling:launchconfiguration โ†’ ImageId
  • Use Packer (by HashiCorp) to automate AMI building
  • Combine with .ebextensions for app-specific config on top of the pre-baked image
Nginx / Proxy Customization Core

Beanstalk platforms (Amazon Linux 2+) use Nginx as the reverse proxy in front of your application. You can customize Nginx by placing config files in your source bundle:

๐Ÿ”ง

Custom Nginx Config

# .platform/nginx/conf.d/proxy.conf
client_max_body_size 50M;
proxy_read_timeout 300s;

# Custom headers
add_header X-Frame-Options "DENY";
add_header X-Content-Type "nosniff";
๐Ÿ”„

Full Nginx Override

# .platform/nginx/nginx.conf
# Complete replacement โ€” use with care
# Must include all required directives

# Useful for:
# - Custom routing
# - WebSocket support
# - Gzip configuration
# - Static file serving
Concept Diagram โ€” Configuration Priority Stack Introductory
Configuration Sources โ€” Priority Order (Top Wins)
โ‘  Direct Environment Settings Console ยท CLI ยท API โ€” immediate, highest precedence โ‘ก Saved Configurations Reusable templates โ€” apply per environment (prod vs dev) โ‘ข .ebextensions (in source bundle) Version-controlled ยท lives in your code repo ยท shared defaults โ‘ฃ Platform Defaults AWS managed โ€” sensible defaults for the chosen runtime HIGHEST LOWEST When the same setting exists at multiple levels, the higher-priority source always wins.
AWS Diagram โ€” Customization Touchpoints Core
Where Configuration Applies in the Stack
โš™๏ธ Application Config

Environment Variables

DB_HOST, API_KEY, NODE_ENV

Secrets Manager

Encrypted secrets at runtime

๐Ÿ—๏ธ Platform Config

.platform/hooks/

Lifecycle scripts

.platform/nginx/

Proxy customization

Custom AMI

Pre-baked dependencies

โ˜๏ธ Infrastructure Config

.ebextensions/

Instance type, ASG, ELB

Resources (CFN)

Extra RDS, SQS, DynamoDB

Saved Configs

Reusable templates

EC2
EC2
Env vars + hooks
ELB
ELB
.ebextensions
ASG
ASG
.ebextensions
CloudWatch
CloudWatch
Auto-configured
CFN
CloudFormation
Resources key

Application config โ†’ your code reads env vars ยท Platform config โ†’ hooks + nginx ยท Infrastructure config โ†’ .ebextensions + CFN

Architecture Diagram โ€” Deployment with Configuration Deep
Source Bundle โ†’ Configuration Processing โ†’ Running Environment
SOURCE BUNDLE app.js (your code) .ebextensions/*.config .platform/hooks/* .platform/nginx/* package.json / pom.xml upload BEANSTALK PROCESSES 1. Store ZIP โ†’ S3 2. Read .ebextensions 3. Merge config layers 4. Update CFN stack 5. Run hooks 6. Apply nginx config 7. Start app โœ“ RUNNING EC2 INSTANCE Amazon Linux 2023 (OS) Nginx (reverse proxy โ€” custom config applied) Node.js 18 Runtime (platform) Your Application Code (app.js) Env Vars: DB_HOST, NODE_ENV, API_KEY Secrets Manager / SSM Encrypted secrets at runtime Source bundle contains code + config โ†’ Beanstalk merges all layers โ†’ EC2 runs with OS + proxy + runtime + app + secrets
๐ŸŽฏ Chapter 06 Summary

Beanstalk offers multiple configuration layers โ€” use the right tool for the right job.

  • Priority order: Direct settings > Saved configs > .ebextensions > Platform defaults
  • Environment variables โ€” simplest config. Use Secrets Manager for sensitive values.
  • .ebextensions โ€” powerful YAML configs for option_settings, packages, commands, and CloudFormation Resources
  • Platform hooks (.platform/hooks/) โ€” modern lifecycle scripts: prebuild โ†’ predeploy โ†’ postdeploy
  • Custom AMI โ€” pre-bake dependencies for faster deploys. Maintain and update yourself.
  • Nginx โ€” customize via .platform/nginx/conf.d/ or full override. Don't forget client_max_body_size!
  • leader_only: true โ€” run a command on only one instance (critical for DB migrations)
07
Chapter Seven

Architecture Patterns

Pattern 1 โ€” Simple Web Application Introductory

The most common Beanstalk pattern: a single-tier web application with all components managed by one Beanstalk environment. Suitable for most small to medium applications.

๐ŸŒ

Architecture

  • Web Server Environment โ€” ALB + ASG + EC2
  • Single codebase handles all requests
  • External RDS for persistence
  • ElastiCache for sessions (optional)
  • CloudFront for static assets (optional)
โœ…

When to Use

  • Standard web apps, REST APIs, admin dashboards
  • Small to medium traffic (up to thousands req/sec)
  • Single team, single deployment unit
  • Quick time-to-market โ€” simplest architecture
  • Monolithic applications (not microservices)
Pattern 2 โ€” Web + Worker (Decoupled) Core

For applications with both user-facing traffic and heavy background processing. Separate the two concerns into two Beanstalk environments connected by SQS.

๐ŸŒ

Web Tier

  • Web Server Environment
  • Handles HTTP requests
  • Sends heavy tasks to SQS
  • Responds immediately to user
๐Ÿ“ฌ

Message Queue

  • SQS Standard or FIFO
  • Decouples web from worker
  • Buffers work during spikes
  • Dead letter queue for failures
โš™๏ธ

Worker Tier

  • Worker Environment
  • Polls SQS, processes tasks
  • Scales on queue depth
  • No internet traffic

๐Ÿ‘‰ Real-world examples: E-commerce site (web = product browsing, worker = order processing + email). Photo app (web = upload UI, worker = image resizing + thumbnail generation). SaaS (web = dashboard, worker = report generation + data exports).

Pattern 3 โ€” Blue/Green CI/CD Pipeline Deep

For teams that need zero-downtime deployments with instant rollback capability. Combine Beanstalk's URL swap with a CI/CD pipeline for fully automated releases.

๐Ÿ”„

Pipeline Flow

  1. Developer pushes code to CodeCommit / GitHub
  2. CodePipeline detects change, triggers build
  3. CodeBuild runs tests, creates artifact
  4. Deploy to Green environment (new)
  5. Run smoke tests on Green
  6. Swap URLs โ€” Green becomes production
  7. Old Blue available for instant rollback
โšก

Benefits

  • Zero downtime โ€” users never see an outage
  • Instant rollback โ€” swap URLs back in seconds
  • Testing in production infra โ€” Green has same config as Blue
  • Canary-like โ€” test with Route 53 weighted routing before full swap
  • Full automation via CodePipeline
Pattern 4 โ€” Docker on Beanstalk Core

When your application runs in Docker containers but you don't need the complexity of ECS or EKS, Beanstalk's Docker platform is the simplest path. Just provide a Dockerfile or docker-compose.yml.

๐Ÿณ

Single-Container Docker

  • One Docker container per EC2 instance
  • Provide a Dockerfile or Dockerrun.aws.json
  • Beanstalk builds and runs the container
  • Simplest Docker deployment on AWS
  • Standard ALB + ASG + Auto Scaling
๐Ÿณ๐Ÿณ

Multi-Container Docker

  • Multiple containers per EC2 (via ECS under the hood)
  • Define with Dockerrun.aws.json v2
  • Sidecar pattern โ€” app + logging + monitoring containers
  • More complex โ€” consider ECS for production multi-container
  • โš ๏ธ Retired on Amazon Linux 2 โ€” use ECS instead

๐Ÿ‘‰ Docker vs Native Platform: Use Docker when you need a specific runtime version not offered by Beanstalk, or when your team already uses Docker for local development. For standard Node.js/Java/Python apps, the native platform is simpler and faster to deploy.

โš ๏ธ Multi-container Docker migration: The multi-container Docker platform (Dockerrun.aws.json v2) is not available on Amazon Linux 2023. For existing multi-container environments on Amazon Linux 2, migrate to ECS on EC2 or ECS on Fargate before the AL2 platform reaches end of life. For single-container workloads, the AL2023 Docker platform is the recommended path forward.

Concept Diagram โ€” Choosing the Right Pattern Introductory
Architecture Pattern Decision Guide
What's your workload? Simple web/API Pattern 1: Simple Web App ALB + ASG + External RDS + async tasks Pattern 2: Web + Worker Web โ†’ SQS โ†’ Worker Zero-downtime deploy Pattern 3: Blue/Green Dual env + URL swap Using Docker? YES Pattern 4: Docker on EB Dockerfile + Beanstalk Microservices? Consider ECS / EKS Beanstalk = monolith/simple Beanstalk excels at standard web apps. For complex microservices โ†’ ECS. For event-driven โ†’ Lambda.
AWS Diagram โ€” Blue/Green CI/CD Pipeline Deep
Automated Blue/Green Deployment Pipeline
๐Ÿ‘จโ€๐Ÿ’ป
Developer
git push
โ†’
CodePipeline
CodePipeline
Orchestrate
โ†’
CodeDeploy
Build & Test
CodeBuild
โ†’
EB
EB Green
Deploy v2
โ†’
๐Ÿ”„
Swap URLs
CNAME Swap
๐Ÿ”ต Blue (current prod)
ELB
ELB
โ†’
EC2
v1
EC2
v1
๐ŸŸข Green (new version)
ELB
ELB
โ†’
EC2
v2
EC2
v2

git push โ†’ CodePipeline โ†’ Build โ†’ Deploy to Green โ†’ Smoke test โ†’ Swap URLs โ†’ Green is prod ยท Blue = rollback target

Architecture Diagram โ€” Complete Production Stack Deep
Production Beanstalk โ€” Web + Worker + CI/CD + External Services
CI/CD PIPELINE GitHub โ†’ CodePipeline โ†’ CodeBuild โ†’ Deploy to Beanstalk โ†’ Swap URLs Blue/Green Automated ๐ŸŒ Users โ†’ Route 53 โ†’ CloudFront (CDN) CloudFront โ€” Static assets cached at edge Application Load Balancer WEB SERVER ENV ALB + ASG + 2-6 EC2 EC2 REST API EC2 REST API +N SQS Queue send WORKER ENV SQS + ASG + 1-4 EC2 EC2 Worker EC2 Worker poll RDS (External) Multi-AZ PostgreSQL โœ“ Persists ElastiCache Redis Sessions S3 User Uploads + Assets CloudWatch Metrics ยท Logs ยท Alarms FULL PRODUCTION PATTERN โ€” KEY DECISIONS External RDS (persist) ยท ElastiCache (sessions) ยท CloudFront (CDN) ยท Web+Worker (decouple) ยท Blue/Green (zero-downtime) ยท CloudWatch (observe)
๐ŸŽฏ Chapter 07 Summary

Choose the right Beanstalk pattern based on your workload complexity.

  • Pattern 1 โ€” Simple Web App: Single env, ALB + ASG + external RDS. Best for monoliths and standard web apps.
  • Pattern 2 โ€” Web + Worker: Two envs connected by SQS. Decouple request handling from heavy processing.
  • Pattern 3 โ€” Blue/Green CI/CD: Automated pipeline with dual environments. Zero-downtime deployments + instant rollback.
  • Pattern 4 โ€” Docker: Run containers on Beanstalk with a Dockerfile. Simplest Docker deployment on AWS.
  • When Beanstalk isn't enough: Use ECS/EKS for microservices, Lambda for event-driven, raw EC2 for full control.
  • Production checklist: External RDS (Multi-AZ) ยท ElastiCache (sessions) ยท CloudFront (CDN) ยท Enhanced Health ยท Blue/Green deploys
๐Ÿ“š
Quick Reference

Beanstalk Cheatsheet

EB CLI โ€” Essential Commands Core
CommandWhat It DoesWhen to Use
eb initInitialize EB application in current directoryFirst-time project setup
eb createCreate a new environmentNew environment (dev, staging, prod)
eb deployDeploy current code to environmentPush a new version
eb openOpen environment URL in browserQuick access to running app
eb healthShow real-time health statusMonitor instance health
eb logsFetch and display logsDebugging issues
eb setenv KEY=valueSet environment variableRuntime configuration
eb configView/edit environment configurationChange scaling, instance type, etc.
eb swap env1 --destination_name env2Swap CNAMEs between environmentsBlue/Green deployment
eb statusShow environment info (URL, health, platform)Check environment state
eb terminateDelete environment and all resourcesTear down env (โš ๏ธ destructive)
eb abortCancel in-progress environment updateRolling back a bad deploy
eb cloneClone an existing environmentCreate staging from prod config
eb scale NSet number of running instancesManual scaling
.ebextensions โ€” Common Configuration Namespaces Core
NamespaceSettingExample ValuePurpose
aws:autoscaling:asgMinSize2Minimum instances
aws:autoscaling:asgMaxSize6Maximum instances
aws:autoscaling:launchconfigurationInstanceTypet3.mediumEC2 instance size
aws:autoscaling:launchconfigurationIamInstanceProfileaws-elasticbeanstalk-ec2-roleInstance IAM role
aws:elasticbeanstalk:environmentLoadBalancerTypeapplicationALB / NLB / classic
aws:elasticbeanstalk:environmentServiceRoleaws-elasticbeanstalk-service-roleBeanstalk service role
aws:elasticbeanstalk:application:environmentNODE_ENVproductionApp env variable
aws:elasticbeanstalk:healthreporting:systemSystemTypeenhancedEnable enhanced health
aws:elasticbeanstalk:commandDeploymentPolicyRollingDeployment strategy
aws:elasticbeanstalk:commandBatchSizeTypePercentageBatch size unit
aws:elasticbeanstalk:commandBatchSize25% of instances per batch
aws:autoscaling:triggerMeasureNameCPUUtilizationScaling metric
aws:autoscaling:triggerUpperThreshold70Scale out threshold
aws:autoscaling:triggerLowerThreshold30Scale in threshold
Health Check Colors โ€” Quick Reference Introductory
๐ŸŸข

Green

Healthy. All instances passing. No action needed.

๐ŸŸก

Yellow

Warning. Some failures or high latency. Investigate.

๐Ÿ”ด

Red

Degraded. Multiple unhealthy instances. Immediate action.

โšช

Grey

Unknown. Updating or insufficient data. Wait.

Deployment Strategies โ€” Quick Decision Core
StrategyDowntime?Rollback SpeedExtra Cost?Use For
All at Onceโš ๏ธ Yes๐Ÿข SlowNoneDev / test only
Rollingโœ… No๐Ÿข SlowNoneCost-sensitive prod
Rolling + Batchโœ… No๐Ÿข SlowTemp extraProd, full capacity
Immutableโœ… Noโšก Fast2x during deployProd, safe rollback
Blue/Greenโœ… Noโšก InstantFull duplicateCritical prod, zero risk
File Structure โ€” Beanstalk Source Bundle Core
my-app/
โ”œโ”€โ”€ .ebextensions/                 โ† Infrastructure config (YAML)
โ”‚   โ”œโ”€โ”€ 01-env-vars.config         โ† Environment variables + scaling
โ”‚   โ”œโ”€โ”€ 02-packages.config         โ† yum packages + commands
โ”‚   โ””โ”€โ”€ 03-resources.config        โ† Extra CloudFormation resources
โ”œโ”€โ”€ .platform/                     โ† Platform customization (AL2023)
โ”‚   โ”œโ”€โ”€ hooks/
โ”‚   โ”‚   โ”œโ”€โ”€ prebuild/              โ† Before build (install deps)
โ”‚   โ”‚   โ”œโ”€โ”€ predeploy/             โ† Before app starts (migrations)
โ”‚   โ”‚   โ””โ”€โ”€ postdeploy/            โ† After app running (warmup)
โ”‚   โ”œโ”€โ”€ confighooks/               โ† Same stages, config changes only
โ”‚   โ””โ”€โ”€ nginx/
โ”‚       โ””โ”€โ”€ conf.d/
โ”‚           โ””โ”€โ”€ proxy.conf         โ† Custom Nginx settings
โ”œโ”€โ”€ app.js                         โ† Your application code
โ”œโ”€โ”€ package.json                   โ† Dependencies
โ””โ”€โ”€ Procfile                       โ† (Optional) custom start command
    web: node app.js --port $PORT
Exam โ€” Key Points to Remember Deep
๐Ÿ“

Frequently Tested

  • RDS inside Beanstalk = deleted on env terminate. Always create externally.
  • Blue/Green = URL swap, not built-in deployment policy
  • Immutable = new ASG, fast rollback. All at Once = only one with downtime.
  • Cannot change LB type after creation
  • Worker environments use SQS, no load balancer
  • .ebextensions for config, platform hooks for scripts
  • leader_only: true for DB migrations
  • Beanstalk is free โ€” you pay for underlying resources only
๐Ÿง 

Common Traps

  • "Beanstalk doesn't support Docker" โ€” โŒ It does (Dockerfile or Dockerrun.aws.json)
  • "Beanstalk is serverless" โ€” โŒ EC2 instances run 24/7
  • "You can't SSH into Beanstalk instances" โ€” โŒ You can
  • "Blue/Green is a deployment policy" โ€” โŒ It's a URL swap strategy
  • "Enhanced health is enabled by default" โ€” โŒ Must be explicitly enabled
  • "Rolling deployment has downtime" โ€” โŒ Only All at Once has downtime
  • "Beanstalk manages its own separate compute" โ€” โŒ Uses EC2 under the hood
๐Ÿ Elastic Beanstalk โ€” The Complete Picture

Beanstalk = PaaS convenience + IaaS transparency. Valet parking for your code.

  • Upload code โ†’ Beanstalk creates EC2, ASG, ELB, CloudWatch, S3, SNS via CloudFormation
  • 5 deploy strategies โ€” All at Once (dev), Rolling (cheap), Rolling+Batch (safe), Immutable (safer), Blue/Green (safest)
  • 2 env types โ€” Web Server (HTTP) and Worker (SQS)
  • Configure via โ€” env vars, .ebextensions, platform hooks, saved configs, custom AMI
  • Scale via โ€” Target tracking, step scaling, or scheduled. Enhanced health for real-time monitoring.
  • Production must-haves โ€” External RDS, Multi-AZ, ElastiCache, Enhanced Health, Immutable or Blue/Green deploys