# Deploying Applications with AWS Elastic Beanstalk

> Chapter 6 of the Courseiva AWS-DEVELOPER-ASSOCIATE curriculum — https://courseiva.com/learn/aws-developer-associate/elastic-beanstalk-deployment

**Official objective:** Domain 2 — Create environments, manage deployments, and use configuration files.

## Introduction

AWS Elastic Beanstalk is a service that automatically handles the infrastructure needed to run your web application so you can focus on writing code. For the DVA-C02 exam, you need to understand how to manage the lifecycle of an application, including creating environments, deploying new versions, and using configuration files to customise settings. This chapter will give you a beginner-friendly map of the entire process.

## The Restaurant Kitchen Renovation Analogy

Because you have a popular restaurant that is constantly busy, you decide to renovate the kitchen to add more fryers and a new pizza oven. You cannot just close the restaurant for a month, so you plan a careful deployment. First, you install the new oven while the old one is still running, which means your kitchen is a mess of two ovens and temporary workarounds. This leads to a 'rolling update,' where one station at a time gets replaced, and your staff serves customers with a slightly slower pace until everything is done. 

 If you wanted to test the new pizza oven in a controlled way, you would set up a small, separate 'staging' kitchen in the back alley with a couple of tables. This is an 'immutable deployment,' where you bake a perfect new kitchen environment from scratch on the side and then switch the entire operation over in one quick move. If the new oven catches fire, you instantly flip back to the old kitchen configuration. 

 Finally, you could treat your entire recipe book and kitchen setup as a 'blueprint' stored in a binder. When you need to open a second location, you just hand the binder to the new crew, and they set up an identical kitchen in hours rather than months. This map of your kitchen's environment, including all the tweaks for different dishes (like the right temperature for the proofing drawer), is exactly what a configuration file, or 'environment manifest,' does for your application's deployment.

## Core explanation

AWS Elastic Beanstalk is a Platform as a Service (PaaS), which means it provides a ready-made platform for your application to run on without you having to manually set up servers, databases, or load balancers. Think of it as a 'one-click deploy' service for web applications. 

 You start by uploading your application code (e.g., a Python Flask app, a Java Spring Boot app, or a Node.js Express app) to Elastic Beanstalk, and the service automatically provisions all the necessary AWS resources. These resources include an Amazon EC2 instance (the virtual server that runs your code), a security group (which acts as a virtual firewall to control traffic), a load balancer (which distributes incoming internet traffic across multiple EC2 instances to handle high demand), and an Auto Scaling group (which adds or removes EC2 instances based on CPU usage or other metrics to maintain performance). 

 Elastic Beanstalk creates an 'environment'. An environment is a collection of AWS resources that are configured to run a specific version of your application. You can have two main types of environments: a 'web server environment' for applications that respond to HTTP requests (like a website or an API), and a 'worker environment' for applications that process background tasks from a queue (like sending emails or processing images). 

 The exam focuses heavily on 'deployment policies', which control how new versions of your application are rolled out to the environment. Here are the primary deployment policies you must know: 

 - All at once: This deploys the new version to all instances simultaneously. It is the fastest method, but it causes a brief period of downtime because all your application servers are being updated at the same time. 
 - Rolling: This deploys the new version in batches. You can specify a batch size (e.g., 50% of instances). This reduces downtime compared to 'All at once', but your instances will run a mix of old and new versions for a short time. 
 - Rolling with additional batch: This first launches a new batch of instances running the new version, then moves the old instances out of rotation. This avoids any reduction in capacity during the deployment, meaning your application can serve traffic at full capacity throughout the update. 
 - Immutable: This launches a completely new set of instances in a new Auto Scaling group. Once the new instances are healthy, Elastic Beanstalk swaps the old and new groups. If the new instances fail health checks, the old ones remain untouched. This is the safest but slowest method because it doubles the number of running instances. 
 - Blue/green deployment: This is a separate process where you create a second, independent environment (the green environment) running the new version. After verifying the green environment works, you swap the environment's CNAME record (the URL) so all traffic flows to the green environment. The old (blue) environment remains for rollback. 

 Configuration files, known as '.ebextensions', are YAML or JSON files stored in your source code within a '.ebextensions' folder. These files allow you to customise the environment by installing additional packages, creating files, defining environment variables, or running custom commands. For example, you can use an .ebextensions file to install the 'nginx' web server or to configure a cron job to run every hour. This is a key topic for the exam because it gives developers fine-grained control over the infrastructure without leaving the Elastic Beanstalk console. 

 Elastic Beanstalk also integrates with AWS CodeCommit (a source control service similar to GitHub) and AWS CodePipeline (a CI/CD service for automating builds and deployments). You can set up a pipeline so that every time you push code to a branch in CodeCommit, Elastic Beanstalk automatically deploys the new version. This is called 'continuous deployment', and the exam will test you on how to connect these services. 

 Finally, you need to understand 'environment configurations' versus 'saved configurations'. An environment configuration is a specific set of settings (e.g., instance type, key pair, VPC settings) for a running environment. A saved configuration (also called a 'template' or 'configuration template') is a snapshot of those settings that you can use to launch a new identical environment. This is useful for recreating a production environment for staging or disaster recovery. 

 A critical exam concept is the 'environment lifecycle'. You can create, update, and terminate environments. When you terminate an environment, all the resources (EC2 instances, load balancers, security groups) are deleted, but your application versions and saved configurations are retained. This helps you avoid unnecessary costs while keeping your deployment history.

