Skip to content

AWS Elastic Beanstalk

Service Overview and Purpose

AWS Elastic Beanstalk is a Platform-as-a-Service (PaaS) offering that makes it easy to deploy and manage applications in the AWS Cloud. You simply upload your code, and Elastic Beanstalk automatically handles the deployment details of capacity provisioning, load balancing, auto-scaling, and application health monitoring.

Core Purpose: - Simplify application deployment and management - Provide a platform-as-a-service (PaaS) solution - Enable rapid application development and deployment - Maintain full control over underlying AWS resources - Support multiple programming languages and frameworks

Key Features and Capabilities

Core Features

  • Easy Deployment: Upload code and deploy with a few clicks
  • Automatic Scaling: Built-in auto scaling and load balancing
  • Health Monitoring: Application health dashboard and alerts
  • Version Management: Application version control and rollback
  • Configuration Management: Environment configuration templates
  • Integration: Deep integration with AWS services
  • Multiple Platforms: Support for various programming languages
  • Cost Optimization: No additional charges for the service itself

Supported Platforms

  • Java: Tomcat, Java SE
  • NET: Windows Server with IIS
  • .NET Core: Linux and Windows
  • PHP: Apache HTTP Server
  • Node.js: Node.js runtime
  • Python: Apache HTTP Server with mod_wsgi
  • Ruby: Passenger or Puma
  • Go: Go runtime
  • Docker: Docker containers

Deployment Options

  • All at Once: Deploy to all instances simultaneously
  • Rolling: Deploy in batches with zero downtime
  • Rolling with Additional Batch: Deploy with additional instances
  • Immutable: Deploy to fresh instances, then swap
  • Blue/Green: Deploy to separate environment, then swap URLs

Use Cases and Scenarios

Primary Use Cases

  1. Web Applications
  2. Traditional three-tier web applications
  3. Content management systems
  4. E-commerce platforms
  5. Blog and portfolio websites

  6. API Development

  7. RESTful API backends
  8. Microservices development
  9. Third-party API integrations
  10. Mobile app backends

  11. Development and Testing

  12. Development environments
  13. Staging environments
  14. Proof of concepts
  15. Prototyping

  16. Legacy Application Migration

  17. Lift and shift migrations
  18. Application modernization
  19. Cloud-first development
  20. Hybrid deployments

  21. Educational and Learning

  22. Learning cloud development
  23. Student projects
  24. Training environments
  25. Experimentation platforms

Detailed Scenarios

E-commerce Platform

Frontend (React/Angular) β†’ Load Balancer β†’ Elastic Beanstalk (Node.js/Java)
                                        ↓
                                   RDS Database
                                        ↓
                                S3 (Static Assets)

API Backend Service

Mobile/Web App β†’ API Gateway β†’ Elastic Beanstalk (Python/Java)
                            ↓
                       DynamoDB/RDS
                            ↓
                    ElastiCache (Caching)

Multi-Environment Pipeline

Development β†’ Staging β†’ Production
     ↓           ↓         ↓
EB Environment β†’ EB Environment β†’ EB Environment
     ↓           ↓         ↓
Git Repository β†’ CI/CD Pipeline β†’ Automated Deployment

WordPress Website

Users β†’ CloudFront β†’ Load Balancer β†’ Elastic Beanstalk (PHP)
                                   ↓
                              RDS (MySQL)
                                   ↓
                              EFS (Shared Files)

Pricing Models and Cost Optimization

Pricing Structure

Elastic Beanstalk Service

  • No Additional Charges: Elastic Beanstalk itself is free
  • Pay for Resources: Only pay for underlying AWS resources
  • Resource Costs: EC2, Load Balancers, Auto Scaling, etc.

Underlying Resource Costs

  1. EC2 Instances: Based on instance types and usage
  2. Load Balancers: Application Load Balancer or Classic Load Balancer
  3. Auto Scaling: No additional charges for Auto Scaling service
  4. Storage: EBS volumes, S3 storage for application versions
  5. Data Transfer: Standard AWS data transfer rates