## Real-world context

An IT professional, Sarah, works for an online retail company that sells handmade furniture. The company's main website is a Node.js application hosted on Elastic Beanstalk, and they need to roll out a new payment integration feature. Sarah is responsible for ensuring zero downtime during the holiday shopping season. 

 First, Sarah checks the current environment. It is configured as a 'web server environment' with a load balancer and six EC2 instances behind an Auto Scaling group. The instances are running the current version of the application, version 2.0. She has the new code on a branch in CodeCommit named 'release-3.0'. 

 Sarah decides to use a blue/green deployment because it offers the safest cutover with zero downtime. She does the following steps: 

 - She creates a new Elastic Beanstalk environment (the 'green' environment) that is an exact copy of the current production environment (the 'blue' environment) in terms of instance type, security group, and environment variables. She deploys version 3.0 of the application to this new environment. She tests the green environment using its direct URL to verify that payments process correctly. 
 - She then swaps the CNAME records between the two environments using the Elastic Beanstalk console. This instantly routes all user traffic from the old environment to the new one. 
 - After confirming that the green environment is running smoothly for 24 hours, Sarah terminates the blue environment to avoid paying for unused resources. She keeps a saved configuration of the blue environment in case a rollback is needed. 

 On another occasion, the company needs to update the time zone setting in the application's configuration file. Instead of a full blue/green switch, Sarah uses an '.ebextensions' file. She creates a file called '01-timezone.config' in the '.ebextensions' folder of her source code with the content that sets the TZ environment variable. She then performs an immutable deployment to push this small change. The deployment launches three new instances with the new time zone, verifies they are healthy, and then terminates the three old instances. This ensures that even a small configuration change does not cause a version mismatch across the fleet. 

 Finally, Sarah regularly checks the 'health' dashboard of the Elastic Beanstalk console. This dashboard shows the health status of each instance, the load balancer's response time, and the overall environment colour. If an instance turns 'red' (unhealthy), Elastic Beanstalk automatically replaces it based on the configuration of the Auto Scaling group. Sarah also monitors the 'environment events' tab to see logs of any deployment failures or scaling activities. For the DVA-C02 exam, you must be able to interpret these health states and know what actions to take when an environment is degraded.

## Exam focus

The DVA-C02 exam tests your understanding of Elastic Beanstalk's deployment policies, configuration files, and environment management in depth. You will not be asked to write a command line, but you must choose the correct deployment policy for a given scenario. 

 Very common question patterns include: 

 - Scenario with zero downtime requirement: The question describes a production environment where you cannot afford any service interruption. The correct answer is usually 'Blue/green deployment' or 'Immutable deployment'. The trap is that beginners choose 'Rolling with additional batch' because it sounds good, but that still involves a brief window where old instances are being terminated while new ones are being launched, which can cause a slight dip in performance. The safest is either immutable or blue/green. 
 - Scenario with minimal cost: If the question says you need to deploy quickly and are running a single instance environment, the correct answer is often 'All at once' because it is free (you are not launching extra instances). The trap is that you choose 'Rolling' or 'Immutable', which would require additional EC2 instances and incur costs. 
 - Configuration file syntax: The exam will give you a snippet of YAML in a .ebextensions file and ask what it does. You need to know that 'packages', 'sources', 'files', 'commands', and 'services' are the main keys. For example, a question might show: 

 - packages: 
   yum: 
     nginx: [] 

 This installs the nginx package using the yum package manager when the environment is provisioned. 
 - Environment variable priority: Questions will test the order of precedence for environment variables. The order is: 1) console or API (highest priority), 2) saved configuration, 3) .ebextensions configuration files, 4) the configuration file from the source bundle (like the 'env' or 'option_settings' in the application code). A common trap is to assume .ebextions override console settings, but console changes always win. 
 - RDS database integration: Elastic Beanstalk can provision an RDS database and pass its endpoint as an environment variable (e.g., RDS_HOSTNAME). However, the exam cautions that if you terminate the environment, the RDS database is also deleted unless you explicitly choose to retain it. A common trap involves the candidate thinking the database persists automatically. 
 - Swap environment CNAMEs: This is the mechanism for blue/green deployments. The exam will ask you to order the steps correctly: first, verify the new environment works, then swap the environment's CNAME records using the Elastic Beanstalk console or API, and finally, terminate the old environment if you want to save costs. The trap is that some candidates think you change the DNS record in Route 53, but Elastic Beanstalk manages a CNAME swap internally. 
 - Worker environment: You need to know that a worker environment pulls tasks from an Amazon SQS queue. The environment runs a daemon (a background process) that reads from the queue and sends HTTP POST requests to your application. The exam will test that this is how Elastic Beanstalk handles background processing without needing you to manage the SQS polling code. 

 Memorise the following definitions for the exam: 

 - 'Immutable deployment' means you launch a new Auto Scaling group and replace the old one in one shot. 
 - 'Health check URL' is a path you can configure to determine if your application is healthy. 
 - 'Platform' refers to the operating system and runtime stack (e.g., Python 3.8 on Amazon Linux 2). 
 - 'Environment tiers' refer to Web Server or Worker. 
 - 'MaximumPercent' setting in the deployment configuration controls batch sizes. 
 - 'At rest' encryption for storage uses EBS encryption; 'in transit' uses SSL/TLS certificates. 

 Finally, be aware of the following trap patterns: 

 - A question might say 'you want to deploy a new version without any impact on existing traffic' and offer 'All at once' as an option. The correct answer is not 'All at once'. 
 - A question about 'environment configuration' versus 'saved configuration': environment configuration is the live settings; saved configuration is the template. Traps involve calling a saved configuration an environment. 
 - A question about 'updating the platform version' (e.g., from Amazon Linux 1 to Amazon Linux 2): you cannot do this in-place. You must create a new environment with the new platform and migrate your application over. Beginners sometimes think you can just update the platform version on the existing environment, but that is not supported.

## Step by step