Cost Optimization Strategies

  1. Right-size Instances
  2. Monitor application performance and resource usage
  3. Use appropriate instance types for workload
  4. Implement auto scaling to match demand
  5. Consider Spot instances for development environments

  6. Environment Management

  7. Terminate unused environments
  8. Use saved configurations for quick recreation
  9. Schedule environments for development/testing
  10. Implement environment lifecycle policies

  11. Load Balancer Optimization

  12. Choose appropriate load balancer type
  13. Use single AZ for development environments
  14. Implement health checks efficiently
  15. Optimize target group configurations

  16. Storage Optimization

  17. Clean up old application versions
  18. Use S3 lifecycle policies
  19. Optimize EBS volume types and sizes
  20. Implement data compression

  21. Monitoring and Alerts

  22. Set up cost alerts and budgets
  23. Monitor resource utilization regularly
  24. Use AWS Cost Explorer for analysis
  25. Implement resource tagging for cost allocation

Configuration Details and Best Practices

Environment Configuration

Basic Environment Setup

# .ebextensions/01-environment.config
option_settings:
  aws:elasticbeanstalk:environment:
    EnvironmentType: LoadBalanced
    ServiceRole: aws-elasticbeanstalk-service-role
  aws:elasticbeanstalk:environment:process:default:
    HealthCheckPath: /health
    Port: 80
    Protocol: HTTP
  aws:autoscaling:launchconfiguration:
    InstanceType: t3.micro
    IamInstanceProfile: aws-elasticbeanstalk-ec2-role
    SecurityGroups: sg-12345678
  aws:autoscaling:asg:
    MinSize: 1
    MaxSize: 4
    Cooldown: 360
  aws:elasticbeanstalk:healthreporting:system:
    SystemType: enhanced
    HealthCheckSuccessThreshold: Ok

Advanced Configuration

# .ebextensions/02-advanced.config
option_settings:
  aws:elasticbeanstalk:application:environment:
    DATABASE_URL: RDS_ENDPOINT
    REDIS_URL: ELASTICACHE_ENDPOINT
    S3_BUCKET: my-app-bucket
  aws:elbv2:loadbalancer:
    SecurityGroups: sg-12345678,sg-87654321
    ManagedSecurityGroup: sg-managed
  aws:elbv2:listener:443:
    Protocol: HTTPS
    SSLCertificateArns: arn:aws:acm:region:account:certificate/cert-id
  aws:autoscaling:trigger:
    MeasureName: CPUUtilization
    Unit: Percent
    UpperThreshold: 80
    LowerThreshold: 20
    BreachDuration: 300
    Period: 300
    EvaluationPeriods: 2
    Statistic: Average
    UpperBreachScaleIncrement: 1
    LowerBreachScaleIncrement: -1

Database Configuration

# .ebextensions/03-database.config
option_settings:
  aws:rds:dbinstance:
    DBInstanceClass: db.t3.micro
    DBEngine: mysql
    DBEngineVersion: 8.0
    MultiAZDatabase: false
    DBAllocatedStorage: 20
    DBUser: admin
    DBPassword: mypassword
    DeletionPolicy: Delete

Application Code Structure

Java Application (Spring Boot)

myapp/
β”œβ”€β”€ src/
β”‚   └── main/
β”‚       β”œβ”€β”€ java/
β”‚       └── resources/
β”‚           └── application.properties
β”œβ”€β”€ .ebextensions/
β”‚   β”œβ”€β”€ 01-environment.config
β”‚   └── 02-https.config
β”œβ”€β”€ pom.xml
└── Procfile
# application.properties
server.port=5000
spring.datasource.url=${DATABASE_URL}
spring.profiles.active=${SPRING_PROFILES_ACTIVE:prod}
# Procfile
web: java -jar target/myapp-1.0.jar --server.port=$PORT

Node.js Application

myapp/
β”œβ”€β”€ app.js
β”œβ”€β”€ package.json
β”œβ”€β”€ .ebextensions/
β”‚   └── nodecommand.config
└── .npmrc
// app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.get('/health', (req, res) => {
  res.status(200).json({ status: 'healthy' });
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
# .ebextensions/nodecommand.config
option_settings:
  aws:elasticbeanstalk:container:nodejs:
    NodeCommand: "npm start"
    NodeVersion: 18.x
  aws:elasticbeanstalk:application:environment:
    NODE_ENV: production

Python Application (Django)

myapp/
β”œβ”€β”€ myproject/
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .ebextensions/
β”‚   └── python.config
└── application.py
# application.py
import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
# .ebextensions/python.config
option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: application.py
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: myproject.settings

Best Practices

Application Design

  1. Stateless Applications
  2. Design applications to be stateless
  3. Store session data in external stores (Redis, DynamoDB)
  4. Use external databases, not local file storage
  5. Implement proper logging to CloudWatch

  6. Health Checks

  7. Implement application health check endpoints
  8. Monitor application-specific metrics
  9. Use meaningful health check responses
  10. Configure appropriate timeouts

  11. Configuration Management

  12. Use environment variables for configuration
  13. Store secrets in Systems Manager or Secrets Manager
  14. Use .ebextensions for infrastructure configuration
  15. Implement configuration validation

Deployment Best Practices

  1. Version Management
  2. Use semantic versioning for applications
  3. Tag application versions appropriately
  4. Maintain deployment history
  5. Implement rollback procedures

  6. Deployment Strategies

  7. Use rolling deployments for zero downtime
  8. Implement blue/green for critical applications
  9. Test deployments in staging environments
  10. Automate deployment processes

  11. Security

  12. Use IAM roles instead of access keys
  13. Implement HTTPS with SSL certificates
  14. Configure security groups appropriately
  15. Regular security updates and patches

Performance Optimization

  1. Auto Scaling
  2. Configure appropriate scaling triggers
  3. Monitor application performance metrics
  4. Use predictive scaling when possible
  5. Implement proper cooldown periods

  6. Load Balancing

  7. Use Application Load Balancers for HTTP/HTTPS
  8. Configure health checks properly
  9. Implement sticky sessions if needed
  10. Optimize target group settings

  11. Caching

  12. Implement application-level caching
  13. Use CloudFront for static content
  14. Configure browser caching headers
  15. Use ElastiCache for session storage

Integration with Other AWS Services

Core Integrations

  1. Amazon RDS
  2. Managed database integration
  3. Automatic connection string injection
  4. Database security group configuration
  5. Backup and maintenance automation

  6. Amazon S3

  7. Application version storage
  8. Static asset hosting
  9. Log file storage
  10. Configuration file storage

  11. Amazon CloudWatch

  12. Application and infrastructure monitoring
  13. Custom metrics and alarms
  14. Log aggregation and analysis
  15. Performance dashboards

  16. AWS Certificate Manager

  17. SSL/TLS certificate management
  18. Automatic certificate renewal
  19. Load balancer integration
  20. Domain validation

  21. Amazon VPC

  22. Network isolation and security
  23. Custom network configurations
  24. Private subnet deployments
  25. VPC endpoint integration

Advanced Integrations

  1. AWS CodePipeline
  2. Continuous integration and deployment
  3. Source code integration
  4. Automated testing and deployment
  5. Multi-environment pipelines

  6. Amazon ElastiCache

  7. Session storage and caching
  8. Performance optimization
  9. Database query caching
  10. Application state management

  11. Amazon SES

  12. Email sending capabilities
  13. Transactional email integration
  14. Bounce and complaint handling
  15. Email analytics

  16. AWS Systems Manager

  17. Parameter store integration
  18. Configuration management
  19. Patch management
  20. Session manager access

  21. Amazon CloudFront

  22. Content delivery network
  23. Static asset acceleration
  24. Geographic distribution
  25. SSL termination

CI/CD Integration Patterns

CodePipeline Integration

# buildspec.yml
version: 0.2
phases:
  install:
    runtime-versions:
      java: corretto11
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
  build:
    commands:
      - echo Build started on `date`
      - mvn clean package
  post_build:
    commands:
      - echo Build completed on `date`
artifacts:
  files:
    - target/*.jar
    - .ebextensions/**/*
    - Procfile

GitHub Actions Integration

# .github/workflows/deploy.yml
name: Deploy to Elastic Beanstalk
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    - name: Setup Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '18'

    - name: Install dependencies
      run: npm install

    - name: Run tests
      run: npm test

    - name: Deploy to EB
      uses: einaregilsson/beanstalk-deploy@v21
      with:
        aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        application_name: myapp
        environment_name: myapp-prod
        version_label: ${{ github.sha }}
        region: us-west-2
        deployment_package: deployment.zip

Security Considerations

Access Control

  1. IAM Roles and Policies
  2. Service role for Elastic Beanstalk
  3. Instance profile for EC2 instances
  4. Application-specific permissions
  5. Cross-service access controls

  6. Application Security

  7. Secure coding practices
  8. Input validation and sanitization
  9. Authentication and authorization
  10. Session management