1. **Upload Your Application Code** — You begin by packaging your application code (e.g., a ZIP file containing your Node.js app with a package.json) and uploading it to Elastic Beanstalk via the console, the EB CLI, or an automated pipeline. This step is the foundation: without your code, there is nothing to deploy.
2. **Choose an Environment Tier** — You select either a 'Web server environment' for handling HTTP requests (like a website or API) or a 'Worker environment' for processing background tasks from an SQS queue. The tier determines what resources are provisioned; a web tier gets a load balancer, while a worker tier gets a daemon to poll the queue.
3. **Select a Platform** — You choose the operating system and runtime stack (e.g., Python 3.9 on Amazon Linux 2, or Tomcat 9 for Java). The platform dictates how your code runs. The exam tests you on the fact that you cannot change the platform version of an existing environment without creating a new environment.
4. **Configure Environment Settings** — You set environment variables, instance type, key pair, and security groups. You may also upload .ebextensions configuration files here. These settings define everything from your database connection string to the size of your EC2 instances. This step is critical because it customises the generic environment to your specific application needs.
5. **Deploy the Application** — Elastic Beanstalk creates the environment (provisioning EC2 instances, a load balancer, and an Auto Scaling group) and deploys your application. During this step, the health checks start, and the environment gradually turns green if everything works. If not, the deployment fails and the environment rolls back to the previous version.
6. **Monitor and Manage Health** — After deployment, you monitor the environment health via the console. You can view logs, check instance health, and see events (e.g., deployment completion or failure). This is where you decide if the new version is stable. The exam asks you to interpret health states and know when to roll back.

## Comparisons

### Immutable Deployment vs Rolling Deployment

**Immutable Deployment:**
- Launches a completely new Auto Scaling group with new instances.
- Swaps groups only when all new instances are healthy.
- Slower but safer, as old instances remain untouched until the swap.

**Rolling Deployment:**
- Updates existing instances in batches without adding extra capacity.
- During the deployment, old and new versions run simultaneously.
- Faster and incurs no additional EC2 cost, but risks mixed-version errors.

### Web Server Environment vs Worker Environment

**Web Server Environment:**
- Designed to handle HTTP/HTTPS requests from users.
- Includes a load balancer to distribute traffic.
- Auto Scaling based on CPU, network, or request count.

**Worker Environment:**
- Designed to process background tasks from an SQS queue.
- Does not have a load balancer; uses a daemon to poll the queue.
- Auto Scaling based on the length of the SQS queue.

### Environment Variables Set in Console vs Environment Variables Set in .ebextensions

**Environment Variables Set in Console:**
- Set via the Elastic Beanstalk console or API.
- Override any variable set in .ebextensions or saved configuration.
- Persist across deployments if not changed, but are not stored in source code.

**Environment Variables Set in .ebextensions:**
- Defined in YAML files in the .ebextensions folder.
- Stored in source code, making them version-controlled.
- Lower priority than console settings; used for default values.

### Environment (Live) vs Saved Configuration (Template)

**Environment (Live):**
- A running collection of AWS resources (EC2, LB, ASG).
- Incurs costs for the resources used.
- Can be terminated; all resources are deleted.

**Saved Configuration (Template):**
- A JSON/YAML snapshot of environment settings only.
- Does not incur any cost to store the template.
- Cannot be run directly; must be used to create a new environment.

## Common misconceptions

- **Misconception:** Elastic Beanstalk is just a container for EC2 instances, and you still have to manually set up the load balancer and Auto Scaling. **Reality:** Elastic Beanstalk automatically provisions and configures EC2 instances, load balancers, Auto Scaling groups, and security groups based on the environment tier you choose. (Many beginners come from a background of manually setting up infrastructure, so they assume Elastic Beanstalk is just a thin wrapper around EC2 and requires the same manual setup. In reality, it is a PaaS that abstracts away almost all infrastructure configuration.)
- **Misconception:** If you deploy a new version using a rolling update, no instance ever runs the old and new version at the same time. **Reality:** In a rolling deployment, instances are updated in batches, so during the deployment, some instances run the old version while others run the new version. This can cause compatibility issues if your application does not support mixed versions. (The term 'rolling' sounds like a smooth, uninterrupted process, but it actually involves a period of mixing. People assume it is like a rolling stone that changes everything at once, but in reality it is a phased transition.)
- **Misconception:** When you terminate an Elastic Beanstalk environment, all associated resources (including the RDS database, if you added one) are automatically deleted permanently. **Reality:** By default, terminating an environment deletes the RDS database, but you can choose to delete it or retain it by changing the 'Delete database' option in the termination settings. If you do not explicitly set it to retain, the database is deleted. (Because Elastic Beanstalk abstractly manages resources, beginners think it handles everything intelligently and would never delete a database without warning. However, the default behaviour is to delete everything to avoid orphaned resources and unexpected costs.)
- **Misconception:** Elastic Beanstalk can automatically run your code even if your application code is not packaged correctly or if you do not provide a valid entry point. **Reality:** Elastic Beanstalk only deploys code that follows the expected structure for the chosen platform. You must provide a valid application file (e.g., a .war file for Java, a package.json for Node.js) and a proper Procfile or entry point, or the deployment will fail. (Beginners think PaaS means 'just upload anything and it works', but the service still expects standardised packaging and a specific file structure. Without it, the health checks fail and the environment marked as degraded.)