Network Security

  1. VPC Configuration
  2. Private subnet deployments
  3. Security group configurations
  4. Network ACLs
  5. VPC endpoints for AWS services

  6. Load Balancer Security

  7. HTTPS termination
  8. Security group rules
  9. Access logging
  10. DDoS protection

Data Protection

  1. Encryption
  2. HTTPS for data in transit
  3. Database encryption at rest
  4. S3 bucket encryption
  5. Log encryption

  6. Secrets Management

  7. Environment variables for non-sensitive config
  8. Systems Manager Parameter Store for secrets
  9. AWS Secrets Manager for database credentials
  10. Regular secret rotation

Compliance and Governance

  1. Monitoring and Auditing
  2. CloudTrail for API logging
  3. VPC Flow Logs for network traffic
  4. Application access logs
  5. Security event monitoring

  6. Patch Management

  7. Regular platform updates
  8. Application dependency updates
  9. Security patch automation
  10. Vulnerability scanning

Monitoring and Troubleshooting

CloudWatch Metrics

Environment Health Metrics

  • EnvironmentHealth: Overall environment health
  • ApplicationRequests2xx: Successful HTTP requests
  • ApplicationRequests4xx: Client error HTTP requests
  • ApplicationRequests5xx: Server error HTTP requests
  • ApplicationRequestsTotal: Total HTTP requests
  • ApplicationLatencyP50: 50th percentile latency
  • ApplicationLatencyP95: 95th percentile latency
  • ApplicationLatencyP99: 99th percentile latency

Instance Metrics

  • CPUUtilization: CPU usage percentage
  • NetworkIn: Network bytes received
  • NetworkOut: Network bytes transmitted
  • DiskReadOps: Disk read operations
  • DiskWriteOps: Disk write operations
  • StatusCheckFailed: Instance status check failures

Load Balancer Metrics

  • RequestCount: Number of requests
  • TargetResponseTime: Response time from targets
  • HealthyHostCount: Number of healthy targets
  • UnHealthyHostCount: Number of unhealthy targets
  • HTTPCode_Target_2XX_Count: Successful responses from targets

Health Monitoring

Application Health Dashboard

# Health check configuration
option_settings:
  aws:elasticbeanstalk:healthreporting:system:
    SystemType: enhanced
    HealthCheckSuccessThreshold: Ok
    EnhancedHealthAuthEnabled: true
  aws:elasticbeanstalk:environment:process:default:
    HealthCheckPath: /health
    HealthCheckInterval: 15
    HealthyThresholdCount: 3
    UnhealthyThresholdCount: 5

Custom Health Check Endpoint

// Node.js health check
app.get('/health', (req, res) => {
  const healthcheck = {
    uptime: process.uptime(),
    message: 'OK',
    timestamp: Date.now(),
    checks: {
      database: 'connected',
      cache: 'connected'
    }
  };

  try {
    res.status(200).send(healthcheck);
  } catch (error) {
    healthcheck.message = error;
    res.status(503).send(healthcheck);
  }
});

Common Troubleshooting Scenarios

  1. Deployment Failures
  2. Application startup errors
  3. Configuration issues
  4. Dependency problems
  5. Health check failures

  6. Performance Issues

  7. High response times
  8. Memory leaks
  9. Database connection issues
  10. Resource constraints

  11. Scaling Issues

  12. Auto scaling not triggering
  13. Instances failing health checks
  14. Load balancer configuration
  15. Target group registration

  16. Connectivity Issues

  17. Database connection failures
  18. External service timeouts
  19. Network configuration problems
  20. Security group misconfigurations

Debugging Tools and Techniques

Log Analysis

# Download log files
eb logs

# Stream logs in real-time
eb logs --all

# Download specific log files
aws s3 cp s3://elasticbeanstalk-region-account/resources/environments/logs/ . --recursive

Environment Debugging

# Check environment status
eb status

# Describe environment health
eb health

# Connect to instance via SSH
eb ssh

# Deploy with verbose output
eb deploy --verbose

CloudWatch Logs Integration

# .ebextensions/cloudwatch-logs.config
option_settings:
  aws:elasticbeanstalk:cloudwatch:logs:
    StreamLogs: true
    DeleteOnTerminate: false
    RetentionInDays: 7
  aws:elasticbeanstalk:cloudwatch:logs:health:
    HealthStreamingEnabled: true
    DeleteOnTerminate: false
    RetentionInDays: 7

Exam-Specific Tips and Common Scenarios

Solutions Architect Associate (SAA-C03)

  • PaaS vs IaaS: When to use Elastic Beanstalk vs EC2
  • Deployment Strategies: Rolling, blue/green, immutable deployments
  • Integration Patterns: RDS, S3, CloudFront integration
  • Cost Considerations: Free tier usage and optimization

Solutions Architect Professional (SAP-C02)

  • Enterprise Deployment: Large-scale application deployment
  • Multi-Environment: Development, staging, production pipelines
  • Advanced Networking: VPC, private subnets, hybrid connectivity
  • Compliance: Security and governance requirements

Developer Associate (DVA-C02)

  • Application Development: Platform-specific development practices
  • CI/CD Integration: Automated deployment pipelines
  • Debugging: Application troubleshooting techniques
  • Version Management: Application version control

SysOps Administrator (SOA-C02)

  • Environment Management: Day-to-day operations
  • Monitoring Setup: CloudWatch and health monitoring
  • Performance Tuning: Application and infrastructure optimization
  • Security Operations: Security best practices and monitoring

Common Exam Scenarios

  1. Scenario: Deploy a web application quickly without infrastructure management Solution: Use Elastic Beanstalk with appropriate platform

  2. Scenario: Need zero-downtime deployments Solution: Configure rolling or blue/green deployment strategies

  3. Scenario: Integrate with existing AWS services Solution: Use .ebextensions and environment variables

  4. Scenario: Multi-environment development workflow Solution: Multiple Elastic Beanstalk environments with CI/CD

  5. Scenario: Legacy application migration to cloud Solution: Containerize or adapt for Elastic Beanstalk platform

Hands-on Examples and CLI Commands

Environment Management

# Initialize Elastic Beanstalk application
eb init myapp --platform node.js --region us-west-2

# Create environment
eb create production --instance-type t3.small --cname myapp-prod

# Deploy application
eb deploy

# Check environment status
eb status

# View environment health
eb health

# Scale environment
eb scale 4

# Set environment variables
eb setenv DATABASE_URL=mysql://user:pass@host:port/db

# Terminate environment
eb terminate production

Configuration Management

# Save environment configuration
eb config save production --cfg prod-config

# Create environment from saved configuration
eb create staging --cfg prod-config

# Update configuration
eb config production

# List saved configurations
eb config list

# Delete saved configuration
eb config delete prod-config

Application Version Management

# List application versions
aws elasticbeanstalk describe-application-versions \
  --application-name myapp

# Create application version
aws elasticbeanstalk create-application-version \
  --application-name myapp \
  --version-label v1.2.0 \
  --source-bundle S3Bucket=my-bucket,S3Key=myapp-v1.2.0.zip

# Deploy specific version
aws elasticbeanstalk update-environment \
  --environment-name production \
  --version-label v1.2.0

# Delete application version
aws elasticbeanstalk delete-application-version \
  --application-name myapp \
  --version-label v1.1.0 \
  --delete-source-bundle

Monitoring and Logs

# View recent events
eb events

# Download logs
eb logs --all

# Stream logs
eb logs --all --stream

# Get CloudWatch metrics
aws cloudwatch get-metric-statistics \
  --namespace AWS/ElasticBeanstalk \
  --metric-name ApplicationRequests2xx \
  --dimensions Name=EnvironmentName,Value=production \
  --statistics Sum \
  --start-time 2023-01-01T00:00:00Z \
  --end-time 2023-01-01T23:59:59Z \
  --period 3600

Advanced Operations

# Create application
aws elasticbeanstalk create-application \
  --application-name myapp \
  --description "My web application"

# Create environment
aws elasticbeanstalk create-environment \
  --application-name myapp \
  --environment-name production \
  --solution-stack-name "64bit Amazon Linux 2 v5.4.0 running Node.js 18" \
  --option-settings file://options.json

# Update environment
aws elasticbeanstalk update-environment \
  --environment-name production \
  --option-settings file://update-options.json

# Swap environment URLs
aws elasticbeanstalk swap-environment-cnames \
  --source-environment-name production \
  --destination-environment-name staging

This comprehensive Elastic Beanstalk documentation provides detailed coverage for all AWS certification paths, including practical deployment examples and real-world application scenarios.