## Key takeaways

- Elastic Beanstalk is a Platform as a Service (PaaS) that automatically provisions and manages the underlying AWS infrastructure for your web application.
- You can choose from five primary deployment policies: all at once, rolling, rolling with additional batch, immutable, and blue/green, each with different trade-offs in speed, cost, and risk.
- Configuration files stored in the '.ebextensions' folder allow you to customise your environment by installing packages, running commands, and setting environment variables.
- When using a blue/green deployment, you swap the CNAME records between two separate environments to achieve zero-downtime deployments.
- If you terminate an environment, the associated RDS database is deleted by default unless you explicitly choose to retain it during termination.
- Environment variables set in the console or API override variables defined in saved configurations and .ebextensions files.
- Worker environments pull tasks from an Amazon SQS queue and send them to your application via HTTP POST, enabling background processing without custom polling code.
- You cannot upgrade the platform version (e.g., from Amazon Linux 1 to Amazon Linux 2) in-place; you must create a new environment with the new platform and migrate your application.
- Immutable deployments launch a completely new Auto Scaling group and swap it with the old group, ensuring no mixed-version instances during the rollout.
- Saved configurations are templates of environment settings; they are not live environments and cannot be used to directly run your application.

## FAQ

**What is the difference between a Blue/Green deployment and an Immutable deployment in Elastic Beanstalk?**

Blue/Green uses two separate environments with their own CNAMEs; you swap the URLs externally. Immutable deployment launches a new Auto Scaling group within the same environment and swaps it out. Blue/Green is better for major version changes, while immutable is faster for small updates.

**Can I add a custom domain name to my Elastic Beanstalk environment?**

Yes, you can point a custom domain (e.g., www.myapp.com) to the environment's CNAME (e.g., myapp.elasticbeanstalk.com) by creating a CNAME record in Amazon Route 53 or another DNS provider. Elastic Beanstalk does not manage DNS for you.

**What happens if my .ebextensions configuration file has a syntax error?**

The deployment will fail because Elastic Beanstalk cannot parse the YAML or JSON file. The environment will remain in the previous healthy state, and you will see an error in the environment events. You must fix the file and redeploy.

**How do I troubleshoot a failed deployment in Elastic Beanstalk?**

Check the environment events tab in the console for error messages, look at the logs (e.g., web server logs, application logs) stored in Amazon S3, and review the health dashboard. If the issue is with the code, check the application log in the EC2 instance using the EB CLI command 'eb logs'.

**Is Elastic Beanstalk always free?**

No, Elastic Beanstalk itself is free, but you pay for the underlying resources it creates, such as EC2 instances, load balancers, and storage. A single t2.micro instance running for a month will incur costs. You are billed based on the resources used, not the service itself.

**What is the difference between an environment and a saved configuration?**

An environment is a live collection of running resources (EC2, load balancer, etc.) serving your application. A saved configuration is a JSON/YAML template of the environment settings that you can use to create a new environment. A saved configuration is not a running application.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/aws-developer-associate/elastic-beanstalk-deployment
