Aws Elastic Beanstalk
Aws Elastic Beanstalk
Aws Elastic Beanstalk
Developer Guide
AWS Elastic Beanstalk Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS Elastic Beanstalk Developer Guide
Table of Contents
What is AWS Elastic Beanstalk? ............................................................................................................ 1
Pricing ...................................................................................................................................... 1
Where to go next ....................................................................................................................... 1
Getting started .................................................................................................................................. 3
Setting up: Create an AWS account .............................................................................................. 3
Step 1: Create ........................................................................................................................... 3
Create an application and an environment ............................................................................ 3
AWS resources created for the example application ................................................................ 5
Step 2: Explore .......................................................................................................................... 5
Step 3: Deploy a new version ...................................................................................................... 7
Step 4: Configure ....................................................................................................................... 8
Make a configuration change ............................................................................................... 9
Verify the configuration change ........................................................................................... 9
Step 5: Clean up ...................................................................................................................... 10
Next steps ............................................................................................................................... 11
Concepts ......................................................................................................................................... 13
Application .............................................................................................................................. 13
Application version ................................................................................................................... 13
Environment ............................................................................................................................ 13
Environment tier ...................................................................................................................... 13
Environment configuration ........................................................................................................ 13
Saved configuration .................................................................................................................. 14
Platform .................................................................................................................................. 14
Web server environments .......................................................................................................... 14
Worker environments ................................................................................................................ 15
Design considerations ............................................................................................................... 16
Scalability ........................................................................................................................ 16
Security ........................................................................................................................... 17
Persistent storage ............................................................................................................. 17
Fault tolerance ................................................................................................................. 18
Content delivery .............................................................................................................. 18
Software updates and patching ......................................................................................... 18
Connectivity ..................................................................................................................... 19
Permissions ..................................................................................................................................... 20
Service role ............................................................................................................................. 20
Instance profile ........................................................................................................................ 21
User policy .............................................................................................................................. 23
Platforms ........................................................................................................................................ 24
Platforms glossary .................................................................................................................... 24
Shared responsibility model ....................................................................................................... 26
Platform support policy ............................................................................................................ 27
Retiring platform branch schedule ...................................................................................... 27
Retired platform branches ................................................................................................. 28
Supported platforms ................................................................................................................ 29
Supported platform versions ............................................................................................. 30
Linux platforms ........................................................................................................................ 30
Linux platform versions ..................................................................................................... 31
List of Elastic Beanstalk Linux platforms ............................................................................. 31
Extending Linux platforms ................................................................................................. 31
Working with Docker ................................................................................................................ 48
The Docker platform family ............................................................................................... 48
Docker platform branch .................................................................................................... 50
ECS managed platform branch .......................................................................................... 65
Preconfigured containers ................................................................................................... 84
iii
AWS Elastic Beanstalk Developer Guide
iv
AWS Elastic Beanstalk Developer Guide
v
AWS Elastic Beanstalk Developer Guide
vi
AWS Elastic Beanstalk Developer Guide
vii
AWS Elastic Beanstalk Developer Guide
viii
AWS Elastic Beanstalk Developer Guide
ix
AWS Elastic Beanstalk Developer Guide
x
AWS Elastic Beanstalk Developer Guide
xi
AWS Elastic Beanstalk Developer Guide
Pricing
With Elastic Beanstalk, you can quickly deploy and manage applications in the AWS Cloud without
having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces
management complexity without restricting choice or control. You simply upload your application, and
Elastic Beanstalk automatically handles the details of capacity provisioning, load balancing, scaling, and
application health monitoring.
Elastic Beanstalk supports applications developed in Go, Java, .NET, Node.js, PHP, Python, and Ruby.
When you deploy your application, Elastic Beanstalk builds the selected supported platform version and
provisions one or more AWS resources, such as Amazon EC2 instances, to run your application.
You can interact with Elastic Beanstalk by using the Elastic Beanstalk console, the AWS Command Line
Interface (AWS CLI), or eb, a high-level CLI designed specifically for Elastic Beanstalk.
To learn more about how to deploy a sample web application using Elastic Beanstalk, see Getting Started
with AWS: Deploying a Web App.
You can also perform most deployment tasks, such as changing the size of your fleet of Amazon EC2
instances or monitoring your application, directly from the Elastic Beanstalk web interface (console).
To use Elastic Beanstalk, you create an application, upload an application version in the form of an
application source bundle (for example, a Java .war file) to Elastic Beanstalk, and then provide some
information about the application. Elastic Beanstalk automatically launches an environment and creates
and configures the AWS resources needed to run your code. After your environment is launched, you can
then manage your environment and deploy new application versions. The following diagram illustrates
the workflow of Elastic Beanstalk.
After you create and deploy your application, information about the application—including metrics,
events, and environment status—is available through the Elastic Beanstalk console, APIs, or Command
Line Interfaces, including the unified AWS CLI.
Pricing
There is no additional charge for Elastic Beanstalk. You pay only for the underlying AWS resources that
your application consumes. For details about pricing, see the Elastic Beanstalk service detail page.
Where to go next
This guide contains conceptual information about the Elastic Beanstalk web service, as well as
information about how to use the service to deploy web applications. Separate sections describe how to
1
AWS Elastic Beanstalk Developer Guide
Where to go next
use the Elastic Beanstalk console, command line interface (CLI) tools, and API to deploy and manage your
Elastic Beanstalk environments. This guide also documents how Elastic Beanstalk is integrated with other
services provided by Amazon Web Services.
We recommend that you first read Getting started using Elastic Beanstalk (p. 3) to learn how to start
using Elastic Beanstalk. Getting Started steps you through creating, viewing, and updating your Elastic
Beanstalk application, as well as editing and terminating your Elastic Beanstalk environment. Getting
Started also describes different ways you can access Elastic Beanstalk.
To learn more about an Elastic Beanstalk application and its components, see the following pages.
2
AWS Elastic Beanstalk Developer Guide
Setting up: Create an AWS account
There is no cost for using Elastic Beanstalk, but the AWS resources that it creates for this tutorial are live
(and don't run in a sandbox). You incur the standard usage fees for these resources until you terminate
them at the end of this tutorial. The total charges are typically less than a dollar. For information about
how to minimize charges, see AWS free tier.
Topics
• Setting up: Create an AWS account (p. 3)
• Step 1: Create an example application (p. 3)
• Step 2: Explore your environment (p. 5)
• Step 3: Deploy a new version of your application (p. 7)
• Step 4: Configure your environment (p. 8)
• Step 5: Clean up (p. 10)
• Next steps (p. 11)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. Follow the instructions shown.
3
AWS Elastic Beanstalk Developer Guide
Create an application and an environment
To run the example application on AWS resources, Elastic Beanstalk takes the following actions. They
take about five minutes to complete.
For details about these AWS resources, see the section called “AWS resources created for the example
application” (p. 5).
3. Creates a new application version named Sample Application. This is the default Elastic Beanstalk
example application file.
4. Deploys the code for the example application to the GettingStartedApp-env environment.
During the environment creation process, the console tracks progress and displays events.
When all of the resources are launched and the EC2 instances running the application pass health checks,
the environment's health changes to Ok. You can now use your web application's website.
4
AWS Elastic Beanstalk Developer Guide
AWS resources created for the example application
• EC2 instance – An Amazon EC2 virtual machine configured to run web apps on the platform you
choose.
Each platform runs a different set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination thereof. Most platforms use either
Apache or nginx as a reverse proxy that processes web traffic in front of your web app, forwards
requests to it, serves static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow incoming traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic is not allowed on other ports.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and are triggered if the load is too high or too low. When an alarm is triggered, your Auto
Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
The environment overview pane shows top level information about your environment. This includes its
name, its URL, its current health status, the name of the currently deployed application version, and the
platform version that the application is running on. Below the overview pane you can see the five most
recent environment events.
To learn more about environment tiers, platforms, application versions, and other Elastic Beanstalk
concepts, see Concepts (p. 13).
5
AWS Elastic Beanstalk Developer Guide
Step 2: Explore
While Elastic Beanstalk creates your AWS resources and launches your application, the environment is in
a Pending state. Status messages about launch events are continuously added to the overview.
The environment's URL is located at the top of the overview, below the environment name. This is the
URL of the web application that the environment is running. Choose this URL to get to the example
application's Congratulations page.
The navigation page on the left side of the console links to other pages that contain more detailed
information about your environment and provide access to additional features:
• Configuration – Shows the resources provisioned for this environment, such as the Amazon Elastic
Compute Cloud (Amazon EC2) instances that host your application. You can configure some of the
provisioned resources on this page.
• Health – Shows the status of and detailed health information about the Amazon EC2 instances
running your application.
6
AWS Elastic Beanstalk Developer Guide
Step 3: Deploy a new version
• Monitoring – Shows statistics for the environment, such as average latency and CPU utilization. You
can use this page to create alarms for the metrics that you are monitoring.
• Events – Shows information or error messages from the Elastic Beanstalk service and from other
services whose resources this environment uses.
• Tags – Shows environment tags and allows you to manage them. Tags are key-value pairs that are
applied to your environment.
The application version that you started this tutorial with is called Sample Application.
1. Download the sample application that matches your environment's platform. Use one of the
following applications.
• Docker – docker.zip
• Multicontainer Docker – docker-multicontainer-v2.zip
• Preconfigured Docker (Glassfish) – docker-glassfish-v1.zip
• Go – go.zip
• Corretto – corretto.zip
• Tomcat – tomcat.zip
• .NET Core on Linux – dotnet-core-linux.zip
• .NET – dotnet-asp-v1.zip
• Node.js – nodejs.zip
• PHP – php.zip
• Python – python.zip
• Ruby – ruby.zip
2. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
3. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
4. On the environment overview page, choose Upload and deploy.
5. Choose Choose file, and then upload the sample application source bundle that you downloaded.
7
AWS Elastic Beanstalk Developer Guide
Step 4: Configure
The console automatically fills in the Version label with a new unique label. If you type in your own
version label, ensure that it's unique.
6. Choose Deploy.
While Elastic Beanstalk deploys your file to your Amazon EC2 instances, you can view the deployment
status on the environment's overview. While the application version is updated, the Environment Health
status is gray. When the deployment is complete, Elastic Beanstalk performs an application health check.
When the application responds to the health check, it's considered healthy and the status returns to
green. The environment overview shows the new Running Version—the name you provided as the
Version label.
Elastic Beanstalk also uploads your new application version and adds it to the table of application
versions. To view the table, choose Application versions under getting-started-app on the navigation
pane.
8
AWS Elastic Beanstalk Developer Guide
Make a configuration change
Some configuration changes are simple and happen quickly. Some changes require deleting and
recreating AWS resources, which can take several minutes. When you change configuration settings,
Elastic Beanstalk warns you about potential application downtime.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, change Environment type to Load balanced.
6. In the Instances row, change Max to 4, and then change Min to 2.
7. Choose Apply.
8. A warning tells you that this update replaces all of your current instances. Choose Confirm.
9. In the navigation pane, choose Events.
The environment update can take a few minutes. To find out that it's complete, look for the event
Successfully deployed new configuration to environment in the event list. This confirms that the
Auto Scaling minimum instance count has been set to 2. Elastic Beanstalk automatically launches
the second instance.
You can see that two Amazon EC2 instances are listed following the Overall line. Your environment
capacity has increased to two instances.
9
AWS Elastic Beanstalk Developer Guide
Step 5: Clean up
Step 5: Clean up
Congratulations! You have successfully deployed a sample application to the AWS Cloud, uploaded a new
version, and modified its configuration to add a second Auto Scaling instance. To ensure that you're not
charged for any services you aren't using, delete all application versions and terminate the environment.
This also deletes the AWS resources that the environment created for you.
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Applications, and then choose getting-started-app.
c. In the navigation pane, find your application's name and choose Application versions.
d. On the Application versions page, select all application versions that you want to delete.
e. Choose Actions, and then choose Delete.
f. Turn on Delete versions from Amazon S3.
g. Choose Delete, and then choose Done.
2. Terminate the environment.
10
AWS Elastic Beanstalk Developer Guide
Next steps
c. Confirm that you want to terminate GettingStartedApp-env by typing the environment name,
and then choose Terminate.
3. Delete the getting-started-app application.
Next steps
Now that you know how to create an Elastic Beanstalk application and environment, we recommend that
you read Concepts (p. 13). This topic provides information about the Elastic Beanstalk components
and architecture, and describes important design considerations for your Elastic Beanstalk application.
In addition to the Elastic Beanstalk console, you can use the following tools to create and manage Elastic
Beanstalk environments.
EB CLI
The EB CLI is a command line tool for creating and managing environments. See Using the Elastic
Beanstalk command line interface (EB CLI) (p. 956) for details.
The AWS SDK for Java requires the J2SE Development Kit 5.0 or later. You can download the latest Java
software from http://developers.sun.com/downloads/. The SDK also requires Apache Commons (Codec,
HTTPClient, and Logging) and Saxon-HE third-party packages, which are included in the third-party
directory of the SDK.
To ensure that you have all the WTP dependencies, we recommend that you start with the Java EE
distribution of Eclipse. You can download it from http://eclipse.org/downloads/.
For more information about using the Elastic Beanstalk plug-in for Eclipse, see AWS Toolkit for Eclipse.
To get started creating your Elastic Beanstalk application using Eclipse, see Creating and deploying Java
applications on Elastic Beanstalk (p. 108).
11
AWS Elastic Beanstalk Developer Guide
Next steps
For more information, see AWS SDK for .NET. For supported .NET Framework and Visual Studio versions,
see the AWS SDK for .NET Developer Guide.
For prerequisite and installation information, see the AWS Toolkit for Visual Studio. To get started
creating your Elastic Beanstalk application using Visual Studio, see Creating and deploying .NET
applications on Elastic Beanstalk (p. 182).
For more information, see the AWS SDK for JavaScript in Node.js.
The AWS SDK for PHP requires PHP 5.2 or later. For download details, see http://php.net/.
The all-in-one library provides Python developer-friendly APIs that hide many of the lower-level
tasks associated with programming for the AWS Cloud, including authentication, request retries, and
error handling. The SDK provides practical examples in Python for how to use the libraries to build
applications.
For information about Boto, example code, documentation, tools, and additional resources, see the
Python Developer Center.
The all-in-one library provides Ruby developer-friendly APIs that hide many of the lower-level tasks
associated with programming for the AWS Cloud, including authentication, request retries, and error
handling. The SDK provides practical examples in Ruby for how to use the libraries to build applications.
For information about the SDK, example code, documentation, tools, and additional resources, see the
Ruby Developer Center.
12
AWS Elastic Beanstalk Developer Guide
Application
Application
An Elastic Beanstalk application is a logical collection of Elastic Beanstalk components, including
environments, versions, and environment configurations. In Elastic Beanstalk an application is
conceptually similar to a folder.
Application version
In Elastic Beanstalk, an application version refers to a specific, labeled iteration of deployable code for
a web application. An application version points to an Amazon Simple Storage Service (Amazon S3)
object that contains the deployable code, such as a Java WAR file. An application version is part of an
application. Applications can have many versions and each application version is unique. In a running
environment, you can deploy any application version you already uploaded to the application, or you
can upload and immediately deploy a new application version. You might upload multiple application
versions to test differences between one version of your web application and another.
Environment
An environment is a collection of AWS resources running an application version. Each environment runs
only one application version at a time, however, you can run the same application version or different
application versions in many environments simultaneously. When you create an environment, Elastic
Beanstalk provisions the resources needed to run the application version you specified.
Environment tier
When you launch an Elastic Beanstalk environment, you first choose an environment tier. The
environment tier designates the type of application that the environment runs, and determines what
resources Elastic Beanstalk provisions to support it. An application that serves HTTP requests runs in a
web server environment tier (p. 14). A backend environment that pulls tasks from an Amazon Simple
Queue Service (Amazon SQS) queue runs in a worker environment tier (p. 15).
Environment configuration
An environment configuration identifies a collection of parameters and settings that define how an
environment and its associated resources behave. When you update an environment’s configuration
settings, Elastic Beanstalk automatically applies the changes to existing resources or deletes and deploys
new resources (depending on the type of change).
13
AWS Elastic Beanstalk Developer Guide
Saved configuration
Saved configuration
A saved configuration is a template that you can use as a starting point for creating unique environment
configurations. You can create and modify saved configurations, and apply them to environments,
using the Elastic Beanstalk console, EB CLI, AWS CLI, or API. The API and the AWS CLI refer to saved
configurations as configuration templates.
Platform
A platform is a combination of an operating system, programming language runtime, web server,
application server, and Elastic Beanstalk components. You design and target your web application to a
platform. Elastic Beanstalk provides a variety of platforms on which you can build your applications.
The environment is the heart of the application. In the diagram, the environment is shown within the
top-level solid line. When you create an environment, Elastic Beanstalk provisions the resources required
to run your application. AWS resources created for an environment include one elastic load balancer (ELB
in the diagram), an Auto Scaling group, and one or more Amazon Elastic Compute Cloud (Amazon EC2)
instances.
Every environment has a CNAME (URL) that points to a load balancer. The environment has a URL,
such as myapp.us-west-2.elasticbeanstalk.com. This URL is aliased in Amazon Route 53 to an
Elastic Load Balancing URL—something like abcdef-123456.us-west-2.elb.amazonaws.com—by
using a CNAME record. Amazon Route 53 is a highly available and scalable Domain Name System (DNS)
web service. It provides secure and reliable routing to your infrastructure. Your domain name that you
registered with your DNS provider will forward requests to the CNAME.
14
AWS Elastic Beanstalk Developer Guide
Worker environments
The load balancer sits in front of the Amazon EC2 instances, which are part of an Auto Scaling group.
Amazon EC2 Auto Scaling automatically starts additional Amazon EC2 instances to accommodate
increasing load on your application. If the load on your application decreases, Amazon EC2 Auto Scaling
stops instances, but always leaves at least one instance running.
The software stack running on the Amazon EC2 instances is dependent on the container type. A container
type defines the infrastructure topology and software stack to be used for that environment. For
example, an Elastic Beanstalk environment with an Apache Tomcat container uses the Amazon Linux
operating system, Apache web server, and Apache Tomcat software. For a list of supported container
types, see Elastic Beanstalk supported platforms (p. 29). Each Amazon EC2 instance that runs your
application uses one of these container types. In addition, a software component called the host
manager (HM) runs on each Amazon EC2 instance. The host manager is responsible for the following:
The host manager reports metrics, errors and events, and server instance status, which are available via
the Elastic Beanstalk console, APIs, and CLIs.
The Amazon EC2 instances shown in the diagram are part of one security group. A security group
defines the firewall rules for your instances. By default, Elastic Beanstalk defines a security group, which
allows everyone to connect using port 80 (HTTP). You can define more than one security group. For
example, you can define a security group for your database server. For more information about Amazon
EC2 security groups and how to configure them for your Elastic Beanstalk application, see Security
groups (p. 503).
Worker environments
AWS resources created for a worker environment tier include an Auto Scaling group, one or more
Amazon EC2 instances, and an IAM role. For the worker environment tier, Elastic Beanstalk also creates
and provisions an Amazon SQS queue if you don’t already have one. When you launch a worker
environment, Elastic Beanstalk installs the necessary support files for your programming language of
choice and a daemon on each EC2 instance in the Auto Scaling group. The daemon reads messages
from an Amazon SQS queue. The daemon sends data from each message that it reads to the web
application running in the worker environment for processing. If you have multiple instances in your
worker environment, each instance has its own daemon, but they all read from the same Amazon SQS
queue.
The following diagram shows the different components and their interactions across environments and
AWS services.
15
AWS Elastic Beanstalk Developer Guide
Design considerations
Amazon CloudWatch is used for alarms and health monitoring. For more information, go to Basic health
reporting (p. 773).
For details about how the worker environment tier works, see Elastic Beanstalk worker
environments (p. 482).
Design considerations
Because applications deployed using AWS Elastic Beanstalk run on AWS Cloud resources, you should
keep several configuration factors in mind to optimize your applications: scalability, security, persistent
storage, fault tolerance, content delivery, software updates and patching, and connectivity. Each of these
are covered separately in this topic. For a comprehensive list of technical AWS whitepapers, covering
topics such as architecture, as well as security and economics, see AWS Cloud Computing Whitepapers.
Scalability
When operating in a physical hardware environment, in contrast to a cloud environment, you can
approach scalability in one of either two ways. Either you can scale up through vertical scaling or you
can scale out through horizontal scaling. The scale-up approach requires that you invest in powerful
16
AWS Elastic Beanstalk Developer Guide
Security
hardware, which can support the increasing demands of your business. The scale-out approach requires
that you follow a distributed model of investment. As such, your hardware and application acquisitions
can be more targeted, your data sets are federated, and your design is service oriented. The scale-up
approach can be expensive, and there's also the risk that your demand could outgrow your capacity. In
this regard, the scale-out approach is usually more effective. However, when using it, you must be able
to predict demand at regular intervals and deploy infrastructure in chunks to meet that demand. As a
result, this approach can often lead to unused capacity and might require some careful monitoring.
By migrating to the cloud, you can make your infrastructure align well with demand by leveraging
the elasticity of cloud. Elasticity helps to streamline resource acquisition and release. With it, your
infrastructure can rapidly scale in and scale out as demand fluctuates. To use it, configure your Auto
Scaling settings to scale up or down based on the metrics for the resources in your environment. For
example, you can set metrics such as server utilization or network I/O. You can use Auto Scaling for
compute capacity to be added automatically whenever usage rises and for it to be removed whenever
usage drops. You can publish system metrics (for example, CPU, memory, disk I/O, and network I/O) to
Amazon CloudWatch. Then, you can use CloudWatch to configure alarms to trigger Auto Scaling actions
or send notifications based on these metrics. For instructions on how to configure Auto Scaling, see Auto
Scaling group for your Elastic Beanstalk environment (p. 511).
We also recommend that you design all your Elastic Beanstalk applications as stateless as possible, using
loosely coupled, fault-tolerant components that can be scaled out as needed. For more information
about designing scalable application architectures for AWS, see AWS Well-Architected Framework.
Security
Security on AWS is a shared responsibility. Amazon Web Services protects the physical resources in your
environment and ensures that the Cloud is a safe place for you to run applications. You're responsible
for the security of data coming in and out of your Elastic Beanstalk environment and the security of your
application.
Configure SSL to protect information that flows between your application and clients. To configure SSL,
you need a free certificate from AWS Certificate Manager (ACM). If you already have a certificate from an
external certificate authority (CA), you can use ACM to import that your certificate. Otherwise, you can
import it using the AWS CLI.
If ACM isn't available in your AWS Region, you can purchase a certificate from an external CA, such as
VeriSign or Entrust. Then, use the AWS Command Line Interface (AWS CLI) to upload a third-party or
self-signed certificate and private key to AWS Identity and Access Management (IAM). The public key
of the certificate authenticates your server to the browser. It also serves as the basis for creating the
shared session key that encrypts the data in both directions. For instructions on how to create, upload,
and assign an SSL certificate to your environment, see Configuring HTTPS for your Elastic Beanstalk
environment (p. 734).
When you configure an SSL certificate for your environment, data is encrypted between the client and
the Elastic Load Balancing load balancer for your environment. By default, encryption is terminated at
the load balancer, and traffic between the load balancer and Amazon EC2 instances is unencrypted.
Persistent storage
Elastic Beanstalk applications run on Amazon EC2 instances that have no persistent local storage. When
the Amazon EC2 instances terminate, the local file system isn't saved. New Amazon EC2 instances
start with a default file system. We recommend that you configure your application to store data in a
persistent data source. AWS offers a number of persistent storage services that you can use for your
application. The following table lists them.
17
AWS Elastic Beanstalk Developer Guide
Fault tolerance
Amazon S3 Amazon Simple Storage Service Using Elastic Beanstalk with Amazon
Documentation S3 (p. 935)
Amazon Elastic File System Amazon Elastic File System Using Elastic Beanstalk with Amazon
Documentation Elastic File System (p. 853)
Amazon Relational Amazon Relational Database Using Elastic Beanstalk with Amazon
Database Service (RDS) Service Documentation RDS (p. 923)
Note
Elastic Beanstalk creates a webapp user for you to set up as the owner of application directories
on EC2 instances. For Amazon Linux 2 platform versions that are released on or after Feburary
3, 2022, Elastic Beanstalk assigns the webapp user a uid (user id) and gid (group id) value of 900
for new environments. It does the same for existing environments following a platform version
update. This approach keeps consistent access permission for the webapp user to permanent file
system storage.
In the unlikely situation that another user or process is already using 900, the operating system
defaults the webapp user uid and gid to another value. Run the Linux command id webapp on
your EC2 instances to verify the uid and gid values that are assigned to the webapp user.
Fault tolerance
As a rule of thumb, you should be a pessimist when designing architecture for the cloud. Leverage the
elasticity that it offers. Always design, implement, and deploy for automated recovery from failure.
Use multiple Availability Zones for your Amazon EC2 instances and for Amazon RDS. Availability Zones
are conceptually like logical data centers. Use Amazon CloudWatch to get more visibility into the
health of your Elastic Beanstalk application and take appropriate actions in case of hardware failure
or performance degradation. Configure your Auto Scaling settings to maintain your fleet of Amazon
EC2 instances at a fixed size so that unhealthy Amazon EC2 instances are replaced by new ones. If
you're using Amazon RDS, then set the retention period for backups, so that Amazon RDS can perform
automated backups.
Content delivery
When users connect to your website, their requests may be routed through a number of individual
networks. As a result, users might experience poor performance due to high latency. Amazon CloudFront
can help ameliorate latency issues by distributing your web content, such as images and video, across a
network of edge locations around the world. Users' requests are routed to the nearest edge location, so
content is delivered with the best possible performance. CloudFront works seamlessly with Amazon S3,
which durably stores the original, definitive versions of your files. For more information about Amazon
CloudFront, see the Amazon CloudFront Developer Guide.
18
AWS Elastic Beanstalk Developer Guide
Connectivity
platform updates (p. 464) your environment automatically upgrades to the latest version of a platform
during a scheduled maintenance window while your application remains in service. For environments
created on November 25, 2019 or later using the Elastic Beanstalk console, managed updates are
enabled by default whenever possible. You can also manually initiate updates using the Elastic Beanstalk
console or EB CLI.
Connectivity
Elastic Beanstalk needs to be able to connect to the instances in your environment to complete
deployments. When you deploy an Elastic Beanstalk application inside an Amazon VPC, the configuration
required to enable connectivity depends on the type of Amazon VPC environment you create:
• For single-instance environments, no additional configuration is required. This is because, with these
environments, Elastic Beanstalk assigns each Amazon EC2 instance a public Elastic IP address that
enables the instance to communicate directly with the internet.
• For load-balanced, scalable environments in an Amazon VPC with both public and private subnets, you
must do the following:
• Create a load balancer in the public subnet to route inbound traffic from the internet to the Amazon
EC2 instances.
• Create a network address translation (NAT) device to route outbound traffic from the Amazon EC2
instances in private subnets to the internet.
• Create inbound and outbound routing rules for the Amazon EC2 instances inside the private subnet.
• If you're using a NAT instance, configure the security groups for the NAT instance and Amazon EC2
instances to enable internet communication.
• For a load-balanced, scalable environment in an Amazon VPC that has one public subnet, no additional
configuration is required. This is because, with this environment, your Amazon EC2 instances are
configured with a public IP address that enables the instances to communicate with the internet.
For more information about using Elastic Beanstalk with Amazon VPC, see Using Elastic Beanstalk with
Amazon VPC (p. 938).
19
AWS Elastic Beanstalk Developer Guide
Service role
The best way to get a properly configured service role and instance profile is to create an environment
running a sample application (p. 407) in the Elastic Beanstalk console or by using the Elastic Beanstalk
Command Line Interface (EB CLI). When you create an environment, the clients create the required roles
and assign them managed policies (p. 879) that include all of the necessary permissions.
In addition to the two roles that you assign to your environment, you can also create user
policies (p. 23) and apply them to IAM users and groups in your account to allow users to create and
manage Elastic Beanstalk applications and environments. Elastic Beanstalk provides managed policies for
full access and read-only access.
You can create your own instance profiles and user policies for advanced scenarios. If your instances need
to access services that are not included in the default policies, you can add additional policies to the
default or create a new one. You can also create more restrictive user policies if the managed policy is
too permissive. See the AWS Identity and Access Management User Guide for in-depth coverage of AWS
permissions.
Topics
• Elastic Beanstalk service role (p. 20)
• Elastic Beanstalk instance profile (p. 21)
• Elastic Beanstalk user policy (p. 23)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticloadbalancing:DescribeInstanceHealth",
20
AWS Elastic Beanstalk Developer Guide
Instance profile
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeTargetHealth",
"ec2:DescribeInstances",
"ec2:DescribeInstanceStatus",
"ec2:GetConsoleOutput",
"ec2:AssociateAddress",
"ec2:DescribeAddresses",
"ec2:DescribeSecurityGroups",
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"autoscaling:DescribeScalingActivities",
"autoscaling:DescribeNotificationConfigurations",
"sns:Publish"
],
"Resource": [
"*"
]
}
]
}
This policy also includes Amazon SQS actions to allow Elastic Beanstalk to monitor queue activity for
worker environments.
When you create an environment using the Elastic Beanstalk console, Elastic Beanstalk prompts you
to create a service role named aws-elasticbeanstalk-service-role with the default set of
permissions and a trust policy that allows Elastic Beanstalk to assume the service role. If you enable
managed platform updates (p. 464), Elastic Beanstalk attaches another policy with permissions that
enable that feature.
Similarly, when you create an environment using the the section called “eb create” (p. 1003) command
of the Elastic Beanstalk Command Line Interface (EB CLI) and don't specify a service role through the
--service-role option, Elastic Beanstalk creates the default service role aws-elasticbeanstalk-
service-role. If the default service role already exists, Elastic Beanstalk uses it for the new
environment.
When you create an environment by using the CreateEnvironment action of the Elastic Beanstalk
API, and don't specify a service role, Elastic Beanstalk creates a monitoring service-linked role. This is a
unique type of service role that is predefined by Elastic Beanstalk to include all the permissions that the
service requires to call other AWS services on your behalf. The service-linked role is associated with your
account. Elastic Beanstalk creates it once, then reuses it when creating additional environments. You can
also use IAM to create your account's monitoring service-linked role in advance. When your account has
a monitoring service-linked role, you can use it to create an environment by using the Elastic Beanstalk
API, the Elastic Beanstalk console, or the EB CLI. For details about using service-linked roles with Elastic
Beanstalk environments, see Using service-linked roles for Elastic Beanstalk (p. 869).
For more information about service roles, see Managing Elastic Beanstalk service roles (p. 860).
• Retrieve application versions (p. 13) from Amazon Simple Storage Service (Amazon S3)
• Write logs to Amazon S3
21
AWS Elastic Beanstalk Developer Guide
Instance profile
• In AWS X-Ray integrated environments (p. 595), upload debugging data to X-Ray
• In multicontainer Docker environments, coordinate container deployments with Amazon Elastic
Container Service
• In worker environments, read from an Amazon Simple Queue Service (Amazon SQS) queue
• In worker environments, perform leader election with Amazon DynamoDB
• In worker environments, publish instance health metrics to Amazon CloudWatch
The AWSElasticBeanstalkWebTier managed policy contains statements that allow instances in your
environment to upload logs to Amazon S3 and send debugging information to X-Ray:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BucketAccess",
"Action": [
"s3:Get*",
"s3:List*",
"s3:PutObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::elasticbeanstalk-*",
"arn:aws:s3:::elasticbeanstalk-*/*"
]
},
{
"Sid": "XRayAccess",
"Action":[
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets",
"xray:GetSamplingStatisticSummaries"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "CloudWatchLogsAccess",
"Action": [
"logs:PutLogEvents",
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:DescribeLogGroups"
],
"Effect": "Allow",
"Resource": [
"arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
]
},
{
"Sid": "ElasticBeanstalkHealthAccess",
"Action": [
"elasticbeanstalk:PutInstanceStatistics"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:*:*:application/*",
"arn:aws:elasticbeanstalk:*:*:environment/*"
]
}
22
AWS Elastic Beanstalk Developer Guide
User policy
]
}
If your web application requires access to any other AWS services, add statements or managed policies to
the instance profile that allow access to those services.
For more information about instance profiles, see Managing Elastic Beanstalk instance profiles (p. 855).
Elastic Beanstalk requires permissions not only for its own API actions, but for several other AWS
services as well. Elastic Beanstalk uses user permissions to launch all of the resources in an environment,
including EC2 instances, an Elastic Load Balancing load balancer, and an Auto Scaling group. Elastic
Beanstalk also uses user permissions to save logs and templates to Amazon Simple Storage Service
(Amazon S3), send notifications to Amazon SNS, assign instance profiles, and publish metrics to
CloudWatch. Elastic Beanstalk requires AWS CloudFormation permissions to orchestrate resource
deployments and updates. It also requires Amazon RDS permissions to create databases when needed,
and Amazon SQS permissions to create queues for worker environments.
For more information about user policies, see Managing Elastic Beanstalk user policies (p. 879).
23
AWS Elastic Beanstalk Developer Guide
Platforms glossary
Elastic Beanstalk provides platforms for different programming languages, application servers, and
Docker containers. Some platforms have multiple concurrently-supported versions.
Topics
• Elastic Beanstalk platforms glossary (p. 24)
• Shared responsibility model for Elastic Beanstalk platform maintenance (p. 26)
• Elastic Beanstalk platform support policy (p. 27)
• Elastic Beanstalk supported platforms (p. 29)
• Elastic Beanstalk Linux platforms (p. 30)
• Deploying Elastic Beanstalk applications from Docker containers (p. 48)
• Creating and deploying Go applications on Elastic Beanstalk (p. 98)
• Creating and deploying Java applications on Elastic Beanstalk (p. 108)
• Working with .NET Core on Linux (p. 151)
• Creating and deploying .NET applications on Elastic Beanstalk (p. 182)
• Deploying Node.js applications to Elastic Beanstalk (p. 238)
• Creating and deploying PHP applications on Elastic Beanstalk (p. 273)
• Working with Python (p. 332)
• Creating and deploying Ruby applications on Elastic Beanstalk (p. 357)
Runtime
The programming language-specific runtime software (framework, libraries, interpreter, vm, etc.)
required to run your application code.
Elastic Beanstalk Components
Software components that Elastic Beanstalk adds to a platform to enable Elastic Beanstalk
functionality. For example, the enhanced health agent is necessary for gathering and reporting
health information.
Platform
A combination of an operating system (OS), runtime, web server, application server, and Elastic
Beanstalk components. Platforms provide components that are available to run your application.
Platform Version
A combination of specific versions of an operating system (OS), runtime, web server, application
server, and Elastic Beanstalk components. You create an Elastic Beanstalk environment based on a
platform version and deploy your application to it.
A platform version has a semantic version number of the form X.Y.Z, where X is the major version, Y
is the minor version, and Z is the patch version.
24
AWS Elastic Beanstalk Developer Guide
Platforms glossary
For details about retired components, see the section called “Platform support policy” (p. 27).
Platform Branch
A line of platform versions sharing specific (typically major) versions of some of their components,
such as the operating system (OS), runtime, or Elastic Beanstalk components. For example: Python
3.6 running on 64bit Amazon Linux; IIS 10.0 running on 64bit Windows Server 2016. Each successive
platform version in the branch is an update to the previous one.
The latest platform version in each platform branch is available to you unconditionally for
environment creation. Previous platform versions in the branch are still supported—you can create
an environment based on a previous platform version if you've used it in an environment in the
last 30 days. But these previous platform versions lack the most up-to-date components and aren't
recommended for use.
A supported component has no retirement date scheduled by its supplier (owner or community). The
supplier might be AWS or a third party. A deprecated component has a retirement date scheduled
by its supplier. A retired component has reached End of Life (EOL) and is no longer supported
by its supplier. For details about retired components, see the section called “Platform support
policy” (p. 27).
If your environment uses a deprecated or retired platform branch, we recommend that you update
it to a platform version in a supported platform branch. For details, see the section called “Platform
updates” (p. 459).
Platform Update
A release of new platform versions that contain updates to some components of the platform—OS,
runtime, web server, application server, and Elastic Beanstalk components. Platform updates follow
semantic version taxonomy, and can have several levels:
25
AWS Elastic Beanstalk Developer Guide
Shared responsibility model
• Major update – An update that has changes that are incompatible with existing platform versions.
You might need to modify your application to run correctly on a new major version. A major
update has a new major platform version number.
• Minor update – An update that adds functionality that is backward compatible with an existing
platform version. You don't need to modify your application to run correctly on a new minor
version. A minor update has a new minor platform version number.
• Patch update – An update that consists of maintenance releases (bug fixes, security updates, and
performance improvements) that are backward compatible with an existing platform version. A
patch update has a new patch platform version number.
Managed Updates
An Elastic Beanstalk feature that automatically applies patch and minor updates to the operating
system (OS), runtime, web server, application server, and Elastic Beanstalk components for an Elastic
Beanstalk supported platform version. A managed update applies a newer platform version in the
same platform branch to your environment. You can configure managed updates to apply only patch
updates, or minor and patch updates. You can also disable managed updates completely.
AWS Elastic Beanstalk helps you perform your side of the shared responsibility model by providing a
managed updates feature. This feature automatically applies patch and minor updates for an Elastic
Beanstalk supported platform version. If a managed update fails, Elastic Beanstalk notifies you of the
failure to ensure that you are aware of it and can take immediate action.
• Publishes its platform support policy (p. 27) and retirement schedule for the coming 12 months.
• Releases patch, minor, and major updates of operating system (OS), runtime, application server, and
web server components typically within 30 days of their availability. Elastic Beanstalk is responsible for
creating updates to Elastic Beanstalk components that are present on its supported platform versions.
All other updates come directly from their suppliers (owners or community).
• Update all the components that you control (identified as Customer in the AWS Shared Responsibility
Model). This includes ensuring the security of your application, your data, and any components that
your application requires and that you downloaded.
• Ensure that your Elastic Beanstalk environments are running on a supported platform version, and
migrate any environment running on a retired platform version to a supported version.
• Resolve all issues that come up in failed managed update attempts and retry the update.
• Patch the OS, runtime, application server, and web server yourself if you opted out of Elastic Beanstalk
managed updates. You can do this by applying platform updates manually (p. 459) or directly
patching the components on all relevant environment resources.
26
AWS Elastic Beanstalk Developer Guide
Platform support policy
• Manage the security and compliance of any AWS services that you use outside of Elastic Beanstalk
according to the AWS Shared Responsibility Model.
When a component (operating system [OS], runtime, application server, or web server) of a supported
platform branch is marked End of Life (EOL) by its supplier, Elastic Beanstalk marks the platform branch
as retired. When a platform branch is marked as retired, Elastic Beanstalk no longer makes it available
to both existing and new Elastic Beanstalk customers for deployments to new environments. Retired
platform branches are available to existing customer environments for a period of 90 days from the
published retirement date.
Elastic Beanstalk isn't able to provide security updates, technical support, or hotfixes for retired platform
branches due to the supplier marking their component EOL. For existing customers running an Elastic
Beanstalk environment on a retired platform version beyond the 90 day period, Elastic Beanstalk may
need to automatically remove the Elastic Beanstalk components and transfer ongoing management
and support responsibility of the running application and associated AWS resources to the customer.
To continue to benefit from important security, performance, and functionality enhancements offered
by component suppliers in more recent releases, we strongly encourage you to update all your Elastic
Beanstalk environments to a supported platform version.
For a list of related Elastic Beanstalk retiring platform branches, see platform versions scheduled for
retirement in the AWS Elastic Beanstalk Platforms guide.
Runtime versions
27
AWS Elastic Beanstalk Developer Guide
Retired platform branches
28
AWS Elastic Beanstalk Developer Guide
Supported platforms
Runtime versions
Elastic Beanstalk provides platforms for programming languages (Go, Java, Node.js, PHP, Python, Ruby),
application servers (Tomcat, Passenger, Puma), and Docker containers. Some platforms have multiple
concurrently-supported versions.
Elastic Beanstalk provisions the resources needed to run your application, including one or more Amazon
EC2 instances. The software stack running on the Amazon EC2 instances depends on the specific
platform version you've selected for your environment.
You can use the solution stack name listed under the platform version name to launch an environment
with the EB CLI (p. 956), Elastic Beanstalk API, or AWS CLI. You can also retrieve solution stack
29
AWS Elastic Beanstalk Developer Guide
Supported platform versions
names from the service with the ListAvailableSolutionStacks API (aws elasticbeanstalk list-
available-solution-stacks in the AWS CLI). This operation returns all of the solution stacks that
you can use to create an environment.
Note
Each platform has supported and retired platform versions. You can always create an
environment based on a supported platform version. Retired platform versions are available
only to existing customer environments for a period of 90 days from the published retirement
date. For a list of published platform version retirement dates, see Retiring platform branch
schedule (p. 27).
When Elastic Beanstalk updates a platform, previous platform versions are still supported, but
they lack the most up-to-date components and aren't recommended for use. We recommend
that you transition to the latest platform version. You can still create an environment based on a
previous platform version if you've used it in an environment in the last 30 days (using the same
account, in the same region).
You can customize and configure the software that your application depends on in your platform.
Learn more at Customizing software on Linux servers (p. 685) and Customizing software on Windows
servers (p. 697). Detailed release notes are available for recent releases at AWS Elastic Beanstalk
Release Notes.
• Docker
• Go
• Java SE
• Tomcat
• .NET Core on Linux
• .NET on Windows Server
• Node.js
• PHP
• Python
• Ruby
Elastic Beanstalk provides platforms for different programming languages, application servers, and
Docker containers. Some platforms have multiple concurrently-supported versions.
For full coverage of Elastic Beanstalk platforms, see Elastic Beanstalk platforms (p. 24).
Many of the platforms that Elastic Beanstalk supports are based on the Linux operating system (OS).
Specifically, these platforms are based on Amazon Linux, a Linux distribution provided by AWS. Elastic
Beanstalk Linux platforms use Amazon Elastic Compute Cloud (Amazon EC2) instances, and these
30
AWS Elastic Beanstalk Developer Guide
Linux platform versions
instances run Amazon Linux. To learn more, see Amazon Linux in the Amazon EC2 User Guide for Linux
Instances.
The Elastic Beanstalk Linux platforms provide a lot of functionality out of the box. You can extend the
platforms in several ways to support your application. For details, see the section called “Extending Linux
platforms” (p. 31).
Topics
• Linux platform versions (p. 31)
• List of Elastic Beanstalk Linux platforms (p. 31)
• Extending Elastic Beanstalk Linux platforms (p. 31)
Elastic Beanstalk maintains platform versions with both Amazon Linux versions. For details about
supported platform versions, see Elastic Beanstalk supported platforms (p. 29).
Note
Amazon Linux 2 platform versions are incompatible with previous Amazon Linux AMI platform
versions. If you're migrating your Elastic Beanstalk application to Amazon Linux 2, read the
section called “Upgrade to Amazon Linux 2” (p. 470).
31
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
several ways to configure options, install software, add files and start-up commands, provide build
and runtime instructions, and add initialization scripts that run in various provisioning stages of your
environment's Amazon Elastic Compute Cloud (Amazon EC2) instances.
For all supporting platforms, syntax and semantics are identical, and are as described on this page.
Individual platform topics mention specific usage of these files for building and running applications in
their respective languages.
Buildfile
To specify a custom build and configuration command for your application, place a file named
Buildfile in the root directory of your application source. The file name is case sensitive. Use the
following syntax for your Buildfile.
<process_name>: <command>
The command in your Buildfile must match the following regular expression: ^[A-Za-z0-9_-]+:
\s*[^\s].*$
Elastic Beanstalk doesn't monitor the application that is run with a Buildfile. Use a Buildfile for
commands that run for short periods and terminate after completing their tasks. For long-running
application processes that should not exit, use a Procfile (p. 32).
All paths in the Buildfile are relative to the root of the source bundle. In the following example of a
Buildfile, build.sh is a shell script located at the root of the source bundle.
Example Buildfile
make: ./build.sh
If you want to provide custom build steps, we recommend that you use predeploy platform hooks for
anything but the simplest commands, instead of a Buildfile. Platform hooks allow richer scripts and
better error handling. Platform hooks are described in the next section.
Procfile
To specify custom commands to start and run your application, place a file named Procfile in the root
directory of your application source. The file name is case sensitive. Use the following syntax for your
Procfile. You can specify one or more commands.
<process_name1>: <command1>
<process_name2>: <command2>
...
Each line in your Procfile must match the following regular expression: ^[A-Za-z0-9_-]+:\s*[^
\s].*$
Use a Procfile for long-running application processes that shouldn't exit. Elastic Beanstalk expects
processes run from the Procfile to run continuously. Elastic Beanstalk monitors these processes and
restarts any process that terminates. For short-running processes, use a Buildfile (p. 32).
32
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
All paths in the Procfile are relative to the root of the source bundle. The following example
Procfile defines three processes. The first one, called web in the example, is the main web application.
Example Procfile
web: bin/myserver
cache: bin/mycache
foo: bin/fooapp
Elastic Beanstalk configures the proxy server to forward requests to your main web application on
port 5000, and you can configure this port number. A common use for a Procfile is to pass this port
number to your application as a command argument. For details about proxy configuration, expand the
Reverse proxy configuration section on this page.
Elastic Beanstalk captures standard output and error streams from Procfile processes in log files.
Elastic Beanstalk names the log files after the process and stores them in /var/log. For example, the
web process in the preceding example generates logs named web-1.log and web-1.error.log for
stdout and stderr, respectively.
Platform hooks
Platform hooks are specifically designed to extend your environment's platform. These are custom
scripts and other executable files that you deploy as part of your application's source code, and Elastic
Beanstalk runs during various instance provisioning stages.
Note
Platform hooks aren't supported on Amazon Linux AMI platform versions (preceding Amazon
Linux 2).
An application deployment occurs when you provide a new source bundle for deployment, or when you
make a configuration change that requires termination and recreation of all environment instances.
To provide platform hooks that run during an application deployment, place the files under the
.platform/hooks directory in your source bundle, in one of the following subdirectories.
• prebuild – Files here run after the Elastic Beanstalk platform engine downloads and extracts the
application source bundle, and before it sets up and configures the application and web server.
The prebuild files run after running commands found in the commands (p. 691) section of any
configuration file and before running Buildfile commands.
• predeploy – Files here run after the Elastic Beanstalk platform engine sets up and configures the
application and web server, and before it deploys them to their final runtime location.
The predeploy files run after running commands found in the container_commands (p. 694) section
of any configuration file and before running Procfile commands.
• postdeploy – Files here run after the Elastic Beanstalk platform engine deploys the application and
proxy server.
A configuration deployment occurs when you make configuration changes that only update environment
instances without recreating them. The following option updates cause a configuration update.
33
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
To provide hooks that run during a configuration deployment, place them under the .platform/
confighooks directory in your source bundle. The same three subdirectories as for application
deployment hooks apply.
Hook files can be binary files, or script files starting with a #! line containing their interpreter path, such
as #!/bin/bash. All files have to have execute permission. Use chmod +x to set execute permission on
your hook files.
Elastic Beanstalk runs files in each one of these directories in lexicographical order of file names. All files
run as the root user. The current working directory (cwd) for platform hooks is the application's root
directory. For prebuild and predeploy files it's the application staging directory, and for postdeploy
files it's the current application directory. If one of the files fails (exits with a non-zero exit code), the
deployment aborts and fails.
Hook files have access to all environment properties that you've defined in application options, and to
the system environment variables HOME, PATH, and PORT.
To get values of environment variables and other configuration options into your platform hook scripts,
you can use the get-config utility that Elastic Beanstalk provides on environment instances. For
details, see the section called “Platform script tools” (p. 42).
Configuration files
You can add configuration files (p. 683) to the .ebextensions directory of your application's
source code to configure various aspects of your Elastic Beanstalk environment. Among other things,
configuration files let you customize software and other files on your environment's instances and
run initialization commands on the instances. For more information, see the section called “Linux
server” (p. 685).
You can also set configuration options (p. 613) using configuration files. Many of the options control
platform behavior, and some of these options are platform specific (p. 674).
On Amazon Linux 2 platforms, we recommend using Buildfile, Procfile, and platform hooks to configure
and run custom code on your environment instances during instance provisioning. These mechanisms
are described in the previous sections on this page. You can still use commands and container commands
in .ebextensions configuration files, but they aren't as easy to work with. For example, writing
command scripts inside a YAML file can be challenging from a syntax standpoint. You still need to use
.ebextensions configuration files for any script that needs a reference to a AWS CloudFormation
resource.
34
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
Note
On Amazon Linux AMI platform versions (preceding Amazon Linux 2) you might have to
configure proxy servers differently. You can find these legacy details under the respective
platform topics (p. 24) in this guide.
Elastic Beanstalk configures the proxy server on your environment's instances to forward web
traffic to the main web application on the root URL of the environment; for example, http://my-
env.elasticbeanstalk.com.
By default, Elastic Beanstalk configures the proxy to forward requests coming in on port 80 to your main
web application on port 5000. You can configure this port number by setting the PORT environment
property using the aws:elasticbeanstalk:application:environment (p. 648) namespace in a configuration
file, as shown in the following example.
option_settings:
- namespace: aws:elasticbeanstalk:application:environment
option_name: PORT
value: <main_port_number>
For more information about setting environment variables for your application, see the section called
“Option settings” (p. 684).
Your application should listen on the port that is configured for it in the proxy. If you change the default
port using the PORT environment property, your code can access it by reading the value of the PORT
environment variable. For example, call os.Getenv("PORT") in Go, or System.getenv("PORT")
in Java. If you configure your proxy to send traffic to multiple application processes, you can configure
several environment properties, and use their values in both proxy configuration and your application
code. Another option is to pass the port value to the process as a command argument in the Procfile.
For details on that, expand the Buildfile and Procfile section on this page.
Configuring nginx
Elastic Beanstalk uses nginx as the default reverse proxy to map your application to your Elastic Load
Balancing load balancer. Elastic Beanstalk provides a default nginx configuration that you can extend or
override completely with your own configuration.
Note
When you add or edit an nginx .conf configuration file, be sure to encode it as UTF-8.
To extend the Elastic Beanstalk default nginx configuration, add .conf configuration files to a folder
named .platform/nginx/conf.d/ in your application source bundle. The Elastic Beanstalk nginx
configuration includes .conf files in this folder automatically.
~/workspace/my-app/
|-- .platform
| `-- nginx
| `-- conf.d
| `-- myconf.conf
`-- other source files
To override the Elastic Beanstalk default nginx configuration completely, include a configuration in your
source bundle at .platform/nginx/nginx.conf:
~/workspace/my-app/
|-- .platform
| `-- nginx
| `-- nginx.conf
35
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
If you override the Elastic Beanstalk nginx configuration, add the following line to your nginx.conf
to pull in the Elastic Beanstalk configurations for Enhanced health reporting and monitoring (p. 776),
automatic application mappings, and static files.
include conf.d/elasticbeanstalk/*.conf;
The Tomcat, Node.js, PHP, and Python platforms allow you to choose the Apache HTTPD proxy server as
an alternative to nginx. This isn't the default. The following example configures Elastic Beanstalk to use
Apache HTTPD.
Example .ebextensions/httpd-proxy.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: apache
You can extend the Elastic Beanstalk default Apache configuration with your additional configuration
files. Alternatively, you can override the Elastic Beanstalk default Apache configuration completely.
To extend the Elastic Beanstalk default Apache configuration, add .conf configuration files to a folder
named .platform/httpd/conf.d in your application source bundle. The Elastic Beanstalk Apache
configuration includes .conf files in this folder automatically.
~/workspace/my-app/
|-- .ebextensions
| -- httpd-proxy.config
|-- .platform
| -- httpd
| -- conf.d
| -- port5000.conf
| -- ssl.conf
-- index.jsp
For example, the following Apache 2.4 configuration adds a listener on port 5000.
Example .platform/httpd/conf.d/port5000.conf
listen 5000
<VirtualHost *:5000>
<Proxy *>
Require all granted
</Proxy>
ProxyPass / http://localhost:8080/ retry=0
ProxyPassReverse / http://localhost:8080/
ProxyPreserveHost on
ErrorLog /var/log/httpd/elasticbeanstalk-error_log
</VirtualHost>
To override the Elastic Beanstalk default Apache configuration completely, include a configuration in
your source bundle at .platform/httpd/conf/httpd.conf.
~/workspace/my-app/
36
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
|-- .ebextensions
| -- httpd-proxy.config
|-- .platform
| `-- httpd
| `-- conf
| `-- httpd.conf
`-- index.jsp
If you override the Elastic Beanstalk Apache configuration, add the following lines to your httpd.conf
to pull in the Elastic Beanstalk configurations for Enhanced health reporting and monitoring (p. 776),
automatic application mappings, and static files.
IncludeOptional conf.d/elasticbeanstalk/*.conf
If you're migrating your Elastic Beanstalk application to an Amazon Linux 2 platform, be sure to also read
the information in the section called “Upgrade to Amazon Linux 2” (p. 470).
Topics
• Application example with extensions (p. 37)
• Instance deployment workflow (p. 38)
• Instance deployment workflow for ECS running on Amazon Linux 2 (p. 40)
• Platform script tools (p. 42)
~/my-app/
|-- web.jar
|-- Procfile
|-- readme.md
|-- .ebextensions/
| |-- options.config # Option settings
| `-- cloudwatch.config # Other .ebextensions sections, for example files and
container commands
`-- .platform/
|-- nginx/ # Proxy configuration
| |-- nginx.conf
| `-- conf.d/
| `-- custom.conf
|-- hooks/ # Application deployment hooks
| |-- prebuild/
| | |-- 01_set_secrets.sh
| | `-- 12_update_permissions.sh
| |-- predeploy/
| | `-- 01_some_service_stop.sh
| `-- postdeploy/
| |-- 01_set_tmp_file_permissions.sh
| |-- 50_run_something_after_app_deployment.sh
| `-- 99_some_service_start.sh
`-- confighooks/ # Configuration deployment hooks
|-- prebuild/
| `-- 01_set_secrets.sh
|-- predeploy/
| `-- 01_some_service_stop.sh
`-- postdeploy/
37
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
|-- 01_run_something_after_config_deployment.sh
`-- 99_some_service_start.sh
Note
Some of these extensions aren't supported on Amazon Linux AMI platform versions (preceding
Amazon Linux 2).
With many ways to extend your environment's platform, it's useful to know what happens whenever
Elastic Beanstalk provisions an instance or runs a deployment to an instance. The following diagram
shows this entire deployment workflow. It depicts the different phases in a deployment and the steps
that Elastic Beanstalk takes in each phase.
Notes
• The diagram doesn't represent the complete set of steps that Elastic Beanstalk takes on
environment instances during deployment. We provide this diagram for illustration, to provide
you with the order and context for the execution of your customizations.
• For simplicity, the diagram mentions only the .platform/hooks/* hook subdirectories (for
application deployments), and not the .platform/confighooks/* hook subdirectories (for
configuration deployments). Hooks in the latter subdirectories run during exactly the same
steps as hooks in corresponding subdirectories shown in the diagram.
38
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
39
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
1. Initial steps
Elastic Beanstalk downloads and extracts your application. After each one of these steps, Elastic
Beanstalk runs one of the extensibility steps.
a. Runs commands found in the commands: (p. 691) section of any configuration file.
b. Runs any executable files found in the .platform/hooks/prebuild directory of your source
bundle (.platform/confighooks/prebuild for a configuration deployment).
2. Configure
Elastic Beanstalk deploys and runs your application and the proxy server.
a. Runs the command found in the Procfile file in your source bundle.
b. Runs or reruns the proxy server with your custom proxy configuration files, if you have any.
c. Runs any executable files found in the .platform/hooks/postdeploy directory of your source
bundle (.platform/confighooks/postdeploy for a configuration deployment).
With many ways to extend your environment's platform, it's useful to know what happens whenever
Elastic Beanstalk provisions an instance or runs a deployment to an instance. The following diagram
shows this entire deployment workflow for an environment based on the ECS running on Amazon Linux
2 platform branch. It depicts the different phases in a deployment and the steps that Elastic Beanstalk
takes in each phase.
Unlike the workflow described in the prior section, the deployment Configuration phase doesn't support
the following extensibility features: Buildfile commands, Procfile commands, reverse proxy
configuration.
Notes
• The diagram doesn't represent the complete set of steps that Elastic Beanstalk takes on
environment instances during deployment. We provide this diagram for illustration, to provide
you with the order and context for the execution of your customizations.
• For simplicity, the diagram mentions only the .platform/hooks/* hook subdirectories (for
application deployments), and not the .platform/confighooks/* hook subdirectories (for
configuration deployments). Hooks in the latter subdirectories run during exactly the same
steps as hooks in corresponding subdirectories shown in the diagram.
40
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
41
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
a. Runs any executable files found in the appdeploy/pre directory under EBhooksDir.
b. Runs any executable files found in the .platform/hooks/prebuild directory of your source bundle
(.platform/confighooks/prebuild for a configuration deployment).
c. Runs any executable files found in the .platform/hooks/predeploy directory of your source
bundle (.platform/confighooks/predeploy for a configuration deployment).
d. Runs any executable files found in the appdeploy/enact directory under EBhooksDir.
e. Runs any executable files found in the appdeploy/post directory under EBhooksDir.
f. Runs any executable files found in the .platform/hooks/postdeploy directory of your source
bundle (.platform/confighooks/postdeploy for a configuration deployment).
The reference to EBhooksDir represents the path of the platform hooks directory. To retrieve directory
path name use the get-config (p. 42) script tool on the command line of your environment instance as
shown:
get-config
Use the get-config tool to retrieve environment variable values and other platform and instance
information. The tool is available at /opt/elasticbeanstalk/bin/get-config.
get-config commands
Each get-config tool command returns a specific type of information. Use the following syntax to run
the commands of any of the tools.
Depending on the command and options you choose, the tool returns an object (JSON or YAML) with
key-value pairs or a single value.
You can test get-config by using SSH to connect to an EC2 instance in your Elastic Beanstalk
environment.
Note
When you run get-config for testing, some commands might require root user privileges to
access the underlying information. If you get an access permission error, run the command again
under sudo.
You don't need to add sudo when using the tool in the scripts that you deploy to your
environment. Elastic Beanstalk runs all your scripts as the root user.
42
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
$ /opt/elasticbeanstalk/bin/get-config optionsettings
{"aws:elasticbeanstalk:application:environment":
{"JDBC_CONNECTION_STRING":""},"aws:elasticbeanstalk:container:tomcat:jvmoptions":{"JVM
Options":"","Xms":"256m","Xmx":"256m"},"aws:elasticbeanstalk:environment:proxy":
{"ProxyServer":"nginx","StaticFiles":[""]},"aws:elasticbeanstalk:healthreporting:system":
{"SystemType":"enhanced"},"aws:elasticbeanstalk:hostmanager":
{"LogPublicationControl":"false"}}
To return a specific configuration option value, use the --namespace (-n) option to specify a
namespace, and the --option-name (-o) option to specify an option name.
$ /opt/elasticbeanstalk/bin/get-config optionsettings -
n aws:elasticbeanstalk:container:php:phpini -o memory_limit
256M
$ /opt/elasticbeanstalk/bin/get-config environment
{"JDBC_CONNECTION_STRING":"","RDS_PORT":"3306","RDS_HOSTNAME":"anj9aw1b0tbj6b.cijbpanmxz5u.us-
west-2.rds.amazonaws.com","RDS_USERNAME":"testusername","RDS_DB_NAME":"ebdb","RDS_PASSWORD":"testpasswo
For example, Elastic Beanstalk provides environment properties for connecting to an integrated
Amazon RDS DB instance (for example, RDS_HOSTNAME). These RDS connection properties appear in
the output of get-config environment. However, they don't appear in the output of get-config
optionsettings. This is because they weren't set in configuration options.
To return a specific environment property, use the --key (-k) option to specify a property key.
The following example shows the output for the command on an Amazon Linux 2 Tomcat environment.
$ /opt/elasticbeanstalk/bin/get-config container
{"common_log_list":["/var/log/eb-engine.log","/var/log/eb-
hooks.log"],"default_log_list":["/var/log/nginx/access.log","/var/log/nginx/
error.log"],"environment_name":"myenv-1da84946","instance_port":"80","log_group_name_prefix":"/
aws/elasticbeanstalk","proxy_server":"nginx","static_files":[""],"xray_enabled":"false"}
To return the value of a specific key, use the --key (-k) option to specify the key.
43
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
The get-config addons command returns an object that contains configuration information of
environment add-ons. Use it to retrieve the configuration of an Amazon RDS database that's associated
with the environment.
$ /opt/elasticbeanstalk/bin/get-config addons
{"rds":{"Description":"RDS Environment variables","env":
{"RDS_DB_NAME":"ebdb","RDS_HOSTNAME":"ea13k2wimu1dh8i.c18mnpu5rwvg.us-
east-2.rds.amazonaws.com","RDS_PASSWORD":"password","RDS_PORT":"3306","RDS_USERNAME":"user"}}}
You can restrict the result in two ways. To retrieve values for a specific add-on, use the --add-on (-a)
option to specify the add-on name.
To return the value of a specific key within an add-on, add the --key (-k) option to specify the key.
The get-config platformconfig command returns an object that contains platform configuration
information that's constant to the platform version. The output is the same on all environments that run
the same platform version. The output object for the command has two embedded objects:
• GeneralConfig – Contains information that's constant across the latest versions of all Amazon Linux
2 platform branches.
• PlatformSpecificConfig – Contains information that's constant for the platform version and is
specific to it.
The following example shows the output for the command on an environment that uses the Tomcat 8.5
running Corretto 11 platform branch.
$ /opt/elasticbeanstalk/bin/get-config platformconfig
{"GeneralConfig":{"AppUser":"webapp","AppDeployDir":"/var/app/current/","AppStagingDir":"/
var/app/
staging/","ProxyServer":"nginx","DefaultInstancePort":"80"},"PlatformSpecificConfig":
{"ApplicationPort":"8080","JavaVersion":"11","TomcatVersion":"8.5"}}
To return the value of a specific key, use the --key (-k) option to specify the key. These keys are unique
across the two embedded objects. You don't need to specify the object that contains the key.
Use the --output option to specify the output object format. Valid values are JSON (default) and YAML.
This is a global option. You must specify it before the command name.
The following example returns configuration option values in the YAML format.
44
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
pkg-repo
In some urgent circumstances, you might need to update your Amazon EC2 instances with an Amazon
Linux 2 security patch that hasn't yet been released with the required Elastic Beanstalk platform
versions. You can't perform a manual update on your Elastic Beanstalk environments by default. This is
because the platform versions are locked to a specific version of the Amazon Linux 2 repository. This lock
ensures that instances run supported and consistent software versions. For urgent cases, the pkg-repo
tool allows a workaround to manually update yum packages on Amazon Linux 2 if you need to install it
on an environment before it's released in a new Elastic Beanstalk platform version.
The pkg-repo tool on Amazon Linux 2 platforms provides the capability to unlock the yum package
repositories. You can then manually perform a yum update for a security patch. Conversely, you can
follow the update by using the tool to lock the yum package repositories to prevent further updates. The
pkg-repo tool is available at the /opt/elasticbeanstalk/bin/pkg-repo directory of all the EC2
instances in your Elastic Beanstalk environments.
Changes using the pkg-repo tool are made only on the EC2 instance that the tool is used on. They
don’t affect other instances or prevent future updates to the environment. The examples that are
provided later in this topic explain how to apply the changes across all instances by calling the pkg-
repo commands from scripts and configuration files.
Warning
We don't recommend this tool for most users. Any manual changes applied to an unlocked
platform version are considered out of band. This option is only viable for those users in urgent
circumstances that can accept the following risks:
We strongly recommend applying best practices that include testing and backout plans. To
help facilitate best practices, you can use the Elastic Beanstalk console and EB CLI to clone an
environment and swap environment URLs. For more information about using these operations,
see Blue/Green deployments (p. 449) in the Managing environments chapter of this guide.
If you plan to manually edit yum repository configuration files, run the pkg-repo tool first. The pkg-
repo tool might not work as intended in an Amazon Linux 2 environment with manually edited yum
repository configuration files. This is because the tool might not recognize the configuration changes.
For more information about the Amazon Linux package repository, see the Package repository topic in
the Amazon EC2 User Guide for Linux Instances.
45
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
pkg-repo commands
The following example runs the help command for the lock command.
The following example runs the help command for the pkg-repo tool.
You can test pkg-repo by using SSH to connect to an instance in your Elastic Beanstalk environment.
One SSH option is the EB CLI eb ssh (p. 1036) command.
Note
The pkg-repo tool requires root user privileges to run. If you get an access permission error, run
the command again under sudo.
You don't need to add sudo when using the tool in the scripts or configuration files that you
deploy to your environment. Elastic Beanstalk runs all your scripts as the root user.
46
AWS Elastic Beanstalk Developer Guide
Extending Linux platforms
pkg-repo examples
The previous section provides command line examples for testing on an individual EC2 instance of an
Elastic Beanstalk environment. This approach can be helpful for testing. However, it updates only one
instance at a time, so it isn’t practical for applying changes to all of the instances in an environment.
A more pragmatic approach is to use platform hook (p. 33) scripts or an .ebextensions (p. 683)
configuration file to apply the changes across all instances in a consistent manner.
The following example calls pkg-repo from a configuration file in the .ebextensions (p. 683) folder.
Elastic Beanstalk runs the commands in the update_package.config file when you deploy your
application source bundle.
.ebextensions
### update_package.config
To receive the latest version of the docker package, this configuration specifies the docker package in the
yum update command.
commands:
update_package:
command: |
/opt/elasticbeanstalk/bin/pkg-repo unlock
yum update docker -y
/opt/elasticbeanstalk/bin/pkg-repo lock
yum clean all -y
rm -rf /var/cache/yum
This configuration doesn't specify any packages in the yum update command. All available updates are
applied as a result.
commands:
update_package:
command: |
/opt/elasticbeanstalk/bin/pkg-repo unlock
yum update -y
/opt/elasticbeanstalk/bin/pkg-repo lock
yum clean all -y
rm -rf /var/cache/yum
The following example calls pkg-repo from a bash script as a platform hook (p. 33). Elastic Beanstalk
runs the update_package.sh script file that's located in the prebuild subdirectory.
.platform
### hooks
### prebuild
### update_package.sh
To receive the latest version of the docker package, this script specifies the docker package in the yum
update command. If the package name is omitted, all the available updates are applied. The prior
configuration file example demonstrates this.
47
AWS Elastic Beanstalk Developer Guide
Working with Docker
#!/bin/bash
/opt/elasticbeanstalk/bin/pkg-repo unlock
yum update docker -y
/opt/elasticbeanstalk/bin/pkg-repo lock
yum clean all -y
rm -rf /var/cache/yum
The example script 00-unzip.sh is located in the appdeploy/pre folder on environment instances. It
demonstrates how to use download-source-bundle to download the application source code to the /
opt/elasticbeanstalk/deploy/appsource folder during deployment.
By using Docker with Elastic Beanstalk, you have an infrastructure that handles all the details of capacity
provisioning, load balancing, scaling, and application health monitoring. You can easily manage your
web application in an environment that supports the range of services that are integrated with Elastic
Beanstalk.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics. This chapter also assumes that you have a basic understanding of Docker and how it works.
For more information see Docker overview on the Docker website.
For more information about supported platform branches for each Docker platform, see the Supported
Platforms page in the AWS Elastic Beanstalk Platforms document.
There are three other platform branches that support Docker. These will be retired on June 30, 2022. All
of these run on Amazon Linux AMI, which precedes Amazon Linux 2:
48
AWS Elastic Beanstalk Developer Guide
The Docker platform family
For a list all Elastic Beanstalk platform branches scheduled for retirement, see platform branches
scheduled for retirement in the AWS Elastic Beanstalk Platforms guide.
This platform branch can be used to deploy a Docker image, described in a Dockerfile or a
Dockerrun.aws.json v1 definition. This platform only supports the Amazon Linux AMI operating
system, (the version that precedes Amazon Linux 2), and it runs only one container for each instance.
We recommend that you create your environments with the newer and supported platform branch
Docker running on 64bit Amazon Linux 2. For more information, see the section called “Docker platform
branch” (p. 50).
This platform branch uses Amazon ECS to coordinate a deployment of multiple Docker containers to an
Amazon ECS cluster in an Elastic Beanstalk environment. However, it only supports the Amazon Linux
AMI operating system, (the version that precedes Amazon Linux 2). Instead of using this platform branch,
we recommend that you use one of the prior-mentioned Docker platform branches that run on Amazon
Linux 2.
If you're already using this platform branch, we recommend that you migrate to the latest ECS Running
on 64bit Amazon Linux 2 platform branch. The latest platform branch supports all of the features from
this discontinued platform branch. No changes to the source code are required. For more information,
see Migrating Multi-container Docker running on Amazon Linux to ECS on Amazon Linux 2 (p. 79).
49
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Amazon Linux 2). This platform branch has been superseded by the platform branch Docker Running on
64bit Amazon Linux 2. Deploy GlassFish and your application code to an Amazon Linux 2 Docker image
to easily migrate your GlassFish application to this newer and supported platform branch. For more
information, see Deploying a GlassFish application to the Docker platform (p. 87).
Topics
• Prerequisites (p. 50)
• Containerize an Elastic Beanstalk application (p. 50)
• Test a container locally (p. 51)
• Deploy a container with a Dockerfile (p. 52)
• Test a remote Docker image (p. 52)
• Deploy a remote Docker image to Elastic Beanstalk (p. 53)
• Clean up (p. 54)
• Running a Docker environment locally with the EB CLI (p. 54)
• Docker configuration (p. 58)
Prerequisites
This tutorial assumes that you have some knowledge of basic Elastic Beanstalk operations, the Elastic
Beanstalk command line interface (EB CLI), and Docker. If you haven't already, follow the instructions
in Getting started using Elastic Beanstalk (p. 3) to launch your first Elastic Beanstalk environment. This
tutorial uses the EB CLI (p. 956), but you can also create environments and upload applications by using
the Elastic Beanstalk console.
To follow this tutorial, you will also need the following Docker components:
• A working local installation of Docker. For more information, see Get Docker on the Docker
documentation website.
• Access to Docker Hub. You will need to create a Docker ID to access the Docker Hub. For more
information, see Share the application on the Docker documentation website.
To learn more about configuring Docker environments on Elastic Beanstalk platforms, see Docker
configuration (p. 58) in this same chapter.
~/eb-docker-flask/
|-- Dockerfile
50
AWS Elastic Beanstalk Developer Guide
Docker platform branch
|-- application.py
Example ~/eb-docker-flask/application.py
# Add a rule when the page is accessed with a name appended to the site
# URL
application.add_url_rule('/<username>', 'hello', (lambda username:
header_text + say_hello(username) + home_link + footer_text))
Example ~/eb-docker-flask/Dockerfile
FROM python:3.6
COPY . /app
WORKDIR /app
RUN pip install Flask==1.0.2
EXPOSE 5000
CMD ["python", "application.py"]
(Optional) Use the eb local run command to build and run your container locally.
51
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Note
To learn more about the eb local command, see the section called “eb local” (p. 1021). The
command isn't supported on Windows. Alternatively, you can build and run your container
with the docker build and docker run commands. For more information, see the Docker
documentation.
(Optional) While your container is running, use the eb local open command to view your application in a
web browser. Alternatively, open http://localhost:5000/ in a web browser.
Use the eb create command to create an environment and deploy your application.
After your environment launches, use the eb open command to view it in a web browser.
~/eb-docker-flask$ eb open
Once we've built and pushed our image, we can deploy it to Elastic Beanstalk with a docker-
compose.yml file, if you are using Docker Compose with your Docker environment. If you are not
using Docker Compose with your Docker environment, use a Dockerrun.aws.json file instead. To
build a Docker image of the Flask application and push it to Docker Hub, run the following commands.
We're using the same directory from the previous example, but you can use any directory with your
application's code. Enter your Docker ID for docker-id to sign in to Docker Hub.
Note
Before pushing your image, you might need to run docker login. You will be prompted for your
Docker Hub credentials if you run the command without parameters.
If you are using the Docker Compose tool to manage your Docker environment, now you can deploy your
application using only a docker-compose.yml file. To learn more about docker-compose.yml files,
see Docker configuration (p. 58).
If you are not using Docker Compose, use a Dockerrun.aws.json file instead. For more information
see Deploy using Dockerrun.aws.json v1 (without Docker Compose) (p. 53).
52
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Example ~/remote-docker/docker-compose.yml
version: '3.8'
services:
beanstalk-flask:
image: "username/beanstalk-flask"
ports:
- "80:5000"
If you are not using the Docker Compose tool to manage your Docker environment, now you can deploy
your application using only a Dockerrun.aws.json file. To learn more about Dockerrun.aws.json
files, see Configuration for Docker platforms (without Docker Compose) (p. 62).
Example ~/remote-docker/Dockerrun.aws.json
{
"AWSEBDockerrunVersion": "1",
"Image": {
"Name": "username/beanstalk-flask",
"Update": "true"
},
"Ports": [
{
"ContainerPort": "5000"
}
]
}
Use the EB CLI to configure your local repository for deployment to Elastic Beanstalk.
(Optional) Use eb local run to build and run your container locally. To learn more about the eb local
command, see eb local (p. 1021).
(Optional) While your container is running, use the eb local open command to view your application in a
web browser. Alternatively, open http://localhost:5000/ in a web browser.
53
AWS Elastic Beanstalk Developer Guide
Docker platform branch
~/remote-docker$ eb open
Clean up
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Topics
• Prerequisites for running Docker applications locally (p. 54)
• Preparing a Docker application for use with the EB CLI (p. 55)
• Running a Docker application locally (p. 55)
• Cleaning up after running a Docker application locally (p. 57)
Run eb init in your project directory to initialize an EB CLI repository. If you haven't used the EB CLI
before, see Managing Elastic Beanstalk environments with the EB CLI (p. 968).
• Docker version 1.6 or greater
54
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Add yourself to the docker group, log out, and then log back in to ensure that you can run Docker
commands without sudo:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS
PORTS NAMES
• A Docker application
If you don't have a Docker application in a project folder on your local machine, see Deploying Elastic
Beanstalk applications from Docker containers (p. 48) for an introduction to using Docker with AWS
Elastic Beanstalk.
• Docker profile (optional)
If your application uses Docker images that are in a private repository, run docker login and follow
the prompts to create an authentication profile.
• w3m (optional)
W3m is a web browser that you can use to view your running web application within a command line
terminal with eb local run. If you are using the command line in a desktop environment, you don't
need w3m.
Docker containers run locally without emulating AWS resources that are provisioned when you deploy an
application to Elastic Beanstalk, including security groups and data or worker tiers.
You can configure your local containers to connect to a database by passing the necessary connection
string or other variables with the envvars option, but you must ensure that any resources in AWS are
accessible from your local machine by opening the appropriate ports in their assigned security groups or
attaching a default gateway or elastic IP address.
The EB CLI reads the Docker configuration and executes the Docker commands necessary to run your
application. The first time you run a project locally, Docker downloads images from a remote repository
and stores them on your local machine. This process can take several minutes.
55
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Note
The eb local run command takes two optional parameters, port and envvars.
To override the default port for a Docker application, use the port option:
This command tells the EB CLI to use port 8080 on the host and map it to the exposed port on
the container. If you don't specify a port, the EB CLI uses the container's port for the host. This
option only works with applications using the Docker platform.
To pass environment variables to the application containers, use the envvars option:
Use environment variables to configure a database connection, set debug options, or pass
secrets securely to your application. For more information on the options supported by the eb
local subcommands, see eb local (p. 1021).
After the containers are up and running in Docker, they are ready to take requests from clients. The
eb local process stays open as long as the containers are running. If you need to stop the process and
containers, press Ctrl+C.
Open a second terminal to run additional commands while the eb local process is running. Use eb local
status to view your application's status:
You can use docker ps to see the status of the containers from Docker's point of view:
~/project$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS
PORTS NAMES
6a8e71274fed nginx:latest "nginx -g 'daemon of 9 minutes ago Up 9
minutes 0.0.0.0:80->80/tcp, 443/tcp elasticbeanstalk_nginxproxy_1
82cbf620bdc1 php:fpm "php-fpm" 9 minutes ago Up 9
minutes 9000/tcp elasticbeanstalk_phpapp_1
This command opens your application in the default web browser. If you are running a terminal in a
desktop environment, this may be Firefox, Safari, or Google Chrome. If you are running a terminal in a
headless environment or over an SSH connection, a command line browser, such as w3m, will be used if
one is available.
56
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Switch back to the terminal running the application process for a moment and note the additional
output:
This shows that the web application in the Docker container received an HTTP GET request for index.php
that was returned successfully with a 200 (non error) status.
Run eb local logs to see where the EB CLI writes the logs.
Return to the terminal running the eb local process and press Ctrl+C to stop the application:
Aborting.
[1]+ Exit 5 eb local run
The EB CLI attempts to stop each running container gracefully with Docker commands. If you need to
stop a process immediately, press Ctrl+C again.
After you stop the applications, the Docker containers should also stop running. Verify this with docker
ps:
$ docker ps --all
CONTAINER ID IMAGE COMMAND CREATED STATUS
PORTS NAMES
73d515d99d2a nginx:latest "nginx -g 'daemon of 21 minutes ago Exited
(0) 11 minutes ago elasticbeanstalk_nginxproxy_1
7061c76220de php:fpm "php-fpm" 21 minutes ago Exited
(0) 11 minutes ago elasticbeanstalk_phpapp_1
The all option shows stopped containers (if you omitted this option, the output will be blank). In the
above example, Docker shows that both containers exited with a 0 (non-error) status.
If you are done using Docker and EB CLI local commands, you can remove the Docker images from your
local machine to save space.
$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL
SIZE
57
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Docker configuration
This section describes how to prepare your Docker image and container for deployment to Elastic
Beanstalk.
This section describes how to prepare your Docker image and container for deployment to Elastic
Beanstalk. Any web application that you deploy to Elastic Beanstalk in a Docker environment must
include a docker-compose.yml file if you also use the Docker Compose tool. You can deploy your web
application as a containerized service to Elastic Beanstalk by doing one of the following actions:
• Create a docker-compose.yml file to deploy a Docker image from a hosted repository to Elastic
Beanstalk. No other files are required if all your deployments are sourced from images in public
repositories. (If your deployment must source an image from a private repository, you need to include
additional configuration files for authentication. For more information, see Using images from
a private repository (p. 59).) For more information about the docker-compose.yml file, see
Compose file reference on the Docker website.
• Create a Dockerfile to have Elastic Beanstalk build and run a custom image. This file is optional,
depending on your deployment requirements. For more information about the Dockerfile see
Dockerfile reference on the Docker website.
• Create a .zip file containing your application files, any application file dependencies, the
Dockerfile, and the docker-compose.yml file. If you use the EB CLI to deploy your application, it
creates a .zip file for you. The two files must be at the root, or top level, of the .zip archive.
If you use only a docker-compose.yml file to deploy your application, you don't need to create a
.zip file.
This topic is a syntax reference. For detailed procedures on launching Docker environments using Elastic
Beanstalk, see Using the Docker platform branch (p. 50).
To learn more about Docker Compose and how to install it, see the Docker sites Overview of Docker
Compose and Install Docker Compose.
Note
If you don't use Docker Compose to configure your Docker environments, then you shouldn't
use the docker-compose.yml file either. Instead, use the Dockerrun.aws.json file or the
Dockerfile or both.
58
AWS Elastic Beanstalk Developer Guide
Docker platform branch
For more information, see the section called “Configuration for Docker platforms (without
Docker Compose) ” (p. 62).
You can configure Elastic Beanstalk to log in to your private repository before it starts the deployment
process. This enables Elastic Beanstalk to access the images from the repository and deploy these images
to your Elastic Beanstalk environment.
This configuration initiates events in the prebuild phase of the Elastic Beanstalk deployment process.
You set this up in the .ebextentions (p. 683) configuration directory. The configuration uses platform
hook (p. 33) scripts that call docker login to authenticate to the online registry that hosts the private
repository. A detailed breakdown of these configuration steps follows.
To configure Elastic Beanstalk to authenticate to your private repository with AWS SSM
Note
You need to set up AWS Systems Manager to complete these steps. For more information, see
the AWS Systems Manager User Guide
### .ebextensions
# ### env.config
### .platform
# ### confighooks
# # ### prebuild
# # ### 01login.sh
# ### hooks
# ### prebuild
# ### 01login.sh
### docker-compose.yml
2. Use the AWS Systems Manager Parameter Store to save the credentials of your private repository so
that Elastic Beanstalk can retrieve your credentials when required. For this, run the put-parameter
command.
3. Create the following env.config file and place it in the .ebextensions directory as shown in the
preceding directory structure.
Note
USER and PASSWD in the script must match the same strings that are used in the preceding
ssm put-parameter commands.
option_settings:
59
AWS Elastic Beanstalk Developer Guide
Docker platform branch
aws:elasticbeanstalk:application:environment:
USER: '{{resolve:ssm:USER:1}}'
PASSWD: '{{resolve:ssm:PASSWD:1}}'
4. Create the following 01login.sh script file and place it in the following directories (also shown in
the preceding directory structure):
• .platform/confighooks/prebuild
• .platform/hooks/prebuild
The 01login.sh script first calls the get-config tool to retrieve the repository credentials, and then
calls docker login to authenticate to the repository.
Notes
• All script files must have execute permission. Use chmod +x to set execute permission on
your hook files.
• Hook files can be either binary files or script files starting with a #! line containing their
interpreter path, such as #!/bin/bash.
• For more information, see the section called “Platform hooks” (p. 33) in Extending
Elastic Beanstalk Linux platforms.
After Elastic Beanstalk can authenticate with the online registry that hosts the private repository, your
images can be deployed and pulled.
1. Generate an authentication file with the docker login command. For repositories on Docker Hub, run
docker login:
$ docker login
Note
If your Elastic Beanstalk environment uses the Amazon Linux AMI Docker platform version
(precedes Amazon Linux 2), read the relevant information in the section called “Docker
configuration on Amazon Linux AMI (preceding Amazon Linux 2)” (p. 96).
For more information about the authentication file, see Store images on Docker Hub and docker
login on the Docker website.
60
AWS Elastic Beanstalk Developer Guide
Docker platform branch
2. Upload a copy of the authentication file that is named .dockercfg to a secure Amazon S3 bucket.
• The Amazon S3 bucket must be hosted in the same AWS Region as the environment that is using
it. Elastic Beanstalk cannot download files from an Amazon S3 bucket hosted in other Regions.
• Grant permissions for the s3:GetObject operation to the IAM role in the instance profile. For
more information, see Managing Elastic Beanstalk instance profiles (p. 855).
3. Include the Amazon S3 bucket information in the Authentication parameter in your
Dockerrun.aws.json v3 file.
{
"AWSEBDockerrunVersion": "3",
"Authentication": {
"bucket": "DOC-EXAMPLE-BUCKET",
"key": "mydockercfg"
}
}
Note
The AWSEBDockerrunVersion parameter indicates the version of the
Dockerrun.aws.json file.
• The Docker Amazon Linux 2 platform uses the Dockerrun.aws.json v3 file for
environments that use Docker Compose. It uses the Dockerrun.aws.json v1 file for
environments that don't use Docker Compose.
• The Multicontainer Docker Amazon Linux AMI platform uses the Dockerrun.aws.json
v2 file.
After Elastic Beanstalk can authenticate with the online registry that hosts the private repository, your
images can be deployed and pulled.
The following snippet is an example of the Dockerfile. If you follow the instructions in Using the
Docker platform branch (p. 50), you can upload this Dockerfile as written. Elastic Beanstalk runs
the game 2048 when you use this Dockerfile.
For more information about instructions you can include in the Dockerfile, see Dockerfile reference on
the Docker website.
FROM ubuntu:12.04
EXPOSE 80
61
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Note
You can run multi-stage builds from a single Dockerfile to produce smaller-sized images with
a significant reduction in complexity. For more information, see Use multi-stage builds on the
Docker documentation website.
Any web application that you deploy to Elastic Beanstalk in a Docker environment must include either
a Dockerfile or a Dockerrun.aws.json file. You can deploy your web application from a Docker
container to Elastic Beanstalk by doing one of the following actions:
• Create a Dockerfile to have Elastic Beanstalk build and run a custom image.
• Create a Dockerrun.aws.json file to deploy a Docker image from a hosted repository to Elastic
Beanstalk.
• Create a .zip file containing your application files, any application file dependencies, the
Dockerfile, and the Dockerrun.aws.json file. If you use the EB CLI to deploy your application, it
creates a .zip file for you.
If you use only a Dockerfile or only a Dockerrun.aws.json file to deploy your application, you
don't need to create a .zip file.
This topic is a syntax reference. For detailed procedures on launching Docker environments, see Using the
Docker platform branch (p. 50).
Dockerrun.aws.json v1
A Dockerrun.aws.json file describes how to deploy a remote Docker image as an Elastic Beanstalk
application. This JSON file is specific to Elastic Beanstalk. If your application runs on an image that is
available in a hosted repository, you can specify the image in a Dockerrun.aws.json v1 file and omit
the Dockerfile.
Valid keys and values for the Dockerrun.aws.json v1 file include the following operations:
AWSEBDockerrunVersion
(Required) Specifies the version number as the value 1 for single container Docker environments.
Authentication
(Required only for private repositories) Specifies the Amazon S3 object storing the .dockercfg file.
Specifies the Docker base image on an existing Docker repository from which you're building a
Docker container. Specify the value of the Name key in the format <organization>/<image
name> for images on Docker Hub, or <site>/<organization name>/<image name> for other
sites.
When you specify an image in the Dockerrun.aws.json file, each instance in your Elastic
Beanstalk environment runs docker pull to run the image. Optionally, include the Update key.
62
AWS Elastic Beanstalk Developer Guide
Docker platform branch
The default value is true and instructs Elastic Beanstalk to check the repository, pull any updates to
the image, and overwrite any cached images.
When using a Dockerfile, do not specify the Image key in the Dockerrun.aws.json file. Elastic
Beanstalk always builds and uses the image described in the Dockerfile when one is present.
Ports
(Required when you specify the Image key) Lists the ports to expose on the Docker container.
Elastic Beanstalk uses the ContainerPort value to connect the Docker container to the reverse proxy
running on the host.
You can specify multiple container ports, but Elastic Beanstalk uses only the first port. It uses
this port to connect your container to the host's reverse proxy and route requests from the public
internet. If you're using a Dockerfile, the first ContainerPort value should match the first entry in
the Dockerfile's EXPOSE list.
Optionally, you can specify a list of ports in HostPort. HostPort entries specify the host ports
that ContainerPort values are mapped to. If you don't specify a HostPort value, it defaults to the
ContainerPort value.
{
"Image": {
"Name": "image-name"
},
"Ports": [
{
"ContainerPort": 8080,
"HostPort": 8000
}
]
}
Volumes
Map volumes from an EC2 instance to your Docker container. Specify one or more arrays of volumes
to map.
{
"Volumes": [
{
"HostDirectory": "/path/inside/host",
"ContainerDirectory": "/path/inside/container"
}
]
...
Logging
Specify the directory inside the container to which your application writes logs. Elastic Beanstalk
uploads any logs in this directory to Amazon S3 when you request tail or bundle logs. If you rotate
logs to a folder named rotated within this directory, you can also configure Elastic Beanstalk to
upload rotated logs to Amazon S3 for permanent storage. For more information, see Viewing logs
from Amazon EC2 instances in your Elastic Beanstalk environment (p. 820).
Command
Specify a command to run in the container. If you specify an Entrypoint, then Command is added as
an argument to Entrypoint. For more information, see CMD in the Docker documentation.
63
AWS Elastic Beanstalk Developer Guide
Docker platform branch
Entrypoint
Specify a default command to run when the container starts. For more information, see
ENTRYPOINT in the Docker documentation.
The following snippet is an example that illustrates the syntax of the Dockerrun.aws.json file for a
single container.
{
"AWSEBDockerrunVersion": "1",
"Image": {
"Name": "janedoe/image",
"Update": "true"
},
"Ports": [
{
"ContainerPort": "1234"
}
],
"Volumes": [
{
"HostDirectory": "/var/app/mydb",
"ContainerDirectory": "/etc/mysql"
}
],
"Logging": "/var/log/nginx",
"Entrypoint": "/app/bin/myapp",
"Command": "--argument"
}
You can provide Elastic Beanstalk with only the Dockerrun.aws.json file, or with a .zip archive
containing both the Dockerrun.aws.json and Dockerfile files. When you provide both files, the
Dockerfile describes the Docker image and the Dockerrun.aws.json file provides additional
information for deployment, as described later in this section.
Note
The two files must be at the root, or top level, of the .zip archive. Don't build the archive from
a directory containing the files. Instead, navigate into that directory and build the archive there.
When you provide both files, don't specify an image in the Dockerrun.aws.json file. Elastic
Beanstalk builds and uses the image described in the Dockerfile and ignores the image
specified in the Dockerrun.aws.json file.
For information about generating and uploading the authentication file, see Using images from a private
repository (p. 95).
The following example shows the use of an authentication file named mydockercfg in a bucket named
DOC-EXAMPLE-BUCKET to use a private image in a third-party registry.
{
"AWSEBDockerrunVersion": "1",
"Authentication": {
"Bucket": "DOC-EXAMPLE-BUCKET",
64
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
"Key": "mydockercfg"
},
"Image": {
"Name": "quay.io/johndoe/private-image",
"Update": "true"
},
"Ports": [
{
"ContainerPort": "1234"
}
],
"Volumes": [
{
"HostDirectory": "/var/app/mydb",
"ContainerDirectory": "/etc/mysql"
}
],
"Logging": "/var/log/nginx"
}
• The platform branch Multi-container Docker running on 64bit Amazon Linux, (the version
that precedes Amazon Linux 2), is scheduled for retirement on June 30, 2022. For more
information about platform support policy and retired platform branches, see the Platform
support policy (p. 27).
• For more information about migrating your applications running on the Multi-container
Docker Amazon Linux platform branch to the Amazon ECS running on Amazon Linux 2
platform branch, see ??? (p. 79).
This topic covers both the Amazon ECS on Amazon Linux 2 platform branch and the platform branch
it replaces, Multi-container Docker on AL1 (also ECS managed). Unless otherwise noted, all of the
information in this topic applies to both platform branches.
Topics
• ECS managed Docker platform (p. 65)
• Dockerrun.aws.json file (p. 66)
• Docker images (p. 67)
• Container instance role (p. 67)
• Amazon ECS resources created by Elastic Beanstalk (p. 68)
• Using multiple Elastic Load Balancing listeners (p. 68)
• Failed container deployments (p. 69)
• ECS managed Docker configuration (p. 69)
• ECS managed Docker environments with the Elastic Beanstalk console (p. 73)
• Migrating Multi-container Docker running on Amazon Linux to ECS on Amazon Linux 2 (p. 79)
• (Legacy) Migrating to the Docker running on Amazon Linux 2 platform branch from Multi-container
Docker running on Amazon Linux (p. 81)
65
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
instances running Docker containers. Elastic Beanstalk takes care of Amazon ECS tasks including cluster
creation, task definition and execution. Each of the instances in the environment run the same set of
containers, which are defined in a Dockerrun.aws.json v2 file. In order to get the most out of Docker,
Elastic Beanstalk lets you create an environment where your Amazon EC2 instances run multiple Docker
containers side by side.
The following diagram shows an example Elastic Beanstalk environment configured with three Docker
containers running on each Amazon EC2 instance in an Auto Scaling group:
Note
Elastic Beanstalk offers extensibility features for all of its platforms that you can use to
customize the deployment and running of your applications. For the ECS running on Amazon
Linux 2 platform branch, the instance deployment workflow implementation of these features
varies from the other platforms. For more information, see Instance deployment workflow for
ECS running on Amazon Linux 2 (p. 40).
Dockerrun.aws.json file
Container instances—Amazon EC2 instances running ECS managed Docker in an Elastic Beanstalk
environment—require a configuration file named Dockerrun.aws.json. This file is specific to Elastic
Beanstalk and can be used alone or combined with source code and content in a source bundle (p. 385)
to create an environment on a Docker platform.
Note
Version 1 of the Dockerrun.aws.json format is used to launch a single Docker container
to an Elastic Beanstalk environment running on Amazon Linux AMI, (the version that
precedes Amazon Linux 2). The environment is based on the Docker running on 64bit Amazon
Linux platform branch, which will be retired on June 30, 2022. To learn more about the
Dockerrun.aws.json v1 format, see Docker platform Configuration - without Docker
Compose (p. 62).
The Version 2 format of the Dockerrun.aws.json adds support for multiple containers per
Amazon EC2 instance and can only be used with an ECS managed Docker platform. The format
differs significantly from the previous version.
66
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
See Dockerrun.aws.json v2 (p. 70) for details on the updated format and an example file.
Docker images
The ECS managed Docker platform for Elastic Beanstalk requires images to be prebuilt and stored in a
public or private online image repository.
Note
Building custom images during deployment with a Dockerfile is not supported by the ECS
managed Docker platform on Elastic Beanstalk. Build your images and deploy them to an online
repository before creating an Elastic Beanstalk environment.
• Images in official repositories on Docker Hub use a single name (for example, ubuntu or mongo).
• Images in other repositories on Docker Hub are qualified with an organization name (for example,
amazon/amazon-ecs-agent).
• Images in other online registries are qualified further by a domain name (for example, quay.io/
assemblyline/ubuntu).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ECSAccess",
"Effect": "Allow",
"Action": [
"ecs:Poll",
"ecs:StartTask",
"ecs:StopTask",
"ecs:DiscoverPollEndpoint",
"ecs:StartTelemetrySession",
"ecs:RegisterContainerInstance",
"ecs:DeregisterContainerInstance",
"ecs:DescribeContainerInstances",
"ecs:Submit*"
],
"Resource": "*"
}
]
}
If you create your own instance profile, you can attach the
AWSElasticBeanstalkMulticontainerDocker managed policy to make sure the permissions stay
up-to-date. For instructions on creating policies and roles in IAM, see Creating IAM Roles in the IAM User
Guide.
67
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
• Amazon ECS Cluster – Container instances in Amazon ECS are organized into clusters. When used with
Elastic Beanstalk, one cluster is always created for each ECS managed Docker environment.
• Amazon ECS Task Definition – Elastic Beanstalk uses the Dockerrun.aws.json v2 in your project
to generate the Amazon ECS task definition that is used to configure container instances in the
environment.
• Amazon ECS Task – Elastic Beanstalk communicates with Amazon ECS to run a task on every instance
in the environment to coordinate container deployment. In a scalable environment, Elastic Beanstalk
initiates a new task whenever an instance is added to the cluster. In rare cases you may have to
increase the amount of space reserved for containers and images. Learn more in the Configuring
Docker environments (p. 90) section.
• Amazon ECS Container Agent – The agent runs in a Docker container on the instances in your
environment. The agent polls the Amazon ECS service and waits for a task to run.
• Amazon ECS Data Volumes – Elastic Beanstalk inserts volume definitions (in addition to the volumes
that you define in Dockerrun.aws.json v2 into the task definition to facilitate log collection.
Elastic Beanstalk creates log volumes on the container instance, one for each container, at /var/log/
containers/containername. These volumes are named awseb-logs-containername and are
provided for containers to mount. See Container definition format (p. 72) for details on how to
mount them.
Create a .ebextensions folder in your source bundle and add a file with a .config file extension.
The following example shows a configuration file that creates an Elastic Load Balancing listener on port
8080.
.ebextensions/elb-listener.config
option_settings:
aws:elb:listener:8080:
ListenerProtocol: HTTP
InstanceProtocol: HTTP
InstancePort: 8080
If your environment is running in a custom Amazon Virtual Private Cloud (Amazon VPC) that you created,
Elastic Beanstalk takes care of the rest. In a default VPC, you need to configure your instance's security
group to allow ingress from the load balancer. Add a second configuration file that adds an ingress rule
to the security group:
.ebextensions/elb-ingress.config
Resources:
port8080SecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
68
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
ToPort: 8080
FromPort: 8080
SourceSecurityGroupName: { "Fn::GetAtt": ["AWSEBLoadBalancer",
"SourceSecurityGroup.GroupName"] }
For more information on the configuration file format, see Adding and customizing Elastic Beanstalk
environment resources (p. 703) and Option settings (p. 684).
In addition to adding a listener to the Elastic Load Balancing configuration and opening a port in the
security group, you need to map the port on the host instance to a port on the Docker container in the
containerDefinitions section of the Dockerrun.aws.json v2 file. The following excerpt shows an
example:
"portMappings": [
{
"hostPort": 8080,
"containerPort": 8080
}
]
See Dockerrun.aws.json v2 (p. 70) for details on the Dockerrun.aws.json v2 file format.
Dockerrun.aws.json describes the containers to deploy to each container instance (Amazon EC2
instance that hosts Docker containers) in the environment as well as the data volumes to create on the
host instance for the containers to mount.
A Dockerrun.aws.json file can be used on its own or zipped up with additional source code in a single
archive. Source code that is archived with a Dockerrun.aws.json is deployed to Amazon EC2 container
instances and accessible in the /var/app/current/ directory. Use the volumes section of the config
to provide file volumes for the Docker containers running on the host instance. Use the mountPoints
section of the embedded container definitions to map these volumes to mount points that applications
on the Docker containers can use.
Topics
• Dockerrun.aws.json v2 (p. 70)
• Using images from a private repository (p. 71)
• Container definition format (p. 72)
69
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
Dockerrun.aws.json v2
The Dockerrun.aws.json file includes three sections:
AWSEBDockerrunVersion
Specifies the version number as the value 2 for ECS managed Docker environments.
containerDefinitions
Creates volumes from folders in the Amazon EC2 container instance, or from your source bundle
(deployed to /var/app/current). Mount these volumes to paths within your Docker containers
using mountPoints in the container definition (p. 72).
Note
Elastic Beanstalk configures additional volumes for logs, one for each container. These
should be mounted by your Docker containers in order to write logs to the host instance.
See Container definition format (p. 72) for details.
"volumes": [
{
"name": "volumename",
"host": {
"sourcePath": "/path/on/host/instance"
}
}
],
authentication
(optional) The location in Amazon S3 of a .dockercfg file that contains authentication data for a
private repository. Uses the following format:
"authentication": {
"bucket": "DOC-EXAMPLE-BUCKET",
"key": "mydockercfg"
},
See Using images from a private repository (p. 71) for details.
The following snippet is an example that illustrates the syntax of the Dockerrun.aws.json file for an
instance with two containers.
{
"AWSEBDockerrunVersion": 2,
"volumes": [
{
"name": "php-app",
"host": {
"sourcePath": "/var/app/current/php-app"
}
},
{
"name": "nginx-proxy-conf",
"host": {
"sourcePath": "/var/app/current/proxy/conf.d"
70
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
}
}
],
"containerDefinitions": [
{
"name": "php-app",
"image": "php:fpm",
"environment": [
{
"name": "Container",
"value": "PHP"
}
],
"essential": true,
"memory": 128,
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/html",
"readOnly": true
}
]
},
{
"name": "nginx-proxy",
"image": "nginx",
"essential": true,
"memory": 128,
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
],
"links": [
"php-app"
],
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/html",
"readOnly": true
},
{
"sourceVolume": "nginx-proxy-conf",
"containerPath": "/etc/nginx/conf.d",
"readOnly": true
},
{
"sourceVolume": "awseb-logs-nginx-proxy",
"containerPath": "/var/log/nginx"
}
]
}
]
}
71
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
For information about generating and uploading the authentication file, see Using images from a private
repository (p. 95).
The following examples show a subset of parameters that are commonly used. More optional parameters
are available. For more information on the task definition format and a full list of task definition
parameters, see Amazon ECS Task Definitions in the Amazon Elastic Container Service Developer Guide.
A Dockerrun.aws.json file contains an array of one or more container definition objects with the
following fields:
name
The name of the container. See Standard Container Definition Parameters for information about the
maximum length and allowed characters.
image
The name of a Docker image in an online Docker repository from which you're building a Docker
container. Note these conventions:
• Images in official repositories on Docker Hub use a single name (for example, ubuntu or mongo).
• Images in other repositories on Docker Hub are qualified with an organization name (for example,
amazon/amazon-ecs-agent.
• Images in other online repositories are qualified further by a domain name (for example,
quay.io/assemblyline/ubuntu).
environment
For example, the following entry defines an environment variable with the name Container and
the value PHP:
"environment": [
{
"name": "Container",
"value": "PHP"
}
],
essential
True if the task should stop if the container fails. Nonessential containers can finish or crash without
affecting the rest of the containers on the instance.
memory
Amount of memory on the container instance to reserve for the container. Specify a non-zero
integer for one or both of the memory or memoryReservation parameters in container definitions.
memoryReservation
The soft limit (in MiB) of memory to reserve for the container. Specify a non-zero integer for one or
both of the memory or memoryReservation parameters in container definitions.
mountPoints
Volumes from the Amazon EC2 container instance to mount, and the location on the Docker
container file system at which to mount them. When you mount volumes that contain application
72
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
content, your container can read the data you upload in your source bundle. When you mount log
volumes for writing log data, Elastic Beanstalk can gather log data from these volumes.
Elastic Beanstalk creates log volumes on the container instance, one for each Docker
container, at /var/log/containers/containername. These volumes are named awseb-
logs-containername and should be mounted to the location within the container file structure
where logs are written.
For example, the following mount point maps the nginx log location in the container to the Elastic
Beanstalk–generated volume for the nginx-proxy container.
{
"sourceVolume": "awseb-logs-nginx-proxy",
"containerPath": "/var/log/nginx"
}
portMappings
List of containers to link to. Linked containers can discover each other and communicate securely.
volumesFrom
Mount all of the volumes from a different container. For example, to mount volumes from a
container named web:
"volumesFrom": [
{
"sourceContainer": "web"
}
],
You can launch a cluster of multi-container instances in a single-instance or scalable Elastic Beanstalk
environment using the Elastic Beanstalk console. This tutorial details container configuration and source
code preparation for an environment that uses two containers.
The containers, a PHP application and an nginx proxy, run side by side on each of the Amazon Elastic
Compute Cloud (Amazon EC2) instances in an Elastic Beanstalk environment. After creating the
environment and verifying that the applications are running, you'll connect to a container instance to see
how it all fits together.
Sections
73
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
The file that Elastic Beanstalk uses to configure the containers on an Amazon EC2 instance is a JSON-
formatted text file named Dockerrun.aws.json. Create a text file with this name at the root of your
application and add the following text:
{
"AWSEBDockerrunVersion": 2,
"volumes": [
{
"name": "php-app",
"host": {
"sourcePath": "/var/app/current/php-app"
}
},
{
"name": "nginx-proxy-conf",
"host": {
"sourcePath": "/var/app/current/proxy/conf.d"
}
}
],
"containerDefinitions": [
{
"name": "php-app",
"image": "php:fpm",
"essential": true,
"memory": 128,
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/html",
"readOnly": true
}
]
},
{
"name": "nginx-proxy",
"image": "nginx",
"essential": true,
"memory": 128,
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
74
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
],
"links": [
"php-app"
],
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/html",
"readOnly": true
},
{
"sourceVolume": "nginx-proxy-conf",
"containerPath": "/etc/nginx/conf.d",
"readOnly": true
},
{
"sourceVolume": "awseb-logs-nginx-proxy",
"containerPath": "/var/log/nginx"
}
]
}
]
}
This example configuration defines two containers, a PHP web site with an nginx proxy in front of it.
These two containers will run side by side in Docker containers on each instance in your Elastic Beanstalk
environment, accessing shared content (the content of the website) from volumes on the host instance,
which are also defined in this file. The containers themselves are created from images hosted in official
repositories on Docker Hub. The resulting environment looks like the following:
The volumes defined in the configuration correspond to the content that you will create next and upload
as part of your application source bundle. The containers access content on the host by mounting
volumes in the mountPoints section of the container definitions.
For more information on the format of Dockerrun.aws.json and its parameters, see Container
definition format (p. 72).
75
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
Add content
Next you will add some content for your PHP site to display to visitors, and a configuration file for the
nginx proxy.
php-app/index.php
<h1>Hello World!!!</h1>
<h3>PHP Version <pre><?= phpversion()?></pre></h3>
php-app/static.html
<h1>Hello World!</h1>
<h3>This is a static HTML page.</h3>
proxy/conf.d/default.conf
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php;
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_pass php-app:9000;
fastcgi_index index.php;
}
}
### Dockerrun.aws.json
### php-app
# ### index.php
# ### static.html
### proxy
### conf.d
### default.conf
This is all you need to create the Elastic Beanstalk environment. Create a .zip archive of the above files
and folders (not including the top-level project folder). To create the archive in Windows explorer, select
the contents of the project folder, right-click, select Send To, and then click Compressed (zipped) Folder
Note
For information on the required file structure and instructions for creating archives in other
environments, see Create an application source bundle (p. 385)
76
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
Next, upload the source bundle to Elastic Beanstalk and create your environment. For Platform, select
Docker. For Platform branch, select ECS running on 64bit Amazon Linux 2.
The Elastic Beanstalk console redirects you to the management dashboard for your new environment.
This screen shows the health status of the environment and events output by the Elastic Beanstalk
service. When the status is Green, click the URL next to the environment name to see your new website.
The easiest way to connect to an instance in your environment is by using the EB CLI. To use it, install
the EB CLI (p. 957), if you haven't done so already. You'll also need to configure your environment with
an Amazon EC2 SSH key pair. Use either the console's security configuration page (p. 585) or the EB
CLI eb init (p. 1017) command to do that. To connect to an environment instance, use the EB CLI eb
ssh (p. 1036) command.
Now that your connected to an Amazon EC2 instance hosting your docker containers, you can see how
things are set up. Run ls on /var/app/current:
This directory contains the files from the source bundle that you uploaded to Elastic Beanstalk during
environment creation.
This is where logs are created on the container instance and collected by Elastic Beanstalk. Elastic
Beanstalk creates a volume in this directory for each container, which you mount to the container
location where logs are written.
You can also take a look at Docker to see the running containers with docker ps.
77
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
This shows the two running containers that you deployed, as well as the Amazon ECS container agent
that coordinated the deployment.
Check the status of the container agent with an HTTP get request to http://localhost:51678/v1/
metadata:
This structure shows the name of the Amazon ECS cluster, and the ARN (Amazon Resource Name) of the
cluster instance (the Amazon EC2 instance that you are connected to).
"DockerId":"dcc3b3c8522cb9510b7359689163814c0f1453b36b237204a3fd7a0b445d2ea6",
"DockerName":"ecs-awseb-Tutorials-env-dc2aywfjwg-1-php-app-
b8d38ae288b7b09e8101",
"Name":"php-app",
"Volumes":[
{
"Source":"/var/app/current/php-app",
"Destination":"/var/www/html"
}
]
},
{
"DockerId":"4ba868dbb7f3fb3328b8afeb2cb6cf03e3cb1cdd5b109e470f767d50b2c3e303",
"DockerName":"ecs-awseb-Tutorials-env-dc2aywfjwg-1-nginx-proxy-
acca84ef87c4aca15400",
78
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
"Name":"nginx-proxy",
"Ports":[
{
"ContainerPort":80,
"Protocol":"tcp",
"HostPort":80
},
{
"ContainerPort":80,
"Protocol":"tcp",
"HostPort":80
}
],
"Volumes":[
{
"Source":"/var/app/current/php-app",
"Destination":"/var/www/html"
},
{
"Source":"/var/log/containers/nginx-proxy",
"Destination":"/var/log/nginx"
},
{
"Source":"/var/app/current/proxy/conf.d",
"Destination":"/etc/nginx/conf.d"
}
]
}
]
}
]
}
This structure describes the task that is run to deploy the two docker containers from this tutorial's
example project. The following information is displayed:
• KnownStatus – The RUNNING status indicates that the containers are still active.
• Family – The name of the task definition that Elastic Beanstalk created from Dockerrun.aws.json.
• Version – The version of the task definition. This is incremented each time the task definition file is
updated.
• Containers – Information about the containers running on the instance.
Even more information is available from the Amazon ECS service itself, which you can call using the AWS
Command Line Interface. For instructions on using the AWS CLI with Amazon ECS, and information about
Amazon ECS in general, see the Amazon ECS User Guide.
The Multi-container Docker running on 64bit Amazon Linux platform branch is scheduled for retirement
on June 30, 2022. This topic guides you in the migration of your applications from this retiring branch to
the current platform branch, ECS Running on 64bit Amazon Linux 2.
79
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
Like the previous Multi-container Docker AL1 branch, the newer ECS AL2 platform branch uses Amazon
ECS to coordinate deployment of multiple Docker containers to an Amazon ECS cluster in an Elastic
Beanstalk environment. The new ECS AL2 platform branch supports all of the features in the previous
Multi-container Docker AL1 platform branch. Also, the same Dockerrun.aws.json v2 file is supported.
Sections
• Migrate with the Elastic Beanstalk console (p. 80)
• Migrate with the AWS CLI (p. 80)
1. Using the application source that's already deployed to the old environment, create an
application source bundle. You can use the same application source bundle and the same
Dockerrun.aws.json v2 file.
2. Create a new environment using the ECS Running on 64bit Amazon Linux 2 platform branch. Use
the source bundle from the prior step for Application code. For more detailed steps, see Deploy to
Elastic Beanstalk (p. 76) in the ECS managed Docker tutorial earlier in this chapter.
Use the following syntax to migrate your environment to the new platform branch.
The following is an example of the command to migrate environment beta-101 to version 3.0.0 of the
ECS Amazon Linux 2 platform branch in the us-east-1 region.
The solution-stack-name parameter provides the platform branch and its version. Use the most
recent platform branch version by specifying the proper solution stack name. The version of every
platform branch is included in the solution stack name, as shown in the above example. For a list of
the most current solution stacks for the Docker platform, see Supported platforms in the AWS Elastic
Beanstalk Platforms guide.
Note
The list-available-solution-stacks command provides a list of the platform versions available for
your account in an AWS Region.
80
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
To learn more about the AWS CLI, see the AWS Command Line Interface User Guide. For more information
about AWS CLI commands for Elastic Beanstalk, see the AWS CLI Command Reference for Elastic
Beanstalk.
We now recommend that customers with environments based on the Multi-container Docker running
on 64bit Amazon Linux platform branch migrate to the ECS Running on 64bit Amazon Linux 2 platform
branch. Unlike the alternate migration path, this approach continues to use Amazon ECS to coordinate
container deployments to ECS managed Docker environments. This aspect allows a more straightforward
approach. No changes to the source code are required, and the same Dockerrun.aws.json v2 is
supported. For more information, see Migrating Multi-container Docker running on Amazon Linux to ECS
on Amazon Linux 2 (p. 79).
Legacy Migration from Multi-container Docker on Amazon Linux to the Docker Amazon Linux 2
platform branch
You can migrate your applications running on the Multi-container Docker platform on Amazon Linux
AMI (p. 65) to the Amazon Linux 2 Docker platform. The Multi-container Docker platform on Amazon
Linux AMI requires that you specify prebuilt application images to run as containers. After migrating,
you will no longer have this limitation, because the Amazon Linux 2 Docker platform also allows Elastic
Beanstalk to build your container images during deployment. Your applications will continue to run in
multi-container environments with the added benefits from the Docker Compose tool.
Docker Compose is tool for defining and running multi-container Docker applications. To learn more
about Docker Compose and how to install it, see the Docker sites Overview of Docker Compose and
Install Docker Compose.
docker-compose.yml Dockerrun.aws.json v2
version: '2.4' {
81
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
docker-compose.yml Dockerrun.aws.json v2
services: "AWSEBDockerrunVersion": 2,
php-app: "volumes": [
image: "php:fpm" {
volumes: "name": "php-app",
- "./php-app:/var/www/html:ro" "host": {
- "${EB_LOG_BASE_DIR}/php-app:/var/ "sourcePath": "/var/app/current/
log/sample-app" php-app"
mem_limit: 128m }
environment: },
Container: PHP {
nginx-proxy: "name": "nginx-proxy-conf",
image: "nginx" "host": {
ports: "sourcePath": "/var/app/current/
- "80:80" proxy/conf.d"
volumes: }
- "./php-app:/var/www/html:ro" }
- "./proxy/conf.d:/etc/nginx/ ],
conf.d:ro" "containerDefinitions": [
- "${EB_LOG_BASE_DIR}/nginx-proxy:/ {
var/log/nginx" "name": "php-app",
mem_limit: 128m "image": "php:fpm",
links: "environment": [
- php-app {
"name": "Container",
"value": "PHP"
}
],
"essential": true,
"memory": 128,
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/
html",
"readOnly": true
}
]
},
{
"name": "nginx-proxy",
"image": "nginx",
"essential": true,
"memory": 128,
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
],
"links": [
"php-app"
],
"mountPoints": [
{
"sourceVolume": "php-app",
"containerPath": "/var/www/
html",
"readOnly": true
},
{
"sourceVolume": "nginx-proxy-
conf",
82
AWS Elastic Beanstalk Developer Guide
ECS managed platform branch
docker-compose.yml Dockerrun.aws.json v2
"containerPath": "/etc/nginx/
conf.d",
"readOnly": true
},
{
"sourceVolume": "awseb-logs-
nginx-proxy",
"containerPath": "/var/log/
nginx"
}
]
}
]
}
The Docker Amazon Linux 2 platform and Multi-container Docker Amazon Linux AMI platform
implement environment properties differently. These two platforms also have different log directories
that Elastic Beanstalk creates for each of their containers. After you migrate from the Amazon Linux AMI
Multi-container Docker platform, you will need to be aware of these different implementations for your
new Amazon Linux 2 Docker platform environment.
Environment In order for your containers to access Elastic Beanstalk can directly pass
properties environment properties you must add environment properties to the container.
a reference to the .env file in the Your code running in the container can
docker-compose.yml file. Elastic access these properties as environment
Beanstalk generates the .env file, listing variables without any additional
each of the properties as environment configuration.
variables. For more information see
Referencing environment variables in
containers (p. 91).
Log For each container Elastic Beanstalk For each container, Elastic Beanstalk
directories creates a log directory called /var/log/ creates a log directory called /var/log/
eb-docker/containers/<service containers/<containername>. For
name> (or ${EB_LOG_BASE_DIR}/ more information see mountPoints field
<service name>). For more information in Container definition format (p. 72).
see Docker container customized logging
(Docker Compose) (p. 92).
Migration Steps
1. Create the docker-compose.yml file for your application, based on its existing
Dockerrun.aws.json v2 file. For more information see the above section The docker-
compose.yml file (p. 81).
2. In your application project folder's root directory, replace the Dockerrun.aws.json v2 file with
the docker-compose.yml you just created.
83
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
~/myApplication
|-- docker-compose.yml
|-- .ebextensions
|-- php-app
|-- proxy
3. Use the eb init command to configure your local directory for deployment to Elastic Beanstalk.
4. Use the eb create command to create an environment and deploy your Docker image.
5. If your app is a web application, after your environment launches, use the eb open command to view
it in a web browser.
6. You can display the status of your newly created environment using the eb status command.
To migrate your GlassFish application to a supported Amazon Linux 2 based supported platform, use
the generic Amazon Linux 2 based Docker platform and deploy GlassFish and your application code to
an Amazon Linux 2 Docker image. For more information, see the followiong topic, the section called
“Tutorial - GlassFish on Docker: path to Amazon Linux 2” (p. 87).
84
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
~$ mkdir eb-preconf-example
~$ cd eb-preconf-example
~$ wget https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/samples/docker-
glassfish-v1.zip
~$ unzip docker-glassfish-v1.zip
~$ rm docker-glassfish-v1.zip
1. Add a Dockerfile to your application’s root folder. In the file, specify the AWS Elastic Beanstalk
Docker base image to be used to run your local preconfigured Docker container. You'll later deploy
your application to an Elastic Beanstalk Preconfigured Docker GlassFish platform version. Choose
the Docker base image that this platform version uses. To find out the current Docker image of
the platform version, see the Preconfigured Docker section of the AWS Elastic Beanstalk Supported
Platforms page in the AWS Elastic Beanstalk Platforms guide.
Example ~/Eb-preconf-example/Dockerfile
For more information about using a Dockerfile, see Docker configuration (p. 58).
2. Build the Docker image.
4. To view the example application, type the following URL into your web browser.
http://localhost:3000
85
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
After testing your application, you are ready to deploy it to Elastic Beanstalk.
1. In your application's root folder, rename the Dockerfile to Dockerfile.local. This step is
required for Elastic Beanstalk to use the Dockerfile that contains the correct instructions for
Elastic Beanstalk to build a customized Docker image on each Amazon EC2 instance in your Elastic
Beanstalk environment.
Note
You do not need to perform this step if your Dockerfile includes instructions that modify
the platform version's base Docker image. You do not need to use a Dockerfile at all if
your Dockerfile includes only a FROM line to specify the base image from which to build
the container. In that situation, the Dockerfile is redundant.
2. Create an application source bundle.
86
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
The tutorial walks you through using the AWS Elastic Beanstalk Docker platform to deploy an application
based on the Java EE GlassFish application server to an Elastic Beanstalk environment.
• Simple – Provide your GlassFish application source code and let Elastic Beanstalk build and run a
Docker image as part of provisioning your environment. This is easy to set up, at a cost of increased
instance provisioning time.
• Advanced – Build a custom Docker image containing your application code and dependencies, and
provide it to Elastic Beanstalk to use in your environment. This approach is slightly more involved, and
decreases the provisioning time of instances in your environment.
Prerequisites
This tutorial assumes that you have some knowledge of basic Elastic Beanstalk operations, the Elastic
Beanstalk command line interface (EB CLI), and Docker. If you haven't already, follow the instructions
in Getting started using Elastic Beanstalk (p. 3) to launch your first Elastic Beanstalk environment. This
tutorial uses the EB CLI (p. 956), but you can also create environments and upload applications by using
the Elastic Beanstalk console.
To follow this tutorial, you will also need the following Docker components:
• A working local installation of Docker. For more information, see Get Docker on the Docker
documentation website.
• Access to Docker Hub. You will need to create a Docker ID to access the Docker Hub. For more
information, see Share the application on the Docker documentation website.
To learn more about configuring Docker environments on Elastic Beanstalk platforms, see Docker
configuration (p. 58) in this same chapter.
An issue with this approach is that Elastic Beanstalk builds the Docker image locally whenever it creates
an instance for your environment. The image build increases instance provisioning time. This impact isn't
limited to initial environment creation—it happens during scale-out actions too.
1. Download the example docker-glassfish-al2-v1.zip, and then expand the .zip file into a
directory in your development environment.
~$ curl https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/samples/docker-
glassfish-al2-v1.zip --output docker-glassfish-al2-v1.zip
~$ mkdir glassfish-example
87
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
~$ cd glassfish-example
~/glassfish-example$ unzip ../docker-glassfish-al2-v1.zip
~/glassfish-example
|-- Dockerfile
|-- Dockerrun.aws.json
|-- glassfish-start.sh
|-- index.jsp
|-- META-INF
| |-- LICENSE.txt
| |-- MANIFEST.MF
| `-- NOTICE.txt
|-- robots.txt
`-- WEB-INF
`-- web.xml
The following files are key to building and running a Docker container in your environment:
• Dockerfile – Provides instructions that Docker uses to build an image with your application and
required dependencies.
• glassfish-start.sh – A shell script that the Docker image runs to start your application.
• Dockerrun.aws.json – Provides a logging key, to include the GlassFish application server log in
log file requests (p. 820). If you aren't interested in GlassFish logs, you can omit this file.
2. Configure your local directory for deployment to Elastic Beanstalk.
3. (Optional) Use the eb local run command to build and run your container locally.
Note
To learn more about the eb local command, see the section called “eb local” (p. 1021). The
command isn't supported on Windows. Alternatively, you can build and run your container
with the docker build and docker run commands. For more information, see the Docker
documentation.
4. (Optional) While your container is running, use the eb local open command to view your application
in a web browser. Alternatively, open http://localhost:8080/ in a web browser.
5. Use the eb create command to create an environment and deploy your application.
6. After your environment launches, use the eb open command to view it in a web browser.
~/glassfish-example$ eb open
When you're done working with the example, terminate the environment and delete related resources.
88
AWS Elastic Beanstalk Developer Guide
Preconfigured containers
When you launch an environment and provide your Docker image, instances in your environment
download and use this image directly and don't need to build a Docker image. Therefore, instance
provisioning time is decreased.
Notes
Note
Before pushing your image, you might need to run docker login. You will be prompted for
your Docker Hub credentials if you run the command without parameters.
3. Create an additional directory.
~$ mkdir glassfish-prebuilt
~$ cd glassfish-prebuilt
Example ~/glassfish-prebuilt/Dockerrun.aws.json
{
"AWSEBDockerrunVersion": "1",
"Image": {
"Name": "docker-username/beanstalk-glassfish-example"
},
"Ports": [
{
"ContainerPort": 8080,
"HostPort": 8080
}
],
"Logging": "/usr/local/glassfish5/glassfish/domains/domain1/logs"
}
6. (Optional) Use the eb local run command to run your container locally.
89
AWS Elastic Beanstalk Developer Guide
Environment configuration
7. (Optional) While your container is running, use the eb local open command to view your application
in a web browser. Alternatively, open http://localhost:8080/ in a web browser.
8. Use the eb create command to create an environment and deploy your Docker image.
9. After your environment launches, use the eb open command to view it in a web browser.
~/glassfish-prebuilt$ eb open
When you're done working with the example, terminate the environment and delete related resources.
Sections
• Configuring software in Docker environments (p. 90)
• Referencing environment variables in containers (p. 91)
• Generating logs for enhanced health reporting (Docker Compose) (p. 92)
• Docker container customized logging (Docker Compose) (p. 92)
• Docker images (p. 93)
• Reclaiming Docker storage space (p. 95)
• Configuring managed updates for Docker environments (p. 95)
• Docker configuration namespaces (p. 96)
• Docker configuration on Amazon Linux AMI (preceding Amazon Linux 2) (p. 96)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
90
AWS Elastic Beanstalk Developer Guide
Environment configuration
For information about configuring software settings in any environment, see the section called
“Software settings” (p. 590). The following sections cover Docker specific information.
Container options
The Container options section has platform-specific options. For Docker environments, it lets you
choose whether or not your environment includes the NGINX proxy server.
If you manage your Docker environment with Docker Compose, Elastic Beanstalk assumes that you run
a proxy server as a container. Therefore it defaults to None for the Proxy server setting, and Elastic
Beanstalk does not provide an NGINX configuration.
Note
Even if you select NGINX as a proxy server, this setting is ignored in an environment with Docker
Compose. The Proxy server setting still defaults to None.
Since the NGINX web server proxy is disabled for the Docker on Amazon Linux 2 platform with Docker
Compose, you must follow the instructions for generating logs for enhanced health reporting. For more
information, see Generating logs for enhanced health reporting (Docker Compose) (p. 92).
Your application code running in a container can refer to an environment variable by name and read its
value. The source code that reads these environment variables will vary by progamming language. You
can find instructions for reading environment variable values in the programming languages that Elastic
Beanstalk managed platforms support in the respective platform topic. For a list of links to these topics,
see the section called “Software settings” (p. 590).
If you manage your Docker environment with Docker Compose, you must make some additional
configuration to retrieve the environment variables in the containers. In order for the executables
running in your container to access these enrironment variables, you must reference them in
the docker-compose.yml. For more information see Referencing environment variables in
containers (p. 91).
In order for a container to reference the environment variables you define in Elastic Beanstalk, you must
follow one or both of these configuration approaches.
91
AWS Elastic Beanstalk Developer Guide
Environment configuration
• Add the .env file generated by Elastic Beanstalk to the env_file configuration option in the
docker-compose.yml file.
• Directly define the environment variables in the docker-compose.yml file.
The following files provide an example. The sample docker-compose.yml file demonstrates both
approaches.
DEBUG_LEVEL=1
LOG_LEVEL=error
• In this docker-compose.yml file, the env_file configuration option points to the .env file, and it
also defines the environment variable DEBUG=1 directly in the docker-compose.yml file.
services:
web:
build: .
environment:
- DEBUG=1
env_file:
- .env
Notes
• If you set the same environment variable in both files, the variable defined in the docker-
compose.yml file has higher precedence than the variable defined in the .env file.
• Be careful to not leave spaces between the equal sign (=) and the value assigned to your
variable in order to prevent spaces from being added to the string.
To learn more about environment variables in Docker Compose, see Environment variables in Compose
Elastic Beanstalk assumes that you run a web server proxy as a container. As a result the NGINX web
server proxy is disabled for Docker environments running Docker Compose. You must configure your
server to write logs in the location and format that the Elastic Beanstalk health agent uses. Doing so
allows you to make full use of enhanced health reporting, even if the web server proxy is disabled.
For instructions on how to do this, see Web server log configuration (p. 807)
92
AWS Elastic Beanstalk Developer Guide
Environment configuration
Elastic Beanstalk creates log directories on the container instance, one for each service defined in the
docker-compose.yml file, at /var/log/eb-docker/containers/<service name>. If you are
using the Docker Compose feature on the Amazon Linux 2 Docker platform, you can mount these
directories to the location within the container file structure where logs are written. When you mount log
directories for writing log data, Elastic Beanstalk can gather log data from these directories.
If your applications are on a Docker platform that is not using Docker Compose, you can follow the
standard procedure desribed in Docker container customized logging (Docker Compose) (p. 92).
To configure your service's logs files to be retreivable tail files and bundle logs
services:
nginx-proxy:
image: "nginx"
volumes:
- "${EB_LOG_BASE_DIR}/nginx-proxy:/var/log/nginx"
• The var/log/nginx directory contains the logs for the nginx-proxy service in the container, and it will
be mapped to the /var/log/eb-docker/containers/nginx-proxy directory on the host.
• All of the logs in this directory are now retrievable as bundle and tail logs through Elastic Beanstalk's
request instance logs (p. 820) functionality.
Notes
Docker images
The Docker and ECS managed Docker platform branches for Elastic Beanstalk support the use of Docker
images stored in a public or private online image repository.
• Images in official repositories on Docker Hub use a single name (for example, ubuntu or mongo).
• Images in other repositories on Docker Hub are qualified with an organization name (for example,
amazon/amazon-ecs-agent).
• Images in other online repositories are qualified further by a domain name (for example,
quay.io/assemblyline/ubuntu or account-id.dkr.ecr.us-east-2.amazonaws.com/
ubuntu:trusty).
93
AWS Elastic Beanstalk Developer Guide
Environment configuration
For environments using the Docker platform only, you can also build your own image during
environment creation with a Dockerfile. See Building custom images with a Dockerfile (p. 61) for
details. The Multi-container Docker platform doesn't support this functionality.
You do, however, need to provide your instances with permission to access the images in your Amazon
ECR repository by adding permissions to your environment's instance profile. You can attach the
AmazonEC2ContainerRegistryReadOnly managed policy to the instance profile to provide read-only
access to all Amazon ECR repositories in your account, or grant access to single repository by using the
following template to create a custom policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowEbAuth",
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken"
],
"Resource": [
"*"
]
},
{
"Sid": "AllowPull",
"Effect": "Allow",
"Resource": [
"arn:aws:ecr:us-east-2:account-id:repository/repository-name"
],
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:DescribeRepositories",
"ecr:ListImages",
"ecr:BatchGetImage"
]
}
]
}
Replace the Amazon Resource Name (ARN) in the above policy with the ARN of your repository.
In your Dockerrun.aws.json file, refer to the image by URL. For the Docker platform (p. 58), the
URL goes in the Image definition:
"Image": {
"Name": "account-id.dkr.ecr.us-east-2.amazonaws.com/repository-name:latest",
"Update": "true"
},
For the Multi-container Docker platform (p. 69), use the image key in a container definition object:
"containerDefinitions": [
94
AWS Elastic Beanstalk Developer Guide
Environment configuration
{
"name": "my-image",
"image": "account-id.dkr.ecr.us-east-2.amazonaws.com/repository-name:latest",
Generate an authentication file with the docker login command. For repositories on Docker Hub, run
docker login:
$ docker login
Note
If your Elastic Beanstalk environment uses an Amazon Linux AMI Docker platform version
(preceding Amazon Linux 2), read the additional information in the section called “Docker
configuration on Amazon Linux AMI (preceding Amazon Linux 2)” (p. 96).
Upload a copy named .dockercfg of the authentication file to a secure Amazon S3 bucket. The
Amazon S3 bucket must be hosted in the same AWS Region as the environment that is using it. Elastic
Beanstalk cannot download files from an Amazon S3 bucket hosted in other Regions. Grant permissions
for the s3:GetObject operation to the IAM role in the instance profile. For details, see Managing Elastic
Beanstalk instance profiles (p. 855).
Include the Amazon S3 bucket information in the Authentication (v1) or authentication (v2)
parameter in your Dockerrun.aws.json file.
For more information about the Dockerrun.aws.json format for Docker environments, see
Docker configuration (p. 58). For multi-container environments, see ECS managed Docker
configuration (p. 69).
For more information about the authentication file, see Store images on Docker Hub and docker login
on the Docker website.
One solution is to increase the size of the application storage space, as described in the previous section.
The other option is less-performant: run fstrim on the host OS periodically, such as using cron, against
container free space to reclaim the unused container data blocks.
docker ps -q | xargs docker inspect --format='{{ .State.Pid }}' | xargs -IZ sudo fstrim /
proc/Z/root/
95
AWS Elastic Beanstalk Developer Guide
Environment configuration
In the case of Docker environments, you might want to decide if an automatic platform update should
happen across Docker versions—when the new platform version includes a new Docker version.
Elastic Beanstalk supports managed platform updates across Docker versions when updating from an
environment running a Docker platform version newer than 2.9.0. When a new platform version includes
a new version of Docker, Elastic Beanstalk increments the minor update version number. Therefore, to
allow managed platform updates across Docker versions, enable managed platform updates for both
minor and patch version updates. To prevent managed platform updates across Docker versions, enable
managed platform updates to apply patch version updates only.
For example, the following configuration file (p. 683) enables managed platform updates at 9:00 AM
UTC each Tuesday for both minor and patch version updates, thereby allowing for managed updates
across Docker versions:
Example .ebextensions/managed-platform-update.config
option_settings:
aws:elasticbeanstalk:managedactions:
ManagedActionsEnabled: true
PreferredStartTime: "Tue:09:00"
aws:elasticbeanstalk:managedactions:platformupdate:
UpdateLevel: minor
For environments running Docker platform versions 2.9.0 or earlier, Elastic Beanstalk never performs
managed platform updates if the new platform version includes a new Docker version.
The Docker platform supports options in the following namespaces, in addition to the options supported
for all Elastic Beanstalk environments (p. 632):
The following example configuration file configures a Docker environment to run no proxy server.
Example .ebextensions/docker-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: none
96
AWS Elastic Beanstalk Developer Guide
Environment configuration
With Docker version 1.7 and later, the docker login command creates the authentication file in
~/.docker/config.json in the following format.
{
"auths":{
"server":{
"auth":"key"
}
}
}
With Docker version 1.6.2 and earlier, the docker login command creates the authentication file in
~/.dockercfg in the following format.
{
"server" :
{
"auth" : "auth_token",
"email" : "email"
}
}
To convert a config.json file, remove the outer auths key, add an email key, and flatten the JSON
document to match the old format.
On Amazon Linux 2 Docker platform versions, Elastic Beanstalk uses the newer authentication file name
and format. If you're using an Amazon Linux 2 Docker platform version, you can use the authentication
file that the docker login command creates without any conversion.
If you need more storage space or increased IOPS for Docker images, you can customize
the image storage volume by using the BlockDeviceMapping configuration option in the
aws:autoscaling:launchconfiguration (p. 633) namespace.
For example, the following configuration file (p. 683) increases the storage volume's size to 100 GB
with 500 provisioned IOPS:
Example .ebextensions/blockdevice-xvdcz.config
option_settings:
aws:autoscaling:launchconfiguration:
BlockDeviceMappings: /dev/xvdcz=:100::io1:500
If you use the BlockDeviceMappings option to configure additional volumes for your application, you
should include a mapping for xvdcz to ensure that it is created. The following example configures two
volumes, the image storage volume xvdcz with default settings and an additional 24 GB application
volume named sdh:
97
AWS Elastic Beanstalk Developer Guide
Working with Go
Example .ebextensions/blockdevice-sdh.config
option_settings:
aws:autoscaling:launchconfiguration:
BlockDeviceMappings: /dev/xvdcz=:12:true:gp2,/dev/sdh=:24
Note
When you change settings in this namespace, Elastic Beanstalk replaces all instances in your
environment with instances running the new configuration. See Configuration changes (p. 452)
for details.
AWS Elastic Beanstalk for Go makes it easy to deploy, manage, and scale your Go web applications
using Amazon Web Services. Elastic Beanstalk for Go is available to anyone developing or hosting a web
application using Go. This chapter provides step-by-step instructions for deploying your web application
to Elastic Beanstalk.
After you deploy your Elastic Beanstalk application, you can continue to use the EB CLI to manage your
application and environment, or you can use the Elastic Beanstalk console, AWS CLI, or the APIs.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
Samples
98
AWS Elastic Beanstalk Developer Guide
Getting started
Download the sample application and deploy it to Elastic Beanstalk by following these steps.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose an existing application's name in the
list or create one (p. 377).
3. On the application overview page, choose Create a new environment.
4. Next, for environment tier, choose the Web server environment or Worker environment
environment tier (p. 13). You can't change an environment's tier after creation.
Note
The .NET on Windows Server platform (p. 182) doesn't support the worker environment
tier.
99
AWS Elastic Beanstalk Developer Guide
Development environment
5. For Platform, select the platform and platform branch that match the language your application
uses.
Note
Elastic Beanstalk supports multiple versions (p. 29) for most of the platforms that are
listed. By default, the console selects the recommended version for the platform and
platform branch you choose. If your application requires a different version, you can select
it here, or choose Configure more options, as described in step 7. For information about
supported platform versions, see the section called “Supported platforms” (p. 29).
6. For Application code, choose Sample application.
7. To further customize your environment, choose Configure more options. You can set the following
options only during environment creation:
• Environment name
• Domain name
• Platform version
• Processor
• VPC
• Tier
You can change the following settings after environment creation, but they require new instances or
other resources to be provisioned and can take a long time to apply:
• Instance type, root volume, key pair, and AWS Identity and Access Management (IAM) role
• Internal Amazon RDS database
• Load balancer
For details on all available settings, see The create new environment wizard (p. 409).
8. Choose Create environment.
Next steps
After you have an environment running an application, you can deploy a new version of the application
or a different application at any time. Deploying a new application version is very quick because it
doesn't require provisioning or restarting EC2 instances.
After you deploy a sample application or two and are ready to start developing and running Go
applications locally, see Setting up your Go development environment (p. 100).
For common setup steps and tools that apply to all languages, see Configuring your development
machine for use with Elastic Beanstalk (p. 953).
Installing Go
To run Go applications locally, install Go. If you don't need a specific version, get the latest version that
Elastic Beanstalk supports. For a list of supported versions, see Go in the AWS Elastic Beanstalk Platforms
document.
100
AWS Elastic Beanstalk Developer Guide
The Go platform
Download Go at https://golang.org/doc/install.
$ go get github.com/aws/aws-sdk-go
• Provide a source bundle with a source file at the root called application.go that contains the main
package for your application. Elastic Beanstalk builds the binary using the following command:
In both cases, with Go 1.11 or later, you can also provide module requirements in a file called go.mod.
For more information, see Migrating to Go Modules in the Go blog.
For more complex Go applications, there are two ways to deploy your application:
• Provide a source bundle that includes your application source files, along with a Buildfile (p. 104)
and a Procfile (p. 103). The Buildfile includes a command to build the application, and the Procfile
includes instructions to run the application.
• Provide a source bundle that includes your application binary files, along with a Procfile. The Procfile
includes instructions to run the application.
The Go platform includes a proxy server to serve static assets and forward traffic to your application. You
can extend or override the default proxy configuration (p. 104) for advanced scenarios.
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
Use the Elastic Beanstalk console to enable log rotation to Amazon S3 and configure variables that your
application can read from the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
101
AWS Elastic Beanstalk Developer Guide
The Go platform
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
Environment properties
The Environment Properties section lets you specify environment configuration settings on the Amazon
EC2 instances that are running your application. Environment properties are passed in as key-value pairs
to the application.
Inside the Go environment running in Elastic Beanstalk, environment variables are accessible using the
os.Getenv function. For example, you could read a property named API_ENDPOINT to a variable with
the following code:
endpoint := os.Getenv("API_ENDPOINT")
See Environment properties and other software settings (p. 590) for more information.
Go configuration namespace
You can use a configuration file (p. 683) to set configuration options and perform other instance
configuration tasks during deployments. Configuration options can be defined by the Elastic Beanstalk
service or the platform that you use and are organized into namespaces.
The Go platform doesn't define any platform-specific namespaces. You can configure the proxy to serve
static files by using the aws:elasticbeanstalk:environment:proxy:staticfiles namespace.
For details and an example, see the section called “Static files” (p. 732).
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
102
AWS Elastic Beanstalk Developer Guide
The Go platform
Go configuration namespaces
You can use a configuration file (p. 683) to set configuration options and perform other instance
configuration tasks during deployments. Configuration options can be defined by the Elastic Beanstalk
service or the platform that you use and are organized into namespaces.
For example, this configuration file (p. 683) tells the proxy server to serve files in the staticimages
folder at the path /images:
Example .ebextensions/go-settings.config
option_settings:
aws:elasticbeanstalk:container:golang:staticfiles:
/html: statichtml
/images: staticimages
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
For details about writing and using a Procfile, expand the Buildfile and Procfile section in the section
called “Extending Linux platforms” (p. 31).
Example Procfile
web: bin/server
queue_process: bin/queue_processor
foo: bin/fooapp
You must call the main application web, and list it as the first command in your Procfile. Elastic
Beanstalk exposes the main web application on the root URL of the environment; for example, http://
my-go-env.elasticbeanstalk.com.
Elastic Beanstalk also runs any application whose name does not have the web_ prefix, but these
applications are not available from outside of your instance.
Elastic Beanstalk expects processes run from the Procfile to run continuously. Elastic Beanstalk
monitors these applications and restarts any process that terminates. For short-running processes, use a
Buildfile (p. 104) command.
103
AWS Elastic Beanstalk Developer Guide
The Go platform
Port passing
Elastic Beanstalk configures the nginx proxy to forward requests to your application on the port
number specified in the PORT environment property (p. 101) for your application. Your application
should always listen on that port. You can access this variable within your application by calling the
os.Getenv("PORT") method.
Elastic Beanstalk uses the port number specified in the PORT environment property for the port for the
first application in the Procfile, and then increments the port number for each subsequent application
in the Procfile by 100. If the PORT environment property is not set, Elastic Beanstalk uses 5000 for the
initial port.
In the preceding example, the PORT environment property for the web application is 5000, the
queue_process application is 5100, and the foo application is 5200.
You can specify the initial port by setting the PORT option with the
aws:elasticbeanstalk:application:environment (p. 648) namespace, as shown in the following example.
option_settings:
- namespace: aws:elasticbeanstalk:application:environment
option_name: PORT
value: <first_port_number>
For more information about setting environment properties for your application, see Option
settings (p. 684).
<process_name>: <command>
The command in your Buildfile must match the following regular expression: ^[A-Za-z0-9_]+:
\s*.+$.
Elastic Beanstalk doesn't monitor the application that is run with a Buildfile. Use a Buildfile for
commands that run for short periods and terminate after completing their tasks. For long-running
application processes that should not exit, use the Procfile (p. 103) instead.
In the following example of a Buildfile, build.sh is a shell script that is located at the root of the
source bundle:
make: ./build.sh
All paths in the Buildfile are relative to the root of the source bundle. If you know in advance where
the files reside on the instance, you can include absolute paths in the Buildfile.
By default, Elastic Beanstalk configures the nginx proxy to forward requests to your application on port
5000. You can override the default port by setting the PORT environment property (p. 101) to the port
on which your main application listens.
104
AWS Elastic Beanstalk Developer Guide
Tutorial for Go
Note
The port that your application listens on doesn't affect the port that the nginx server listens to
receive requests from the load balancer.
All Amazon Linux 2 platforms support a uniform proxy configuration feature. For details about
configuring the proxy server on the new Amazon Corretto platform versions running Amazon
Linux 2, expand the Reverse Proxy Configuration section in the section called “Extending Linux
platforms” (p. 31).
Elastic Beanstalk uses nginx as the reverse proxy to map your application to your load balancer on port
80. If you want to provide your own nginx configuration, you can override the default configuration
provided by Elastic Beanstalk by including the .ebextensions/nginx/nginx.conf file in your source
bundle. If this file is present, Elastic Beanstalk uses it in place of the default nginx configuration file.
If you want to include directives in addition to those in the nginx.conf http block, you can also
provide additional configuration files in the .ebextensions/nginx/conf.d/ directory of your source
bundle. All files in this directory must have the .conf extension.
To take advantage of functionality provided by Elastic Beanstalk, such as Enhanced health reporting and
monitoring (p. 776), automatic application mappings, and static files, you must include the following
line in the server block of your nginx configuration file:
include conf.d/elasticbeanstalk/*.conf;
Sections
• Prerequisites (p. 105)
• Create a Go application (p. 106)
• Deploy your Go application with the EB CLI (p. 106)
• Clean up (p. 108)
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
105
AWS Elastic Beanstalk Developer Guide
Tutorial for Go
this is output
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
This tutorial uses the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing and
configuring the EB CLI, see Install the EB CLI (p. 957) and Configure the EB CLI (p. 964).
Create a Go application
Create a project directory.
~$ mkdir eb-go
~$ cd eb-go
Next, create an application that you'll deploy using Elastic Beanstalk. We'll create a "Hello World" RESTful
web service.
This example prints a customized greeting that varies based on the path used to access the service.
Create a text file in this directory named application.go with the following contents.
Example ~/eb-go/application.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}
106
AWS Elastic Beanstalk Developer Guide
Tutorial for Go
This command creates an application named go-tutorial, and configures your local repository to
create environments with the latest Go platform version.
2. (Optional) Run eb init again to configure a default key pair so that you can use SSH to connect to
the EC2 instance running your application.
~/eb-go$ eb init
Do you want to set up SSH for your instances?
(y/n): y
Select a keypair.
1) my-keypair
2) [ Create new KeyPair ]
Select a key pair if you have one already, or follow the prompts to create one. If you don't see the
prompt or need to change your settings later, run eb init -i.
3. Create an environment and deploy your application to it with eb create. Elastic Beanstalk
automatically builds a binary file for your application and starts it on port 5000.
Environment creation takes about five minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
Elastic Beanstalk manages all of these resources. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
107
AWS Elastic Beanstalk Developer Guide
Working with Java
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
When the environment creation process completes, open your website with eb open.
~/eb-go$ eb open
This opens a browser window using the domain name created for your application.
If you don't see your application running, or get an error message, see Troubleshooting
Deployments (p. 1061) for help with how to determine the cause of the error.
If you do see your application running, then congratulations, you've deployed a Go application with
Elastic Beanstalk!
Clean up
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
~/eb-go$ eb terminate
• Tomcat – A platform based on Apache Tomcat, an open source web container for applications
that use Java servlets and JavaServer Pages (JSPs) to serve HTTP requests. Tomcat facilitates web
application development by providing multithreading, declarative security configuration, and
extensive customization. Elastic Beanstalk has platform branches for each of Tomcat's current major
versions. For more information, see The Tomcat platform (p. 115).
• Java SE – A platform for applications that don't use a web container, or use one other than Tomcat,
such as Jetty or GlassFish. You can include any library Java Archives (JARs) used by your application
108
AWS Elastic Beanstalk Developer Guide
Getting started
in the source bundle that you deploy to Elastic Beanstalk. For more information, see The Java SE
platform (p. 126).
Recent branches of both the Tomcat and Java SE platforms are based on Amazon Linux 2, and use
Corretto—the AWS Java SE distribution. Names of these branches in the platform lists include the word
Corretto instead of Java, for example, Corretto 11 with Tomcat 8.5.
For a list of current platform versions, see Tomcat and Java SE in the AWS Elastic Beanstalk Platforms
guide.
AWS provides several tools for working with Java and Elastic Beanstalk. Regardless of the platform
branch that you choose, you can use the AWS SDK for Java (p. 115) to use other AWS services from
within your Java application. The AWS SDK for Java is a set of libraries that allow you to use AWS APIs
from your application code without writing the raw HTTP calls from scratch.
If you use the Eclipse integrated development environment (IDE) to develop your Java application, you
can also get the AWS Toolkit for Eclipse (p. 137). The AWS Toolkit for Eclipse is an open source plug-
in that lets you manage AWS resources, including Elastic Beanstalk applications and environments, from
within the Eclipse IDE.
If the command line is more your style, install the Elastic Beanstalk Command Line Interface (p. 956)
(EB CLI) and use it to create, monitor, and manage your Elastic Beanstalk environments from the
command line. If you run multiple environments for your application, the EB CLI integrates with Git to let
you associate each of your environments with a different Git branch.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
Topics
• Getting started with Java on Elastic Beanstalk (p. 109)
• Setting up your Java development environment (p. 114)
• Using the Elastic Beanstalk Tomcat platform (p. 115)
• Using the Elastic Beanstalk Java SE platform (p. 126)
• Adding an Amazon RDS DB instance to your Java application environment (p. 132)
• Using the AWS Toolkit for Eclipse (p. 137)
• Resources (p. 151)
The single page samples are the same code that you get when you create an environment without
supplying your own source code. The more complex examples are hosted on GitHub and may need to be
compiled or built prior to deploying to an Elastic Beanstalk environment.
109
AWS Elastic Beanstalk Developer Guide
Getting started
Samples
TomcatAll Tomcat with Corretto platform branches Web tomcat.zipTomcat web application with
(single Server a single page (index.jsp)
page) configured to be displayed at the
Worker website root.
For worker
environments (p. 482), this
sample includes a cron.yaml
file that configures a scheduled
task that calls scheduled.jsp
once per minute. When
scheduled.jsp is called, it
writes to a log file at /tmp/
sample-app.log. Finally, a
configuration file is included in
.ebextensions that copies the
logs from /tmp/ to the locations
read by Elastic Beanstalk when
you request environment logs.
Corretto
Corretto 11 Web corretto.zip
Corretto application with
(single Server Buildfile and Procfile
page)Corretto 8 configuration files.
Scorekeep
Java 8 Web Clone Scorekeep is a RESTful web API
Serverthe that uses the Spring framework
repo at to provide an interface for
GitHub.com
creating and managing users,
sessions, and games. The API is
bundles with an Angular 1.5 web
app that consumes the API over
HTTP.
110
AWS Elastic Beanstalk Developer Guide
Getting started
Does Tomcat 8 with Java 8 Web Clone Does it Have Snakes? is a Tomcat
it Serverthe web application that shows
Have repo at the use of Elastic Beanstalk
Snakes? GitHub.com
configuration files, Amazon RDS,
JDBC, PostgreSQL, Servlets, JSPs,
Simple Tag Support, Tag Files,
Log4J, Bootstrap, and Jackson.
111
AWS Elastic Beanstalk Developer Guide
Getting started
Locust
Java 8 Web Clone Web application that you can
Load Serverthe use to load test another web
Generator repo at application running in a different
GitHub.com
Elastic Beanstalk environment.
Shows the use of Buildfile
and Procfile files, DynamoDB,
and Locust, an open source load
testing tool.
Download any of the sample applications and deploy it to Elastic Beanstalk by following these steps:
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose an existing application's name in the
list or create one (p. 377).
3. On the application overview page, choose Create a new environment.
4. Next, for environment tier, choose the Web server environment or Worker environment
environment tier (p. 13). You can't change an environment's tier after creation.
Note
The .NET on Windows Server platform (p. 182) doesn't support the worker environment
tier.
112
AWS Elastic Beanstalk Developer Guide
Getting started
5. For Platform, select the platform and platform branch that match the language your application
uses.
Note
Elastic Beanstalk supports multiple versions (p. 29) for most of the platforms that are
listed. By default, the console selects the recommended version for the platform and
platform branch you choose. If your application requires a different version, you can select
it here, or choose Configure more options, as described in step 7. For information about
supported platform versions, see the section called “Supported platforms” (p. 29).
6. For Application code, choose Sample application.
7. To further customize your environment, choose Configure more options. You can set the following
options only during environment creation:
• Environment name
• Domain name
• Platform version
• Processor
• VPC
• Tier
You can change the following settings after environment creation, but they require new instances or
other resources to be provisioned and can take a long time to apply:
• Instance type, root volume, key pair, and AWS Identity and Access Management (IAM) role
• Internal Amazon RDS database
• Load balancer
113
AWS Elastic Beanstalk Developer Guide
Development environment
For details on all available settings, see The create new environment wizard (p. 409).
8. Choose Create environment.
Next steps
After you have an environment running an application, you can deploy a new version (p. 441) of the
application or a completely different application at any time. Deploying a new application version is very
quick because it doesn't require provisioning or restarting EC2 instances.
After you've deployed a sample application or two and are ready to start developing and running Java
applications locally, see the next section (p. 114) to set up a Java development environment with all of
the tools and libraries that you will need.
For common setup steps and tools that apply to all languages, see Configuring your development
machine (p. 953).
Sections
• Installing the Java development kit (p. 114)
• Installing a web container (p. 114)
• Downloading libraries (p. 114)
• Installing the AWS SDK for Java (p. 115)
• Installing an IDE or text editor (p. 115)
• Installing the AWS toolkit for Eclipse (p. 115)
The JDK includes the Java compiler, which you can use to build your source files into class files that can
be executed on an Elastic Beanstalk web server.
Downloading libraries
Elastic Beanstalk platforms include few libraries by default. Download libraries that your application will
use and save them in your project folder to deploy in your application source bundle.
114
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
If you've installed Tomcat locally, you can copy the servlet API and JavaServer Pages (JSP) API libraries
from the installation folder. If you deploy to a Tomcat platform version, you don't need to include these
files in your source bundle, but you do need to have them in your classpath to compile any classes that
use them.
JUnit, Google Guava, and Apache Commons provide several useful libraries. Visit their home pages to
learn more:
• Download JUnit
• Download Google Guava
• Download Apache Commons
Visit the AWS SDK for Java home page for more information and installation instructions.
Note
An IDE might add files to your project folder that you might not want to commit to source
control. To prevent committing these files to source control, use .gitignore or your source
control tool's equivalent.
If you just want to begin coding and don't need all of the features of an IDE, consider installing Sublime
Text.
115
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
Out of caution, Elastic Beanstalk released new platform versions that use the latest Amazon
Linux default package repositories, which include the Log4j hotpatched JDK, in our Amazon
Linux platform release on December 21, 2021. If you've customized log4j installation as your
application dependency, we recommend that you upgrade to the latest Elastic Beanstalk
platform version to mitigate CVE-2021-44228 or CVE-2021-45046. You can also enable
automated managed updates as part of normal update practices.
For more information about security-related software updates for Amazon Linux, see the
Amazon Linux Security Center.
The AWS Elastic Beanstalk Tomcat platform is a set of platform versions for Java web applications that
can run in a Tomcat web container. Tomcat runs behind an nginx proxy server. Each platform branch
corresponds to a major version of Tomcat, like Java 8 with Tomcat 8.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
The Elastic Beanstalk Tomcat platform includes a reverse proxy that forwards requests to your
application. You can use configuration options (p. 118) to configure the proxy server to serve static
assets from a folder in your source code to reduce the load on your application. For advanced scenarios,
you can include your own .conf files (p. 122) in your source bundle to extend the Elastic Beanstalk
proxy configuration or overwrite it completely.
Note
Elastic Beanstalk supports nginx (the default) and Apache HTTP Server as the proxy servers on
the Tomcat platform. If your Elastic Beanstalk Tomcat environment uses an Amazon Linux AMI
platform branch (preceding Amazon Linux 2), you also have the option of using Apache HTTP
Server Version 2.2. Apache (latest) is the default on these older platform branches.
You must package Java applications in a web application archive (WAR) file with a specific structure. For
information on the required structure and how it relates to the structure of your project directory, see
Structuring your project folder (p. 120).
To run multiple applications on the same web server, you can bundle multiple WAR files (p. 119)
into a single source bundle. Each application in a multiple WAR source bundle runs at the root path
(ROOT.war runs at myapp.elasticbeanstalk.com/) or at a path directly beneath it (app2.war runs
at myapp.elasticbeanstalk.com/app2/), as determined by the name of the WAR. In a single WAR
source bundle, the application always runs at the root path.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
Topics
• Configuring your Tomcat environment (p. 117)
• Tomcat configuration namespaces (p. 118)
• The Amazon Linux AMI (preceding Amazon Linux 2) Tomcat platform (p. 119)
• Bundling multiple WAR files for Tomcat environments (p. 119)
116
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
You can use the Elastic Beanstalk console to enable log rotation to Amazon S3 and configure variables
that your application can read from the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Container options
You can specify these platform-specific options:
• Proxy server – The proxy server to use on your environment instances. By default, nginx is used.
The permanent generation is a section of the JVM heap that stores class definitions and associated
metadata. To modify the size of the permanent generation, type the new size in the Maximum JVM
PermGen Size (-XX:MaxPermSize argument) field. This setting applies only to Java 7 and earlier.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
117
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
Environment properties
In the Environment Properties section, you can specify environment configuration settings on the
Amazon EC2 instances that are running your application. Environment properties are passed in as key-
value pairs to the application.
The Tomcat platform defines a placeholder property named JDBC_CONNECTION_STRING for Tomcat
environments for passing a connection string to an external database.
Note
If you attach an RDS DB instance to your environment, construct the JDBC connection string
dynamically from the Amazon Relational Database Service (Amazon RDS) environment
properties provided by Elastic Beanstalk. Use JDBC_CONNECTION_STRING only for database
instances that are not provisioned using Elastic Beanstalk.
For more information about using Amazon RDS with your Java application, see Adding an
Amazon RDS DB instance to your Java application environment (p. 132).
Inside the Tomcat environment running in Elastic Beanstalk, environment variables are accessible using
the System.getProperty(). For example, you could read a property named API_ENDPOINT to a
variable with the following code.
See Environment properties and other software settings (p. 590) for more information.
The Tomcat platform supports options in the following namespaces, in addition to the options
supported for all Elastic Beanstalk environments (p. 632):
The following example configuration file shows the use of the Tomcat-specific configuration options.
Example .ebextensions/tomcat-settings.config
option_settings:
aws:elasticbeanstalk:container:tomcat:jvmoptions:
Xms: 512m
118
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
The following example configuration file shows the use of the proxy namespace configuration options.
Example .ebextensions/tomcat-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
GzipCompression: 'true'
ProxyServer: nginx
Example
For an application requiring multiple WAR files, see Bundling multiple WAR files for Tomcat
environments (p. 119) for further instructions.
To deploy multiple web applications to your environment, combine each component's web application
archive (WAR) files into a single source bundle (p. 385).
119
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
To create an application source bundle that contains multiple WAR files, organize the WAR files using the
following structure.
MyApplication.zip
### .ebextensions
### .platform
### foo.war
### bar.war
### ROOT.war
When you deploy a source bundle containing multiple WAR files to an AWS Elastic Beanstalk
environment, each application is accessible from a different path off of the root domain name.
The preceding example includes three applications: foo, bar, and ROOT. ROOT.war is a special
file name that tells Elastic Beanstalk to run that application at the root domain, so that the
three applications are available at http://MyApplication.elasticbeanstalk.com/
foo, http://MyApplication.elasticbeanstalk.com/bar, and http://
MyApplication.elasticbeanstalk.com.
The source bundle can include WAR files, an optional .ebextensions folder, and an optional
.platform folder. For details about these optional configuration folders, see the section called
“Extending Linux platforms” (p. 31).
For information about creating source bundles, see Create an application source bundle (p. 385).
In the following recommended hierarchy, the source code for the web application is placed in a src
directory, to isolate it from the build script and the WAR file it generates.
~/workspace/my-app/
|-- build.sh - Build script that compiles classes and creates a WAR
|-- README.MD - Readme file with information about your project, notes
|-- ROOT.war - Source bundle artifact created by build.sh
`-- src - Source code folder
|-- WEB-INF - Folder for private supporting files
| |-- classes - Compiled classes
| |-- lib - JAR libraries
| |-- tags - Tag files
120
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
The src folder contents match what you will package and deploy to the server, with the exception of the
com folder. The com folder contains your uncompiled classes (.java files). These need to be compiled
and placed in the WEB-INF/classes directory to be accessible from your application code.
The WEB-INF directory contains code and configurations that are not served publicly on the web server.
The other folders at the root of the source directory (css, images, and js) are publicly available at the
corresponding path on the web server.
The following example is identical to the preceding project directory, except that it contains more files
and subdirectories. This example project includes simple tags, model and support classes, and a Java
Server Pages (JSP) file for a record resource. It also includes a style sheet and JavaScript for Bootstrap,
a default JSP file, and an error page for 404 errors.
WEB-INF/lib includes a Java Archive (JAR) file containing the Java Database Connectivity (JDBC) driver
for PostgreSQL. WEB-INF/classes is empty because class files have not been compiled yet.
~/workspace/my-app/
|-- build.sh
|-- README.MD
|-- ROOT.war
`-- src
|-- WEB-INF
| |-- classes
| |-- lib
| | `-- postgresql-9.4-1201.jdbc4.jar
| |-- tags
| | `-- header.tag
| |-- tlds
| | `-- records.tld
| `-- web.xml
|-- com
| `-- myapp
| |-- model
| | `-- Record.java
| `-- web
| `-- ListRecords.java
|-- css
| |-- bootstrap.min.css
| `-- myapp.css
|-- images
| `-- myapp.png
|-- js
| `-- bootstrap.min.js
|-- 404.jsp
|-- default.jsp
`-- records.jsp
cd src
121
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
Inside the WAR file, you find the same structure that exists in the src directory in the preceding
example, excluding the src/com folder. The jar command automatically creates the META-INF/
MANIFEST.MF file.
~/workspace/my-app/ROOT.war
|-- META-INF
| `-- MANIFEST.MF
|-- WEB-INF
| |-- classes
| | `-- com
| | `-- myapp
| | |-- model
| | | `-- Records.class
| | `-- web
| | `-- ListRecords.class
| |-- lib
| | `-- postgresql-9.4-1201.jdbc4.jar
| |-- tags
| | `-- header.tag
| |-- tlds
| | `-- records.tld
| `-- web.xml
|-- css
| |-- bootstrap.min.css
| `-- myapp.css
|-- images
| `-- myapp.png
|-- js
| `-- bootstrap.min.js
|-- 404.jsp
|-- default.jsp
`-- records.jsp
Using .gitignore
To avoid committing compiled class files and WAR files to your Git repository, or seeing messages about
them appear when you run Git commands, add the relevant file types to a file named .gitignore in
your project folder.
~/workspace/myapp/.gitignore
*.zip
*.class
122
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
All Amazon Linux 2 platforms support a uniform proxy configuration feature. For details about
configuring the proxy server on Tomcat platform versions running Amazon Linux 2, expand the Reverse
Proxy Configuration section in the section called “Extending Linux platforms” (p. 31).
Configuring the proxy on the Amazon Linux AMI (preceding Amazon Linux 2)
Tomcat platform
If your Elastic Beanstalk Tomcat environment uses an Amazon Linux AMI platform version (preceding
Amazon Linux 2), read the additional information in this section.
Example .ebextensions/nginx-proxy.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: nginx
Starting with Tomcat platform version 3.0.0 configurations, which were released with the Java with
Tomcat platform update on May 24, 2018, Apache 2.4 is the default proxy of the Tomcat platform.
The Apache 2.4 .conf files are mostly, but not entirely, backward compatible with those of Apache
2.2. Elastic Beanstalk includes default .conf files that work correctly with each Apache version. If your
application doesn't customize Apache's configuration, as explained in Extending and overriding the
default Apache configuration (p. 124), it should migrate to Apache 2.4 without any issues.
If your application extends or overrides Apache's configuration, you might have to make some changes
to migrate to Apache 2.4. For more information, see Upgrading to 2.4 from 2.2 on The Apache Software
Foundation's site. As a temporary measure, until you successfully migrate to Apache 2.4, you can choose
to use Apache 2.2 with your application by including the following configuration file (p. 683) in your
source code.
Example .ebextensions/apache-legacy-proxy.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: apache/2.2
For a quick fix, you can also select the proxy server in the Elastic Beanstalk console.
To select the proxy in your Tomcat environment in the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
123
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
You can extend the Elastic Beanstalk default Apache configuration with your additional configuration
files. Alternatively, you can override the Elastic Beanstalk default Apache configuration completely.
To extend the Elastic Beanstalk default Apache configuration, add .conf configuration files to a folder
named .ebextensions/httpd/conf.d in your application source bundle. The Elastic Beanstalk
Apache configuration includes .conf files in this folder automatically.
~/workspace/my-app/
|-- .ebextensions
| -- httpd
| -- conf.d
| -- myconf.conf
| -- ssl.conf
-- index.jsp
For example, the following Apache 2.4 configuration adds a listener on port 5000.
Example .ebextensions/httpd/conf.d/port5000.conf
listen 5000
<VirtualHost *:5000>
<Proxy *>
Require all granted
</Proxy>
ProxyPass / http://localhost:8080/ retry=0
ProxyPassReverse / http://localhost:8080/
ProxyPreserveHost on
ErrorLog /var/log/httpd/elasticbeanstalk-error_log
</VirtualHost>
To override the Elastic Beanstalk default Apache configuration completely, include a configuration in
your source bundle at .ebextensions/httpd/conf/httpd.conf.
~/workspace/my-app/
|-- .ebextensions
124
AWS Elastic Beanstalk Developer Guide
The Tomcat platform
| `-- httpd
| `-- conf
| `-- httpd.conf
`-- index.jsp
If you override the Elastic Beanstalk Apache configuration, add the following lines to your httpd.conf
to pull in the Elastic Beanstalk configurations for Enhanced health reporting and monitoring (p. 776),
response compression, and static files.
IncludeOptional conf.d/*.conf
IncludeOptional conf.d/elasticbeanstalk/*.conf
If your environment uses Apache 2.2 as its proxy, replace the IncludeOptional directives with
Include. For details about the behavior of these two directives in the two Apache versions, see Include
in Apache 2.4, IncludeOptional in Apache 2.4, and Include in Apache 2.2.
Note
To override the default listener on port 80, include a file named 00_application.conf at
.ebextensions/httpd/conf.d/elasticbeanstalk/ to overwrite the Elastic Beanstalk
configuration.
For a working example, take a look at the Elastic Beanstalk default configuration file at /etc/httpd/
conf/httpd.conf on an instance in your environment. All files in the .ebextensions/httpd folder
in your source bundle are copied to /etc/httpd during deployments.
To extend Elastic Beanstalk's default nginx configuration, add .conf configuration files to a folder
named .ebextensions/nginx/conf.d/ in your application source bundle. The Elastic Beanstalk
nginx configuration includes .conf files in this folder automatically.
~/workspace/my-app/
|-- .ebextensions
| `-- nginx
| `-- conf.d
| |-- elasticbeanstalk
| | `-- my-server-conf.conf
| `-- my-http-conf.conf
`-- index.jsp
Files with the .conf extension in the conf.d folder are included in the http block of the default
configuration. Files in the conf.d/elasticbeanstalk folder are included in the server block within
the http block.
To override the Elastic Beanstalk default nginx configuration completely, include a configuration in your
source bundle at .ebextensions/nginx/nginx.conf.
~/workspace/my-app/
|-- .ebextensions
| `-- nginx
| `-- nginx.conf
`-- index.jsp
If you override the Elastic Beanstalk nginx configuration, add the following line to your configuration's
server block to pull in the Elastic Beanstalk configurations for the port 80 listener, response
compression, and static files.
include conf.d/elasticbeanstalk/*.conf;
125
AWS Elastic Beanstalk Developer Guide
The Java SE platform
Note
To override the default listener on port 80, include a file named 00_application.conf at
.ebextensions/nginx/conf.d/elasticbeanstalk/ to overwrite the Elastic Beanstalk
configuration.
Also include the following line in your configuration's http block to pull in the Elastic Beanstalk
configurations for Enhanced health reporting and monitoring (p. 776) and logging.
include conf.d/*.conf;
For a working example, take a look at the Elastic Beanstalk default configuration file at /etc/nginx/
nginx.conf on an instance in your environment. All files in the .ebextensions/nginx folder in your
source bundle are copied to /etc/nginx during deployments.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
The Elastic Beanstalk Java SE platform includes an nginx server that acts as a reverse proxy, serving
cached static content and passing requests to your application. The platform provides configuration
options to configure the proxy server to serve static assets from a folder in your source code to reduce
the load on your application. For advanced scenarios, you can include your own .conf files (p. 130) in
your source bundle to extend Elastic Beanstalk's proxy configuration or overwrite it completely.
If you only provide a single JAR file for your application source (on its own, not within a source bundle),
Elastic Beanstalk renames your JAR file to application.jar, and then runs it using java -jar
application.jar. To configure the processes that run on the server instances in your environment,
include an optional Procfile (p. 129) in your source bundle. A Procfile is required if you have more
than one JAR in your source bundle root, or if you want to customize the java command to set JVM
options.
We recommend that you always provide a Procfile in the source bundle alongside your application.
This way you precisely control which processes Elastic Beanstalk runs for your application and which
arguments these processes receive.
To compile Java classes and run other build commands on the EC2 instances in your environment at
deploy time, include a Buildfile (p. 128) in your application source bundle. A Buildfile lets you
deploy your source code as-is and build on the server instead of compiling JARs locally. The Java SE
platform includes common build tools to let you build on-server.
126
AWS Elastic Beanstalk Developer Guide
The Java SE platform
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
Use the Elastic Beanstalk console to enable log rotation to Amazon S3 and configure variables that your
application can read from the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
Environment properties
The Environment Properties section lets you specify environment configuration settings on the Amazon
EC2 instances that are running your application. Environment properties are passed in as key-value pairs
to the application.
Inside the Java SE environment running in Elastic Beanstalk, environment variables are accessible using
the System.getenv(). For example, you could read a property named API_ENDPOINT to a variable
with the following code:
See Environment properties and other software settings (p. 590) for more information.
127
AWS Elastic Beanstalk Developer Guide
The Java SE platform
The Java SE platform doesn't define any platform-specific namespaces. You can configure the proxy
to serve static files by using the aws:elasticbeanstalk:environment:proxy:staticfiles
namespace. For details and an example, see the section called “Static files” (p. 732).
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
You can use a configuration file (p. 683) to set configuration options and perform other instance
configuration tasks during deployments. Configuration options can be defined by the Elastic Beanstalk
service or the platform that you use and are organized into namespaces.
For example, this option_settings (p. 684) snippet defines two options in the static files namespace.
The first maps the path /public to a folder named public, and the second maps the path /images to
a folder named img:
option_settings:
aws:elasticbeanstalk:container:java:staticfiles:
/html: statichtml
/images: staticimages
The folders that you map using this namespace must be actual folders in the root of your source bundle.
You cannot map a path to a folder in a JAR file.
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
Commands in a Buildfile are only run once and must terminate upon completion, whereas commands
in a Procfile (p. 129) are expected to run for the life of the application and will be restarted if they
terminate. To run the JARs in your application, use a Procfile.
128
AWS Elastic Beanstalk Developer Guide
The Java SE platform
For details about the placement and syntax of a Buildfile, expand the Buildfile and Procfile section in
the section called “Extending Linux platforms” (p. 31).
The following Buildfile example runs Apache Maven to build a web application from source code. For
a sample application that uses this feature, see Java web application samples (p. 109).
Example Buildfile
The Java SE platform includes the following build tools, which you can invoke from your build script:
We recommend that you always provide a Procfile in the source bundle alongside your application.
This way you precisely control which processes Elastic Beanstalk runs for your application and which
arguments these processes receive.
For details about writing and using a Procfile, expand the Buildfile and Procfile section in the section
called “Extending Linux platforms” (p. 31).
Example Procfile
The command that runs the main JAR in your application must be called web, and it must be the first
command listed in your Procfile. The nginx server forwards all HTTP requests that it receives from
your environment's load balancer to this application.
Elastic Beanstalk assumes that all entries in the Procfile should run at all times and automatically
restarts any application defined in the Procfile that terminates. To run commands that will terminate and
should not be restarted, use a Buildfile (p. 128).
Port passing
By default, Elastic Beanstalk configures the nginx proxy to forward requests to your application on port
5000. You can override the default port by setting the PORT environment property (p. 127) to the port
on which your main application listens.
If you use a Procfile to run multiple applications, Elastic Beanstalk on Amazon Linux AMI platform
versions expects each additional application to listen on a port 100 higher than the previous one.
129
AWS Elastic Beanstalk Developer Guide
The Java SE platform
Elastic Beanstalk sets the PORT variable accessible from within each application to the port that it
expects the application to run on. You can access this variable within your application code by calling
System.getenv("PORT").
In the preceding Procfile example, the web application listens on port 5000, cache listens on port
5100, and web_foo listens on port 5200. web configures its listening port by reading the PORT variable,
and adds 100 to that number to determine which port cache is listening on so that it can send it
requests.
By default, Elastic Beanstalk configures the nginx proxy to forward requests to your application on port
5000. You can override the default port by setting the PORT environment property (p. 127) to the port
on which your main application listens.
Note
The port that your application listens on doesn't affect the port that the nginx server listens to
receive requests from the load balancer.
All Amazon Linux 2 platforms support a uniform proxy configuration feature. For details about
configuring the proxy server on the new Amazon Corretto platform versions running Amazon
Linux 2, expand the Reverse Proxy Configuration section in the section called “Extending Linux
platforms” (p. 31).
To extend Elastic Beanstalk's default nginx configuration, add .conf configuration files to a folder
named .ebextensions/nginx/conf.d/ in your application source bundle. Elastic Beanstalk's nginx
configuration includes .conf files in this folder automatically.
~/workspace/my-app/
|-- .ebextensions
| `-- nginx
| `-- conf.d
| `-- myconf.conf
`-- web.jar
To override Elastic Beanstalk's default nginx configuration completely, include a configuration in your
source bundle at .ebextensions/nginx/nginx.conf:
~/workspace/my-app/
|-- .ebextensions
| `-- nginx
| `-- nginx.conf
`-- web.jar
If you override Elastic Beanstalk's nginx configuration, add the following line to your nginx.conf to pull
in Elastic Beanstalk's configurations for Enhanced health reporting and monitoring (p. 776), automatic
application mappings, and static files.
130
AWS Elastic Beanstalk Developer Guide
The Java SE platform
include conf.d/elasticbeanstalk/*.conf;
The following example configuration from the Scorekeep sample application overrides Elastic Beanstalk's
default configuration to serve a static web application from the public subdirectory of /var/app/
current, where the Java SE platform copies the application source code. The /api location forwards
traffic to routes under /api/ to the Spring application listening on port 5000. All other traffic is served
by the web app at the root path.
Example .ebextensions/nginx/nginx.conf
user nginx;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_processes auto;
worker_rlimit_nofile 33282;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
include conf.d/*.conf;
server {
listen 80 default_server;
root /var/app/current/public;
location / {
}
location /api {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
client_header_timeout 60;
client_body_timeout 60;
keepalive_timeout 60;
gzip off;
gzip_comp_level 4;
131
AWS Elastic Beanstalk Developer Guide
Adding a database
}
}
If you are using Amazon RDS for the first time, add a DB instance to a test environment by using the
Elastic Beanstalk console and verify that your application can connect to it.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577). For instructions on configuring an external database for use with
Elastic Beanstalk, see Using Elastic Beanstalk with Amazon RDS (p. 923).
132
AWS Elastic Beanstalk Developer Guide
Adding a database
To connect to the database, add the appropriate driver JAR file to your application, load the driver
class in your code, and create a connection object with the environment properties provided by Elastic
Beanstalk.
Sections
• Downloading the JDBC driver (p. 133)
• Connecting to a database (Java SE platforms) (p. 133)
• Connecting to a database (Tomcat platforms) (p. 134)
• Troubleshooting database connections (p. 136)
You can find the latest driver for your DB engine in the following locations:
To use the JDBC driver, call Class.forName() to load it before creating the connection with
DriverManager.getConnection() in your code.
jdbc:driver://hostname:port/dbName?user=userName&password=password
You can retrieve the hostname, port, database name, user name, and password from the environment
variables that Elastic Beanstalk provides to your application. The driver name is specific to your database
type and driver version. The following are example driver names:
133
AWS Elastic Beanstalk Developer Guide
Adding a database
Class.forName("org.postgresql.Driver");
String dbName = System.getenv("RDS_DB_NAME");
String userName = System.getenv("RDS_USERNAME");
String password = System.getenv("RDS_PASSWORD");
String hostname = System.getenv("RDS_HOSTNAME");
String port = System.getenv("RDS_PORT");
String jdbcUrl = "jdbc:postgresql://" + hostname + ":" + port + "/" + dbName + "?
user=" + userName + "&password=" + password;
logger.trace("Getting remote connection with connection string from environment
variables.");
Connection con = DriverManager.getConnection(jdbcUrl);
logger.info("Remote connection successful.");
return con;
}
catch (ClassNotFoundException e) { logger.warn(e.toString());}
catch (SQLException e) { logger.warn(e.toString());}
}
return null;
}
The following example code shows a class that creates a connection to a PostgreSQL database.
If you have trouble getting a connection or running SQL statements, try placing the following code in a
JSP file. This code connects to a DB instance, creates a table, and writes to it.
134
AWS Elastic Beanstalk Developer Guide
Adding a database
try {
// Create connection to RDS DB instance
conn = DriverManager.getConnection(jdbcUrl);
setupStatement.addBatch(createTable);
setupStatement.addBatch(insertRow1);
setupStatement.addBatch(insertRow2);
setupStatement.executeBatch();
setupStatement.close();
try {
conn = DriverManager.getConnection(jdbcUrl);
readStatement = conn.createStatement();
resultSet = readStatement.executeQuery("SELECT Resource FROM Beanstalk;");
resultSet.first();
results = resultSet.getString("Resource");
resultSet.next();
results += ", " + resultSet.getString("Resource");
resultSet.close();
readStatement.close();
conn.close();
135
AWS Elastic Beanstalk Developer Guide
Adding a database
To display the results, place the following code in the body of the HTML portion of the JSP file.
<p>Established connection to RDS. Read first two rows: <%= results %></p>
Reviewing logs
You can view all the logs from your Elastic Beanstalk environment from within Eclipse. If you don't have
the AWS Explorer view open, choose the arrow next to the orange AWS icon in the toolbar, and then
choose Show AWS Explorer View. Expand AWS Elastic Beanstalk and your environment name, and then
open the context (right-click) menu for the server. Choose Open in WTP Server Editor.
Choose the Log tab of the Server view to see the aggregate logs from your environment. To open the
latest logs, choose the Refresh button at the upper right corner of the page.
Scroll down to locate the Tomcat logs in /var/log/tomcat7/catalina.out. If you loaded the
webpage from our earlier example several times, you might see the following.
-------------------------------------
/var/log/tomcat7/catalina.out
-------------------------------------
INFO: Server startup in 9285 ms
Loading driver...
Driver loaded!
SQLException: Table 'Beanstalk' already exists
SQLState: 42S01
VendorError: 1050
Closing the connection.
Closing the connection.
All information that the web application sends to standard output appears in the web container log. In
the previous example, the application tries to create the table every time the page loads. This results in
catching a SQL exception on every page load after the first one.
As an example, the preceding is acceptable. But in actual applications, keep your database definitions in
schema objects, perform transactions from within model classes, and coordinate requests with controller
servlets.
First, open the security group to your RDS DB instance to allow traffic from your computer.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
136
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Next to Endpoint, choose the Amazon RDS console link.
6. On the RDS Dashboard instance details page, under Security and Network, choose the security
group starting with rds- next to Security Groups.
Note
The database might have multiple entries labeled Security Groups. Use the first, which
starts with awseb, only if you have an older account that doesn't have a default Amazon
Virtual Private Cloud (Amazon VPC).
7. In Security group details, choose the Inbound tab, and then choose Edit.
8. Add a rule for MySQL (port 3306) that allows traffic from your IP address, specified in CIDR format.
9. Choose Save. The changes take effect immediately.
Return to the Elastic Beanstalk configuration details for your environment and note the endpoint. You
will use the domain name to connect to the RDS DB instance.
Install the MySQL client and initiate a connection to the database on port 3306. On Windows, install
MySQL Workbench from the MySQL home page and follow the prompts.
On Linux, install the MySQL client using the package manager for your distribution. The following
example works on Ubuntu and other Debian derivatives.
After you have connected, you can run SQL commands to see the status of the database, whether your
tables and rows were created, and other information.
137
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
toolkit includes support for multiple AWS accounts, managing existing environments, and connecting
directly to instances in your environment for troubleshooting.
Note
The AWS Toolkit for Eclipse only supports projects that use the Java with Tomcat platform, not
the Java SE platform.
For more information about prerequisites and installing the AWS Toolkit for Eclipse, go to https://
aws.amazon.com/eclipse. You can also check out the Using AWS Elastic Beanstalk with the AWS
Toolkit for Eclipse video. This topic also provides useful information covering tools, how-to topics, and
additional resources for Java developers.
To import existing environments, expand the AWS Elastic Beanstalk node and double-click on an
environment in the AWS Explorer inside Eclipse. You can now deploy your Elastic Beanstalk applications
to this environment.
With the AWS Toolkit for Eclipse, you can change the provisioning and configuration of the AWS
resources that are used by your application environments. For information on how to manage your
application environments using the AWS Management Console, see Managing environments (p. 396).
This section discusses the specific service settings you can edit in the AWS Toolkit for Eclipse as part of
your application environment configuration. For more about AWS Toolkit for Eclipse, see AWS Toolkit for
Eclipse Getting Started Guide.
1. If Eclipse isn't displaying the AWS Explorer view, in the menu choose Window, Show View, AWS
Explorer. Expand the Elastic Beanstalk node and your application node.
2. In AWS Explorer, double-click your Elastic Beanstalk environment.
3. At the bottom of the pane, click the Configuration tab.
138
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
139
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
need, and for any legal purpose. Instances are available in different sizes and configurations. For more
information, go to the Amazon EC2 product page.
Under Server, on your environment's Configuration tab inside the Toolkit for Eclipse, you can edit the
Elastic Beanstalk environment's Amazon EC2 instance configuration.
Instance type displays the instance types available to your Elastic Beanstalk application. Change the
instance type to select a server with the characteristics (including memory size and CPU power) that
are most appropriate to your application. For example, applications with intensive and long-running
operations can require more CPU or memory.
For more information about the Amazon EC2 instance types available for your Elastic Beanstalk
application, see Instance Types in the Amazon Elastic Compute Cloud User Guide.
You can control access to your Elastic Beanstalk application using an Amazon EC2 Security Group. A
security group defines firewall rules for your instances. These rules specify which ingress (i.e., incoming)
network traffic should be delivered to your instance. All other ingress traffic will be discarded. You can
modify rules for a group at any time. The new rules are automatically enforced for all running instances
and instances launched in the future.
You can set up your Amazon EC2 security groups using the AWS Management Console or by using
the AWS Toolkit for Eclipse. You can specify which Amazon EC2 security groups control access to your
Elastic Beanstalk application by entering the names of one or more Amazon EC2 security group names
(delimited by commas) into the EC2 Security Groups box.
Note
If you are running your application using a legacy container type, make sure port 80 (HTTP) is
accessible from 0.0.0.0/0 as the source CIDR range if you want to enable health checks for your
application. For more information about health checks, see Health checks (p. 143). To check if
you are using a legacy container type, see the section called “Why are some platform versions
marked legacy?” (p. 470)
1. In the AWS Toolkit for Eclipse, click AWS Explorer tab. Expand the Amazon EC2 node, and then
double-click Security Groups.
140
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
2. Right-click anywhere in the left table, and then click New Group.
3. In the Security Group dialog box, type the security group name and description and then click OK.
For more information on Amazon EC2 Security Groups, see Using Security Groups in the Amazon Elastic
Compute Cloud User Guide.
You can securely log in to the Amazon EC2 instances provisioned for your Elastic Beanstalk application
with an Amazon EC2 key pair.
Important
You must create an Amazon EC2 key pair and configure your Elastic Beanstalk-provisioned
Amazon EC2 instances to use the Amazon EC2 key pair before you can access your Elastic
Beanstalk-provisioned Amazon EC2 instances. You can create your key pair using the Publish
to Beanstalk Wizard inside AWS Toolkit for Eclipse when you deploy your application to Elastic
Beanstalk. Alternatively, you can set up your Amazon EC2 key pairs using the AWS Management
Console. For instructions on creating a key pair for Amazon EC2, see the Amazon Elastic
Compute Cloud Getting Started Guide.
For more information on Amazon EC2 key pairs, go to Using Amazon EC2 Credentials in the Amazon
Elastic Compute Cloud User Guide. For more information on connecting to Amazon EC2 instances, go to
Connecting to Instances and Connecting to a Linux/UNIX Instance from Windows using PuTTY in the
Amazon Elastic Compute Cloud User Guide.
CloudWatch metrics
By default, only basic Amazon CloudWatch metrics are enabled. They return data in five-minute periods.
You can enable more granular one-minute CloudWatch metrics by selecting 1 minute for the Monitoring
Interval in the Server section of the Configuration tab for your environment in the AWS Toolkit for
Eclipse.
Note
Amazon CloudWatch service charges can apply for one-minute interval metrics. See Amazon
CloudWatch for more information.
Custom AMI ID
You can override the default AMI used for your Amazon EC2 instances with your own custom AMI by
entering the identifier of your custom AMI into the Custom AMI ID box in the Server section of the
Configuration tab for your environment in the AWS Toolkit for Eclipse.
Important
Using your own AMI is an advanced task that you should do with care. If you need a custom
AMI, we recommend you start with the default Elastic Beanstalk AMI and then modify it.
To be considered healthy, Elastic Beanstalk expects Amazon EC2 instances to meet a set of
requirements, including having a running host manager. If these requirements are not met, your
environment might not work properly.
141
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
Elastic Load Balancing automatically distributes and balances incoming application traffic among all the
EC2 server instances you are running. The service also makes it easy to add new instances when you need
to increase the capacity of your application.
Elastic Beanstalk automatically provisions Elastic Load Balancing when you deploy an application. Under
Load Balancing, on the Configuration tab for your environment inside the Toolkit for Eclipse, you can
edit the Elastic Beanstalk environment's load balancing configuration.
The following sections describe the Elastic Load Balancing parameters you can configure for your
application.
Ports
The load balancer provisioned to handle requests for your Elastic Beanstalk application sends requests to
the Amazon EC2 instances that are running your application. The provisioned load balancer can listen for
requests on HTTP and HTTPS ports and route requests to the Amazon EC2 instances in your AWS Elastic
Beanstalk application. By default, the load balancer handles requests on the HTTP port. At least one of
the ports (either HTTP or HTTPS) must be turned on.
Important
Make sure that the port you specified is not locked down; otherwise, users will not be able to
connect to your Elastic Beanstalk application.
142
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
To turn off the HTTP port, you select OFF for HTTP Listener Port. To turn on the HTTP port, you select
an HTTP port (for example, 80).
Note
To access your environment using a port other than the default port 80, such as port 8080, add
a listener to the existing load balancer and configure the new listener to listen on that port.
For example, using the AWS CLI for Classic load balancers, type the following command,
replacing LOAD_BALANCER_NAME with the name of your load balancer for Elastic Beanstalk.
For example, using the AWS CLI for Application Load Balancers, type the following command,
replacing LOAD_BALANCER_ARN with the ARN of your load balancer for Elastic Beanstalk.
If you want Elastic Beanstalk to monitor your environment, do not remove the listener on port
80.
Elastic Load Balancing supports the HTTPS/TLS protocol to enable traffic encryption for client
connections to the load balancer. Connections from the load balancer to the EC2 instances are done
using plain text. By default, the HTTPS port is turned off.
1. Create a new certificate using AWS Certificate Manager (ACM) or upload a certificate and key to AWS
Identity and Access Management (IAM). For more information about requesting an ACM certificate,
see Request a Certificate in the AWS Certificate Manager User Guide. For more information about
importing third-party certificates into ACM, see Importing Certificates in the AWS Certificate
Manager User Guide. If ACM isn't available in your AWS Region, use AWS Identity and Access
Management (IAM) to upload a third-party certificate. The ACM and IAM services store the certificate
and provide an Amazon Resource Name (ARN) for the SSL certificate. For more information about
creating and uploading certificates to IAM, see Working with Server Certificates in IAM User Guide.
2. Specify the HTTPS port by selecting a port from the HTTPS Listener Port drop-down list.
3. In the SSL Certificate ID text box, enter the Amazon Resources Name (ARN) of
your SSL certificate. For example, arn:aws:iam::123456789012:server-
certificate/abc/certs/build or arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678. Use the SSL
certificate that you created and uploaded in step 1.
To turn off the HTTPS port, select OFF for HTTPS Listener Port.
Health checks
You can control the settings for the health check using the EC2 Instance Health Check section of the
Load Balancing panel.
143
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
The following list describes the health check parameters you can set for your application.
• To determine instance health, Elastic Beanstalk looks for a 200 response code on a URL it queries. By
default, Elastic Beanstalk checks TCP:80 for nonlegacy containers and HTTP:80 for legacy containers.
You can override to match an existing resource in your application (e.g., /myapp/index.jsp) by
entering it in the Application Health Check URL box. If you override the default URL, Elastic Beanstalk
uses HTTP to query the resource. To check if you are using a legacy container type, see the section
called “Why are some platform versions marked legacy?” (p. 470)
• For Health Check Interval (seconds), enter the number of seconds between your application's Amazon
EC2 instances health checks.
• For Health Check Timeout, specify the number of seconds for Elastic Load Balancing to wait for a
response before it considers an instance unresponsive.
• Use the Healthy Check Count Threshold and Unhealthy Check Count Threshold boxes, specify the
number of consecutive successful or unsuccessful URL probes before Elastic Load Balancing changes
the instance health status. For example, specifying 5 in the Unhealthy Check Count Threshold text
box means that the URL would have to return an error message or timeout five consecutive times
before Elastic Load Balancing considers the health check "failed."
Sessions
By default, a load balancer routes each request independently to the server instance with the smallest
load. By comparison, a sticky session binds a user's session to a specific server instance so that all
requests coming from the user during the session are sent to the same server instance.
Elastic Beanstalk uses load balancer–generated HTTP cookies when sticky sessions are enabled for an
application. The load balancer uses a special load balancer–generated cookie to track the application
instance for each request. When the load balancer receives a request, it first checks to see if this cookie
is present in the request. If so, the request is sent to the application instance specified in the cookie. If it
finds no cookie, the load balancer chooses an application instance based on the existing load balancing
algorithm. A cookie is inserted into the response for binding subsequent requests from the same user to
that application instance. The policy configuration defines a cookie expiry, which establishes the duration
of validity for each cookie.
Under Load Balancer in the Sessions section, specify whether or not the load balancer for your
application allows session stickiness and the duration for each cookie.
For more information on Elastic Load Balancing, see the Elastic Load Balancing Developer Guide.
144
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
Amazon EC2 Auto Scaling lets you take a group of Amazon EC2 instances and set various parameters
to have this group automatically increase or decrease in number. Amazon EC2 Auto Scaling can add or
remove Amazon EC2 instances from that group to help you seamlessly deal with traffic changes to your
application.
Amazon EC2 Auto Scaling also monitors the health of each Amazon EC2 instance that it launches. If any
instance terminates unexpectedly, Amazon EC2 Auto Scaling detects the termination and launches a
replacement instance. This capability enables you to maintain a fixed, desired number of Amazon EC2
instances automatically.
Elastic Beanstalk provisions Amazon EC2 Auto Scaling for your application. Under Auto Scaling, on
your environment's Configuration tab inside the Toolkit for Eclipse, you can edit the Elastic Beanstalk
environment's Auto Scaling configuration.
The following sections discuss how to configure Auto Scaling parameters for your application.
Launch configuration
You can edit the launch configuration to control how your Elastic Beanstalk application provisions
Amazon EC2 Auto Scaling resources.
Use the Minimum Instance Count and Maximum Instance Count settings to specify the minimum and
maximum size of the Auto Scaling group that your Elastic Beanstalk application uses.
145
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
Note
To maintain a fixed number of Amazon EC2 instances, set the Minimum Instance Count and
Maximum Instance Count text boxes to the same value.
For Availability Zones, specify the number of Availability Zones you want your Amazon EC2 instances to
be in. It is important to set this number if you want to build fault-tolerant applications: If one Availability
Zone goes down, your instances will still be running in your other Availability Zones.
Note
Currently, it is not possible to specify which Availability Zone your instance will be in.
Triggers
A trigger is an Amazon EC2 Auto Scaling mechanism that you set to tell the system when to increase
(scale out) and decrease (scale in) the number of instances. You can configure triggers to fire on any
metric published to Amazon CloudWatch, such as CPU utilization, and determine whether the specified
conditions have been met. When your upper or lower thresholds for the metric have been breached for
the specified period of time, the trigger launches a long-running process called a scaling activity.
You can define a scaling trigger for your Elastic Beanstalk application using the AWS Toolkit for Eclipse.
You can configure the following list of trigger parameters in the Scaling Trigger section of the
Configuration tab for your environment inside the Toolkit for Eclipse.
146
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
For more information on Amazon EC2 Auto Scaling, see the Amazon EC2 Auto Scaling section on Amazon
Elastic Compute Cloud Documentation.
To access the Container/JVM options panel for your Elastic Beanstalk application
1. If Eclipse isn't displaying the AWS Explorer view, in the menu choose Window, Show View, AWS
Explorer. Expand the Elastic Beanstalk node and your application node.
2. In the AWS Explorer, double-click your Elastic Beanstalk environment.
3. At the bottom of the pane, click the Configuration tab.
4. Under Container, you can configure container options.
Remote debugging
To test your application remotely, you can run your application in debug mode.
147
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
The Additional Tomcat JVM command line options setting is filled automatically.
1. In the AWS Toolkit for Eclipse menu, choose Window, Show View, Other.
2. Expand the Server folder, and then choose Servers. Choose OK.
3. In the Servers pane, right-click the server your application is running on, and then click Restart in
Debug.
1. If Eclipse isn't displaying the AWS Explorer view, choose Window, Show View, Other. Expand AWS
Toolkit and then choose AWS Explorer.
2. In the AWS Explorer pane, expand Elastic Beanstalk, expand the node for your application, and
then double-click your Elastic Beanstalk environment.
3. At the bottom of the pane for your environment, click the Advanced tab.
4. Under aws:elasticbeanstalk:application:environment, click JDBC_CONNECTION_STRING and
then type a connection string. For example, the following JDBC connection string would connect to
a MySQL database instance on port 3306 of localhost, with a user name of me and a password of
mypassword:
jdbc:mysql://localhost:3306/mydatabase?user=me&password=mypassword
This will be accessible to your Elastic Beanstalk application as a system property called
JDBC_CONNECTION_STRING.
5. Press Ctrl+C on the keyboard or choose File, Save to save your changes to the environment
configuration. Changes are reflected in about one minute.
148
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
1. In Eclipse, make sure the toolbar is visible. On the toolbar, click the arrow next to the AWS icon and
select Preferences.
2. Click Add account.
3. In the Account Name text box, type the display name for the account.
4. In the Access Key ID text box, type your AWS access key ID.
5. In the Secret Access Key text box, type your AWS secret key.
For API access, you need an access key ID and secret access key. Use IAM user access keys instead of
AWS account root user access keys. For more information about creating access keys, see Managing
access keys for IAM users in the IAM User Guide.
6. Click OK.
1. In the Eclipse toolbar, click the arrow next to the AWS icon and select Preferences.
2. For Default Account, select the account you want to use to deploy applications to Elastic Beanstalk.
3. Click OK.
4. In the Project Explorer pane, right-click the application you want to deploy, and then select Amazon
Web Services > Deploy to Elastic Beanstalk.
Viewing events
You can use the AWS Toolkit for Eclipse to access events and notifications associated with your
application.
149
AWS Elastic Beanstalk Developer Guide
Eclipse toolkit
1. If Eclipse isn't displaying the AWS Explorer view, in the menu click Window > Show View > AWS
Explorer. Expand the Elastic Beanstalk node and your application node.
2. In the AWS Explorer, double-click your Elastic Beanstalk environment.
3. At the bottom of the pane, click the Events tab.
A list of the events for all environments for your application is displayed.
1. In the AWS Toolkit for Eclipse, click AWS Explorer. Expand the Amazon EC2 node, and then double-
click Instances.
2. In the Amazon EC2 Instances window, in the Instance ID column, right-click the Instance ID for the
Amazon EC2 instance running in your application's load balancer. Then click Open Shell.
Eclipse automatically opens the SSH client and makes the connection to the EC2 instance.
150
AWS Elastic Beanstalk Developer Guide
Resources
For more information on connecting to an Amazon EC2 instance, see the Amazon Elastic Compute
Cloud Getting Started Guide.
Terminating an environment
To avoid incurring charges for unused AWS resources, you can use the AWS Toolkit for Eclipse to
terminate a running environment. For details about environment termination, see Terminate an Elastic
Beanstalk environment (p. 430).
To terminate an environment
1. In the AWS Toolkit for Eclipse, click the AWS Explorer pane. Expand the Elastic Beanstalk node.
2. Expand the Elastic Beanstalk application and right-click on the Elastic Beanstalk environment.
3. Click Terminate Environment. It will take a few minutes for Elastic Beanstalk to terminate the AWS
resources running in the environment.
Resources
There are several places you can go to get additional help when developing your Java applications.
Resource Description
The AWS Java Development Forum Post your questions and get feedback.
Java Developer Center One-stop shop for sample code, documentation, tools, and
additional resources.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
Topics
• Getting started with .NET Core on Linux (p. 151)
• Setting up your .NET Core on Linux development environment (p. 154)
• Using the .NET Core on Linux platform (p. 154)
• Tutorial: Deploying an ASP.NET core application on Linux using Elastic Beanstalk (p. 159)
• The AWS Toolkit for Visual Studio - Working with .Net Core (p. 164)
• Migrating from .NET on Windows Server platforms to the .NET Core on Linux platform (p. 181)
151
AWS Elastic Beanstalk Developer Guide
Getting started
an environment. When you create an environment, Elastic Beanstalk allocates all of the AWS resources
needed to run a highly scalable web application.
Samples
.NET Core on Web dotnet-core- Two web applications that run on the same web
Linux server linux-multiple- server.
apps.zip
Download the sample application and deploy it to Elastic Beanstalk by following these steps.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose an existing application's name in the
list or create one (p. 377).
3. On the application overview page, choose Create a new environment.
4. Next, for environment tier, choose the Web server environment or Worker environment
environment tier (p. 13). You can't change an environment's tier after creation.
Note
The .NET on Windows Server platform (p. 182) doesn't support the worker environment
tier.
152
AWS Elastic Beanstalk Developer Guide
Getting started
5. For Platform, select the platform and platform branch that match the language your application
uses.
Note
Elastic Beanstalk supports multiple versions (p. 29) for most of the platforms that are
listed. By default, the console selects the recommended version for the platform and
platform branch you choose. If your application requires a different version, you can select
it here, or choose Configure more options, as described in step 7. For information about
supported platform versions, see the section called “Supported platforms” (p. 29).
6. For Application code, choose Sample application.
7. To further customize your environment, choose Configure more options. You can set the following
options only during environment creation:
• Environment name
• Domain name
• Platform version
• Processor
• VPC
• Tier
You can change the following settings after environment creation, but they require new instances or
other resources to be provisioned and can take a long time to apply:
• Instance type, root volume, key pair, and AWS Identity and Access Management (IAM) role
• Internal Amazon RDS database
• Load balancer
153
AWS Elastic Beanstalk Developer Guide
Development environment
For details on all available settings, see The create new environment wizard (p. 409).
8. Choose Create environment.
Next steps
After you have an environment running an application, you can deploy a new version of the application
or a different application at any time. Deploying a new application version is very quick because it
doesn't require provisioning or restarting Amazon EC2 instances.
After you deploy a sample application or two and are ready to start developing and running .NET Core
applications locally, see Setting up your .NET Core on Linux development environment (p. 154).
For common setup steps and tools that apply to all languages, see Configuring your development
machine for use with Elastic Beanstalk (p. 953).
Sections
• Installing the .NET Core SDK (p. 154)
• Installing an IDE (p. 154)
• Installing the AWS Toolkit for Visual Studio (p. 154)
See the .NET downloads page to download and install the .NET Core SDK.
Installing an IDE
Integrated development environments (IDEs) provide a range of features that facilitate application
development. If you haven't used an IDE for .NET development, try Visual Studio Community to get
started.
See the Visual Studio Community page to download and install Visual Studio Community.
154
AWS Elastic Beanstalk Developer Guide
The .NET Core on Linux platform
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see
the section called “Extending Linux platforms” (p. 31). Following are some platform-specific
considerations.
Application structure
You can publish runtime-dependent applications that use the .NET Core runtime provided by Elastic
Beanstalk. You can also publish self-contained applications that include the .NET Core runtime and
your application's dependencies in the source bundle. To learn more, see the section called “Bundling
applications” (p. 157).
Platform configuration
To configure the processes that run on the server instances in your environment, include an optional
Procfile (p. 158) in your source bundle. A Procfile is required if you have more than one application
in your source bundle.
We recommend that you always provide a Procfile in the source bundle with your application. This
way you precisely control which processes Elastic Beanstalk runs for your application.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
Use the Elastic Beanstalk console to enable log rotation to Amazon S3 and configure variables that your
application can read from the environment.
To configure your .NET Core on Linux environment using the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
155
AWS Elastic Beanstalk Developer Guide
The .NET Core on Linux platform
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Environment properties
The Environment Properties section enables you to specify environment configuration settings on the
Amazon EC2 instances that are running your application. Environment properties are passed in as key-
value pairs to the application.
Inside the .NET Core on Linux environment running in Elastic Beanstalk, environment variables are
accessible using Environment.GetEnvironmentVariable("variable-name"). For example, you
could read a property named API_ENDPOINT to a variable with the following code.
See Environment properties and other software settings (p. 590) for more information.
The .NET Core on Linux platform supports options in the following namespace, in addition to the options
supported for all Elastic Beanstalk environments (p. 632):
The following example configuration file shows the use of the .NET Core on Linux-specific configuration
options.
Example .ebextensions/proxy-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: none
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
156
AWS Elastic Beanstalk Developer Guide
The .NET Core on Linux platform
A runtime-dependent application uses a .NET Core runtime that Elastic Beanstalk provides to run your
application. Elastic Beanstalk uses the runtimeconfig.json file in your source bundle to determine
the runtime to use for your application. Elastic Beanstalk chooses the latest compatible runtime available
for your application.
A self-contained application includes the .NET Core runtime, your application, and its dependencies. To
use a version of the .NET Core runtime that Elastic Beanstalk doesn't include in its platforms, provide a
self-contained application.
Examples
You can compile both self-contained and runtime-dependent applications with the dotnet publish
command. To learn more about publishing .NET Core apps, see .NET Core application publishing
overview in the .NET Core documentation.
The following example file structure defines a single application that uses a .NET Core runtime that
Elastic Beanstalk provides.
### appsettings.Development.json
### appsettings.json
### dotnetcoreapp.deps.json
### dotnetcoreapp.dll
### dotnetcoreapp.pdb
### dotnetcoreapp.runtimeconfig.json
### web.config
### Procfile
### .ebextensions
### .platform
You can include multiple applications in your source bundle. The following example defines two
applications to run on the same web server. To run multiple applications, you must include a
Procfile (p. 158) in your source bundle. For a full example application, see dotnet-core-linux-multiple-
apps.zip.
### DotnetMultipleApp1
# ### Amazon.Extensions.Configuration.SystemsManager.dll
# ### appsettings.Development.json
# ### appsettings.json
# ### AWSSDK.Core.dll
# ### AWSSDK.Extensions.NETCore.Setup.dll
# ### AWSSDK.SimpleSystemsManagement.dll
# ### DotnetMultipleApp1.deps.json
# ### DotnetMultipleApp1.dll
# ### DotnetMultipleApp1.pdb
# ### DotnetMultipleApp1.runtimeconfig.json
# ### Microsoft.Extensions.PlatformAbstractions.dll
# ### Newtonsoft.Json.dll
# ### web.config
### DotnetMultipleApp2
# ### Amazon.Extensions.Configuration.SystemsManager.dll
# ### appsettings.Development.json
# ### appsettings.json
# ### AWSSDK.Core.dll
# ### AWSSDK.Extensions.NETCore.Setup.dll
# ### AWSSDK.SimpleSystemsManagement.dll
# ### DotnetMultipleApp2.deps.json
# ### DotnetMultipleApp2.dll
157
AWS Elastic Beanstalk Developer Guide
The .NET Core on Linux platform
We recommend that you always provide a Procfile in the source bundle with your application.
This way you precisely control which processes Elastic Beanstalk runs for your application and which
arguments these processes receive.
The following example uses a Procfile to specify two applications for Elastic Beanstalk to run on the
same web server.
Example Procfile
For details about writing and using a Procfile, expand the Buildfile and Procfile section in the section
called “Extending Linux platforms” (p. 31).
By default, Elastic Beanstalk configures the nginx proxy to forward requests to your application on port
5000. You can override the default port by setting the PORT environment property (p. 156) to the port
on which your main application listens.
Note
The port that your application listens on doesn't affect the port that the nginx server listens on
receive requests from the load balancer.
All Amazon Linux 2 platforms support a uniform proxy configuration feature. For details about
configuring the proxy server, expand the Reverse Proxy Configuration section in the section called
“Extending Linux platforms” (p. 31).
The following example configuration file extends your environment's nginx configuration. The
configuration directs requests to /api to a second web application that listens on port 5200 on the web
server. By default, Elastic Beanstalk forwards requests to a single application that listens on port 5000.
Example 01_custom.conf
location /api {
proxy_pass http://127.0.0.1:5200;
proxy_http_version 1.1;
158
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core on Linux
In this tutorial, you first use the .NET Core SDK's dotnet command line tool to do the following:
Sections
• Prerequisites (p. 159)
• Generate a .NET core project as a web application (p. 160)
• Launch an Elastic Beanstalk environment and deploy your application (p. 162)
• Cleanup (p. 163)
• Next steps (p. 163)
Prerequisites
This tutorial uses the .NET Core SDK to generate a basic .NET Core web application, run it locally, and
build a deployable package.
Requirements
1. Download the installer from microsoft.com/net/core. Choose your development platform. Choose
Download .NET Core SDK.
159
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core on Linux
Note
Although the examples in this tutorial are listings from the Windows command line, the .NET
Core SDK supports development platforms on several operating systems. The dotnet
commands shown in this tutorial are consistent across different development platforms.
This tutorial uses a command line ZIP utility to create a source bundle that you can deploy to Elastic
Beanstalk. To use the zip command in Windows, you can install UnxUtils. (UnxUtils is a lightweight
collection of useful command line utilities like zip and ls.) Alternatively, you can use Windows
Explorer (p. 386) or any other ZIP utility to create source bundle archives.
To install UnxUtils
1. Download UnxUtils.
2. Extract the archive to a local directory. For example, C:\Program Files (x86).
3. Add the path to the binaries to your Windows PATH user variable. For example, C:\Program Files
(x86)\UnxUtils\usr\local\wbin.
> zip -h
Copyright (C) 1990-1999 Info-ZIP
Type 'zip "-L"' for software license.
...
1. Open a new command prompt window and navigate to your user folder.
> cd %USERPROFILE%
2. Use the dotnet new command to generate a new .NET Core project.
160
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core on Linux
Restore succeeded.
C:\Users\username> cd dotnet-core-tutorial
C:\Users\username\dotnet-core-tutorial> dotnet restore
Determining projects to restore...
All projects are up-to-date for restore.
2. Use the dotnet run command to build and start the application locally.
3. Open localhost:5000 to view the site from your default web browser.
The application returns Hello World!, which is displayed on your web browser.
To run the application on a web server, you must bundle the compiled source code with a web.config
configuration file and runtime dependencies. The dotnet tool provides a publish command that
gathers these files in a directory based on the configuration in dotnet-core-tutorial.csproj.
• Use the dotnet publish command to output compiled code and dependencies to a folder named
site.
The source bundle contains all of the files published to the site folder.
161
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core on Linux
Note
If you use a different ZIP utility, be sure to add all files to the root folder of the resulting
ZIP archive. This is required for a successful deployment of the application to your Elastic
Beanstalk environment.
C:\users\username\dotnet-core-tutorial> cd site
C:\users\username\dotnet-core-tutorial\site>zip -r ../dotnet-core-tutorial.zip .
adding: appsettings.Development.json (164 bytes security) (deflated 38%)
adding: appsettings.json (164 bytes security) (deflated 39%)
adding: dotnet-core-tutorial.deps.json (164 bytes security) (deflated 93%)
adding: dotnet-core-tutorial.dll (164 bytes security) (deflated 58%)
adding: dotnet-core-tutorial.exe (164 bytes security) (deflated 57%)
adding: dotnet-core-tutorial.pdb (164 bytes security) (deflated 48%)
adding: dotnet-core-tutorial.runtimeconfig.json (164 bytes security) (deflated 33%)
adding: web.config (164 bytes security) (deflated 41%)
Note
In this tutorial, you are only running one application on the web server, so a Procfile is not
required in your source bundle. However, to deploy multiple applications on the same web
server, you must include a Procfile. For more information, see Using a Procfile to configure
your .NET Core on Linux environment (p. 158).
It takes about 10 minutes to create the environment and deploy your code.
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
162
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core on Linux
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
Elastic Beanstalk manages all of these resources. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and isn't
deleted when you terminate the environment. For more information, see Using Elastic Beanstalk
with Amazon S3 (p. 935).
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
As you continue to develop your application, you might want to manage your environments and deploy
your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console.
163
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use commands for
creating, configuring, and deploying applications to Elastic Beanstalk environments from the command
line interface.
If you use Visual Studio to develop your application, you can also use the AWS Toolkit for Visual Studio
to deploy changes in your code, manage your Elastic Beanstalk environments, and manage other AWS
resources. See The AWS Toolkit for Visual Studio (p. 212) for more information.
For developing and testing purposes, you can consider leveraging the deployment functionality
ofElastic Beanstalk to add a managed DB instance directly to your environment. For information
on setting up a database inside your environment, see Adding a database to your Elastic Beanstalk
environment (p. 577).
Last, if you plan to use your application in a production environment, we recommend that you configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
This topic shows how you can do the following tasks using the AWS Toolkit for Visual Studio:
This topic also explores how you can use the AWS Toolkit for Visual Studio to manage your Elastic
Beanstalk application environments and monitor your application's health.
Sections
• Prerequisites (p. 164)
• Create a new application project (p. 164)
• Create an Elastic Beanstalk environment and deploy your application (p. 166)
• Terminating an environment (p. 169)
• Managing your Elastic Beanstalk application environments (p. 170)
• Monitoring application health (p. 180)
Prerequisites
Before you begin this tutorial, you need to install the AWS Toolkit for Visual Studio. For instructions, see
Setting up the AWS Toolkit for Visual Studio.
If you have never used the toolkit before, the first thing you'll need to do after installing the toolkit is
to register your AWS credentials with the toolkit. For more information about this, see Providing AWS
Credentials.
164
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
1. In Visual Studio, on the File menu, choose New and then choose Project.
2. In the Create a new project dialog box, select C#, select Linux, and then select Cloud.
3. From the list of project templates that displays select ASP.NET Core Web Application, and then
select Next.
Note
If you don't see ASP.NET Core Web Application listed in the project templates, you can
install it in Visual Studio.
1. Scroll to the bottom of the template list and select the Install more tools and features
link that is located under the template list.
2. If you are prompted to allow the Visual Studio application to make changes to your
device, select Yes.
3. Choose the Workloads tab, then select ASP.NET and web development.
4. Select the Modify button. The Visual Studio Installer installs the project template.
5. After the installer completes, exit the panel to return to where you left off in Visual
Studio .
4. In the Configure your new project dialog box, enter a Project name. The Solution name defaults to
your project name. Next, choose Create.
5. In the Create a new ASP.NET Core web application dialog box, select .NET Core, and then select
ASP.NET Core 3.1. From the list of application types that are displayed, select Web Application,
then select the Create button.
Visual Studio displays the Creating Project dialog box when it creates your application. After Visual
Studio completes generating your application, a panel with your application name is displayed.
165
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
3. In the Publish to AWS Elastic Beanstalk wizard, enter your account information.
a. For Account profile to use, select your default account or choose the Add another account icon
to enter new account information.
b. For Region, select the Region where you want to deploy your application. For information about
available AWS Regions, see AWS Elastic Beanstalk Endpoints and Quotas in the AWS General
Reference. If you select a Region that is not supported by Elastic Beanstalk, then the option to
deploy to Elastic Beanstalk is unavailable.
166
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
4. On the Application Environment dialog box, enter the details for your new application
environment.
5. On the next AWS options dialog box, set Amazon EC2 options and other AWS related options for
your deployed application.
a. For Container type select 64bit Amazon Linux 2 v<n.n.n> running .NET Core.
Note
We recommend you select the current platform version of Linux. This version contains
the most recent security and bug fixes that are included in our latest Amazon Machine
Image (AMI).
b. For Instance Type, select t2.micro. (Choosing a micro instance type minimizes the cost
associated with running the instance.)
c. For Key pair, select Create new key pair. Enter a name for the new key pair, and then choose
OK. (In this example, we use myuseastkeypair.) A key pair enables remote-desktop access
to your Amazon EC2 instances. For more information about Amazon EC2 key pairs, see Using
Credentials in the Amazon Elastic Compute Cloud User Guide.
d. For a simple, low traffic application, select Single instance environment. For more information,
see Environment types (p. 480)
e. Select Next.
167
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
For more information about the AWS options that are not used in this example consider the
following pages:
• For Use custom AMI, see Using a custom Amazon machine image (AMI) (p. 729).
• If you don't select Single instance environment, you need to choose a Load balance type. See
Load balancer for your Elastic Beanstalk environment (p. 526) for more information.
• Elastic Beanstalk uses the default Amazon VPC (Amazon Virtual Private Cloud) configuration if
you didn't choose Use non-default VPC. For more information see Using Elastic Beanstalk with
Amazon VPC (p. 938).
• Choosing the Enable Rolling Deployments option splits a deployment into batches to avoid
potential downtime during deployments. For more information, see Deploying applications to
Elastic Beanstalk environments (p. 441).
• Choosing the Relational Database Access option connects your Elastic Beanstalk environment
to a previously created Amazon RDS database with Amazon RDS DB Security Groups. For more
information, see Controlling Access with Security Groups in the Amazon RDS User Guide.
6. Select Next on the Permissions dialog box.
7. Select Next on the Applications Options dialog box.
8. Review your deployment options. After you've verified your settings are correct, select Deploy.
Your ASP.NET Core web application is exported as a web deploy file. This file is then uploaded to Amazon
S3 and registered as a new application version with Elastic Beanstalk. The Elastic Beanstalk deployment
feature monitors your environment until it is available with the newly deployed code. The Status for your
environment is displayed on the Env:<environment name> tab. After the status updates to Environment
is healthy, you can select the URL address to launch the web application.
168
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Terminating an environment
To avoid incurring charges for unused AWS resources, you can use the AWS Toolkit for Visual Studio to
terminate a running environment.
Note
You can always launch a new environment using the same version later.
To terminate an environment
1. Expand the Elastic Beanstalk node and the application node. In AWS Explorer open the context
(right-click) menu for your application environment and select Terminate Environment.
2. When prompted, select Yes to confirm that you want to terminate the environment. It takes a few
minutes for Elastic Beanstalk to terminate the AWS resources running in the environment.
The Status for your environment on the Env:<environment name> tab changes to Terminating and is
eventually Terminated.
Note
When you terminate your environment, the CNAME associated with the terminated environment
becomes available for anyone to use.
169
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
• AWS X-Ray
• Server
• Load Balancer (only applies to multiple-instance environments)
• Auto Scaling (only applies to multiple-instance environments)
• Notifications
• Container
• Advanced Configuration Options
170
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Configuring AWS X-Ray using the AWS toolkit for Visual Studio
AWS X-Ray provides request tracing, exception collection, and profiling capabilities. With the AWS X-Ray
panel, you can enable or disable X-Ray for your application. For more information about X-Ray, see the
AWS X-Ray Developer Guide.
Configuring EC2 instances using the AWS toolkit for Visual Studio
You can use Amazon Elastic Compute Cloud (Amazon EC2) to launch and manage server instances
in Amazon's data centers. You can use Amazon EC2 server instances at any time, for as long as you
need, and for any legal purpose. Instances are available in different sizes and configurations. For more
information, see Amazon EC2.
You can edit your Amazon EC2 instance configuration with the Server tab inside your application
environment tab in the AWS Toolkit for Visual Studio.
Instance type displays the instance types available to your Elastic Beanstalk application. Change the
instance type to select a server with the characteristics (including memory size and CPU power) that
are most appropriate to your application. For example, applications with intensive and long-running
operations can require more CPU or memory.
For more information about the Amazon EC2 instance types available for your Elastic Beanstalk
application, see Instance Types in the Amazon Elastic Compute Cloud User Guide.
171
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
You can specify which Amazon EC2 Security Groups control access to your Elastic Beanstalk application.
To do this, enter the names of specific Amazon EC2 security groups (separating multiple secruity
groups with commas) into the EC2 Security Groups text box. You can do this either by using the AWS
Management Console or the AWS Toolkit for Visual Studio.
To create a security group using the AWS toolkit for Visual Studio
1. In Visual Studio, in AWS Explorer, expand the Amazon EC2 node, and then select Security Groups.
2. Select Create Security Group, and enter a name and description for your security group.
3. Select OK.
For more information on Amazon EC2 Security Groups, see Using Security Groups in the Amazon Elastic
Compute Cloud User Guide.
The Existing Key Pair text box lets you specify the name of an Amazon EC2 key pair that you can use to
securely log in to the Amazon EC2 instances that are running your Elastic Beanstalk application.
For more information about Amazon EC2 key pairs, go to Using Amazon EC2 Credentials in the Amazon
Elastic Compute Cloud User Guide. For more information about connecting to Amazon EC2 instances, see
Monitoring interval
By default, only basic Amazon CloudWatch metrics are enabled. They return data in five-minute periods.
You can enable more granular one-minute CloudWatch metrics by selecting 1 minute for the Monitoring
Interval in the Server section of the Configuration tab for your environment in the AWS Toolkit for
Eclipse.
Note
Amazon CloudWatch service charges can apply for one-minute interval metrics. See Amazon
CloudWatch for more information.
172
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Custom AMI ID
You can override the default AMI used for your Amazon EC2 instances with your own custom AMI by
entering the identifier of your custom AMI into the Custom AMI ID box in the Server section of the
Configuration tab for your environment in the AWS Toolkit for Eclipse.
Important
Using your own AMI is an advanced task that you should do with care. If you need a custom
AMI, we recommend you start with the default Elastic Beanstalk AMI and then modify it.
To be considered healthy, Elastic Beanstalk expects Amazon EC2 instances to meet a set of
requirements, including having a running host manager. If these requirements are not met, your
environment might not work properly.
Configuring Elastic Load Balancing using the AWS toolkit for Visual Studio
Elastic Load Balancing is an Amazon web service that helps you improve the availability and scalability
of your application. This service makes it easy for you to distribute application loads between two or
more Amazon EC2 instances. Elastic Load Balancing improves availability through providing additional
redundancy and supports traffic growth for your application.
With Elastic Load Balancing, you can automatically distribute and balance incoming application traffic
among all your running instances. You can also easily add new instances when increasing the capacity of
your application is required.
Elastic Beanstalk automatically provisions Elastic Load Balancing when you deploy an application. You
can edit the Elastic Beanstalk environment's Amazon EC2 instance configuration with the Load Balancer
tab inside your application environment tab in AWS Toolkit for Visual Studio.
The following sections describe the Elastic Load Balancing parameters you can configure for your
application.
Ports
The load balancer provisioned to handle requests for your Elastic Beanstalk application sends requests to
the Amazon EC2 instances that are running your application. The provisioned load balancer can listen for
173
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
requests on HTTP and HTTPS ports and route requests to the Amazon EC2 instances in your AWS Elastic
Beanstalk application. By default, the load balancer handles requests on the HTTP port. For this to work,
at least one of the ports (either HTTP or HTTPS) must be turned on.
Important
Make sure that the port that you specified is not locked down; otherwise, you won't be able to
connect to your Elastic Beanstalk application.
To turn off the HTTP port, select OFF for HTTP Listener Port. To turn on the HTTP port, you select an
HTTP port (for example, 80) from the list.
Note
To access your environment using a port other than the default port 80, such as port 8080, add
a listener to the existing load balancer and configure the new listener to listen on that port.
For example, using the AWS CLI for Classic load balancers, type the following command,
replacing LOAD_BALANCER_NAME with the name of your load balancer for Elastic Beanstalk.
For example, using the AWS CLI for Application Load Balancers, type the following command,
replacing LOAD_BALANCER_ARN with the ARN of your load balancer for Elastic Beanstalk.
If you want Elastic Beanstalk to monitor your environment, do not remove the listener on port
80.
Elastic Load Balancing supports the HTTPS/TLS protocol to enable traffic encryption for client
connections to the load balancer. Connections from the load balancer to the EC2 instances use plaintext
encryption. By default, the HTTPS port is turned off.
1. Create a new certificate using AWS Certificate Manager (ACM) or upload a certificate and key to AWS
Identity and Access Management (IAM). For more information about requesting an ACM certificate,
see Request a Certificate in the AWS Certificate Manager User Guide. For more information about
importing third-party certificates into ACM, see Importing Certificates in the AWS Certificate
Manager User Guide. If ACM is not available in your region, use AWS Identity and Access Management
(IAM) to upload a third-party certificate. The ACM and IAM services store the certificate and provide
an Amazon Resource Name (ARN) for the SSL certificate. For more information about creating and
uploading certificates to IAM, see Working with Server Certificates in IAM User Guide.
2. Specify the HTTPS port by selecting a port for HTTPS Listener Port.
174
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
3. For SSL Certificate ID, enter the Amazon Resources Name (ARN) of your
SSL certificate. For example, arn:aws:iam::123456789012:server-
certificate/abc/certs/build or arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678. Use the SSL
certificate that you created or uploaded in step 1.
To turn off the HTTPS port, select OFF for HTTPS Listener Port.
Health checks
The health check definition includes a URL to be queried for instance health. By default, Elastic Beanstalk
uses TCP:80 for nonlegacy containers and HTTP:80 for legacy containers. You can override the default
URL to match an existing resource in your application (for example, /myapp/default.aspx) by
entering it in the Application Health Check URL box. If you override the default URL, then Elastic
Beanstalk uses HTTP to query the resource. To check if you are using a legacy container type, see the
section called “Why are some platform versions marked legacy?” (p. 470)
You can control the settings for the health check using the EC2 Instance Health Check section of the
Load Balancing panel.
The health check definition includes a URL to be queried for instance health. Override the default URL to
match an existing resource in your application (for example, /myapp/index.jsp) by entering it in the
Application Health Check URL box.
The following list describes the health check parameters you can set for your application.
• For Health Check Interval (seconds), enter the number of seconds Elastic Load Balancing waits
between health checks for your application's Amazon EC2 instances.
• For Health Check Timeout (seconds), specify the number of seconds Elastic Load Balancing waits for a
response before it considers the instance unresponsive.
• For Healthy Check Count Threshold and Unhealthy Check Count Threshold, specify the number
of consecutive successful or unsuccessful URL probes before Elastic Load Balancing changes the
instance health status. For example, specifying 5 for Unhealthy Check Count Threshold means that
the URL must return an error message or timeout five consecutive times before Elastic Load Balancing
considers the health check as failed.
Sessions
By default, a load balancer routes each request independently to the server instance with the smallest
load. By comparison, a sticky session binds a user's session to a specific server instance so that all
requests coming from the user during the session are sent to the same server instance.
175
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Elastic Beanstalk uses load balancer–generated HTTP cookies when sticky sessions are enabled for an
application. The load balancer uses a special load balancer–generated cookie to track the application
instance for each request. When the load balancer receives a request, it first checks to see if this cookie
is present in the request. If it is present, the request is sent to the application instance that is specified
in the cookie. If there is no cookie, the load balancer chooses an application instance based on the
existing load balancing algorithm. A cookie is inserted into the response for binding subsequent requests
from the same user to that application instance. The policy configuration defines a cookie expiry, which
establishes the duration of validity for each cookie.
You can use the Sessions section on the Load Balancer tab to specify whether the load balancer for your
application allows session stickiness.
For more information on Elastic Load Balancing, see the Elastic Load Balancing Developer Guide.
Configuring Auto Scaling using the AWS toolkit for Visual Studio
Amazon EC2 Auto Scaling is an Amazon web service that is designed to automatically launch or
terminate Amazon EC2 instances based on user-defined triggers. You can set up Auto Scaling groups and
associate triggers with these groups to automatically scale computing resources based on metrics such
as bandwidth usage or CPU utilization. Amazon EC2 Auto Scaling works with Amazon CloudWatch to
retrieve metrics for the server instances running your application.
Amazon EC2 Auto Scaling lets you take a group of Amazon EC2 instances and set various parameters
to have this group automatically increase or decrease in number. Amazon EC2 Auto Scaling can add or
remove Amazon EC2 instances from that group to help you seamlessly deal with traffic changes to your
application.
Amazon EC2 Auto Scaling also monitors the health of each Amazon EC2 instance that it launches. If any
instance terminates unexpectedly, Amazon EC2 Auto Scaling detects the termination and launches a
replacement instance. This capability enables you to maintain a fixed, desired number of Amazon EC2
instances automatically.
Elastic Beanstalk provisions Amazon EC2 Auto Scaling for your application. You can edit the Elastic
Beanstalk environment's Amazon EC2 instance configuration with the Auto Scaling tab inside your
application environment tab in the AWS Toolkit for Visual Studio.
176
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
The following section discusses how to configure Auto Scaling parameters for your application.
The Minimum Instance Count and Maximum Instance Count boxes let you specify the minimum and
maximum size of the Auto Scaling group that your Elastic Beanstalk application uses.
Note
To maintain a fixed number of Amazon EC2 instances, set Minimum Instance Count and
Maximum Instance Count to the same value.
The Availability Zones box lets you specify the number of Availability Zones you want your Amazon EC2
instances to be in. It is important to set this number if you want to build fault-tolerant applications. If
one Availability Zone goes down, your instances will still run in your other Availability Zones.
Note
Currently, it is not possible to specify which Availability Zone your instance will be in.
177
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Triggers
A trigger is an Amazon EC2 Auto Scaling mechanism that you set to tell the system when you want to
increase (scale out) or decrease (scale in) the number of instances. You can configure triggers to fire
on any metric published to Amazon CloudWatch (for example, CPU utilization) and determine if the
conditions you specified have been met. When the upper or lower thresholds of the conditions you have
specified for the metric have been breached for the specified period of time, the trigger launches a long-
running process called a Scaling Activity.
You can define a scaling trigger for your Elastic Beanstalk application using AWS Toolkit for Visual
Studio.
Amazon EC2 Auto Scaling triggers work by monitoring a specific Amazon CloudWatch metric of a
particular instance. Metrics include CPU utilization, network traffic, and disk activity. Use the Trigger
Measurement setting to select a metric for your trigger.
The following list describes the trigger parameters you can configure using the AWS Management
Console.
• You can specify which statistic the trigger should use. You can select Minimum, Maximum, Sum, or
Average for Trigger Statistic.
• For Unit of Measurement, specify the unit for the trigger measurement.
• The value in the Measurement Period box specifies how frequently Amazon CloudWatch measures the
metrics for your trigger. The Breach Duration is the amount of time a metric can go beyond its defined
limit (as specified for the Upper Threshold and Lower Threshold) before the trigger fires.
• For Upper Breach Scale Increment and Lower Breach Scale Increment, specify how many Amazon
EC2 instances to add or remove when performing a scaling activity.
For more information on Amazon EC2 Auto Scaling, see the Amazon EC2 Auto Scaling section on Amazon
Elastic Compute Cloud Documentation.
178
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Configuring additional environment options using AWS toolkit for Visual Studio
Elastic Beanstalk defines a large number of configuration options that you can use to configure your
environment's behavior and the resources that it contains. Configuration options are organized into
namespaces like aws:autoscaling:asg. Each namespace defines options for an environment's Auto
Scaling group. The Advanced panel lists the configuration option namespaces in alphabetical order that
you can update after environment creation.
For a complete list of namespaces and options, including default and supported values for each, see
General options for all environments (p. 632) and .NET Core on Linux platform options (p. 677).
Configuring .NET Core containers using the AWS toolkit for Visual Studio
The Container panel lets you specify environment variables that you can read from your application
code.
179
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
For information about the health monitoring provided by Elastic Beanstalk, see Basic health
reporting (p. 773).
You can access operational information about your application by using either the AWSToolkit for Visual
Studio or the AWS Management Console.
The toolkit displays your environment's status and application health in the Status field.
1. In the AWS Toolkit for Visual Studio, in AWS Explorer, expand the Elastic Beanstalk node, and then
expand your application node.
2. Open the context (right-click) menu for your application environment and select View Status.
3. On your application environment tab, select Monitoring.
The Monitoring panel includes a set of graphs showing resource usage for your particular
application environment.
Note
By default, the time range is set to the last hour. To modify this setting, in the Time Range
list, select a different time range.
You can use the AWS Toolkit for Visual Studio or the AWS Management Console to view events
associated with your application.
180
AWS Elastic Beanstalk Developer Guide
Migration from Windows to Linux
1. In the AWS Toolkit for Visual Studio, in AWS Explorer, expand the Elastic Beanstalk node and your
application node.
2. Open the context (right-click) menu for your application environment and select View Status.
3. In your application environment tab, select Events.
Application On Windows platforms, you use a deployment manifest (p. 189) to specify the
configuration applications that run in your environment. The .NET Core on Linux platforms use
a Procfile (p. 158) to specify the applications that run on your environment's
instances. For details on bundling applications, see the section called “Bundling
applications” (p. 157).
Proxy server On Windows platforms, you use IIS as your application's proxy server. The .NET Core
on Linux platforms include nginx as a reverse proxy by default. You can choose to use
no proxy server and use Kestrel as your application's web server. To learn more, see the
section called “Proxy server” (p. 158).
Routing On Windows platforms, you use IIS in your application code and include a deployment
manifest (p. 189) to configure the IIS path. For the .NET Core on Linux platform, you
use ASP .NET Core routing in your application code, and update your environment's
nginx configuration. To learn more, see the section called “Proxy server” (p. 158).
Logs The Linux and Windows platforms stream different logs. For details, see the section
called “How Elastic Beanstalk sets up CloudWatch Logs” (p. 834).
181
AWS Elastic Beanstalk Developer Guide
Working with .NET
Get started now: To get started with a tutorial, you can go directly to Tutorial: How to deploy a .NET
sample application using Elastic Beanstalk (p. 194). In this tutorial, you will deploy a sample ASP.NET
Web Application to an AWS Elastic Beanstalk application container.
The rest of this section presents instructions for creating, testing, deploying, and redeploying your
ASP.NET web application to Elastic Beanstalk. Some examples demonstrate using the AWS Toolkit
for Visual Studio, and the section called “The AWS Toolkit for Visual Studio” (p. 212) subsection
explains how to manage and configure your applications and environments using the toolkit. For more
information about prerequisites, installation instructions, and running code samples, go to the AWS
Toolkit for Microsoft Visual Studio. This site also provides useful information about tools, how-to topics,
and additional resources for ASP.NET developers.
Note
This platform doesn't support the following Elastic Beanstalk features:
• Worker environments. For details, see Elastic Beanstalk worker environments (p. 482).
• Bundle logs. For details, see View instance logs (p. 820).
In addition, platform versions earlier than v2.0.0 don't support enhanced health reporting,
managed platform updates, immutable updates, immutable deployments, and rolling
deployments with an additional batch.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
Topics
• Getting started with .NET on Elastic Beanstalk (p. 182)
• Setting up your .NET development environment (p. 185)
• Using the Elastic Beanstalk .NET platform (p. 186)
• Tutorial: How to deploy a .NET sample application using Elastic Beanstalk (p. 194)
• Tutorial: Deploying an ASP.NET core application with Elastic Beanstalk (p. 201)
• Adding an Amazon RDS DB instance to your .NET application environment (p. 209)
• The AWS Toolkit for Visual Studio (p. 212)
• Migrating your on-premises .NET application to Elastic Beanstalk (p. 237)
• Resources (p. 238)
182
AWS Elastic Beanstalk Developer Guide
Getting started
Samples
WS 2012 R2
WS 2012
ASP.NET
WS 2012 R2 Web dotnet- ASP.NET web application with
MVC5 Serveraspmvc5-a classic model-view-control
v1.zip architecture.
Download any of the sample applications and deploy it to Elastic Beanstalk by using the following
procedure.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose an existing application's name in the
list or create one (p. 377).
3. On the application overview page, choose Create a new environment.
4. Next, for environment tier, choose the Web server environment or Worker environment
environment tier (p. 13). You can't change an environment's tier after creation.
183
AWS Elastic Beanstalk Developer Guide
Getting started
Note
The .NET on Windows Server platform (p. 182) doesn't support the worker environment
tier.
5. For Platform, select the platform and platform branch that match the language your application
uses.
Note
Elastic Beanstalk supports multiple versions (p. 29) for most of the platforms that are
listed. By default, the console selects the recommended version for the platform and
platform branch you choose. If your application requires a different version, you can select
it here, or choose Configure more options, as described in step 7. For information about
supported platform versions, see the section called “Supported platforms” (p. 29).
6. For Application code, choose Sample application.
7. To further customize your environment, choose Configure more options. You can set the following
options only during environment creation:
• Environment name
• Domain name
• Platform version
• Processor
• VPC
• Tier
You can change the following settings after environment creation, but they require new instances or
other resources to be provisioned and can take a long time to apply:
• Instance type, root volume, key pair, and AWS Identity and Access Management (IAM) role
• Internal Amazon RDS database
184
AWS Elastic Beanstalk Developer Guide
Development environment
• Load balancer
For details on all available settings, see The create new environment wizard (p. 409).
8. Choose Create environment.
Next steps
After you have an environment running an application, you can deploy a new version (p. 441) of the
application or a completely different application at any time. Deploying a new application version is
quick because it doesn't require provisioning or restarting EC2 instances.
After you've deployed a sample application or two and you're ready to start developing locally, you can
follow the instructions in the next section (p. 185) to set up a .NET development environment.
For common setup steps and tools that apply to all languages, see Configuring your development
machine for use with Elastic Beanstalk (p. 953).
Sections
• Installing an IDE (p. 154)
• Installing the AWS Toolkit for Visual Studio (p. 154)
If you need to manage AWS resources from within your application, install the AWS SDK for .NET. For
example, you can use Amazon S3 to store and retrieve data.
With the AWS SDK for .NET, you can get started in minutes with a single, downloadable package
complete with Visual Studio project templates, the AWS .NET library, C# code samples, and
documentation. Practical examples are provided in C# for how to use the libraries to build applications.
Online video tutorials and reference documentation are provided to help you learn how to use the
libraries and code samples.
Visit the AWS SDK for .NET homepage for more information and installation instructions.
Installing an IDE
Integrated development environments (IDEs) provide a wide range of features that facilitate application
development. If you haven't used an IDE for .NET development, try Visual Studio Community to get
started.
Visit the Visual Studio Community page to download and install Visual Studio Community.
185
AWS Elastic Beanstalk Developer Guide
The .NET platform
Elastic Beanstalk provides configuration options (p. 613) that you can use to customize the software
that runs on the EC2 instances in your Elastic Beanstalk environment. You can configure environment
variables needed by your application, enable log rotation to Amazon S3, and set .NET framework
settings.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Container options
• Target .NET runtime – Set to 2.0 to run CLR v2.
• Enable 32-bit applications – Set to True to run 32-bit applications.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
186
AWS Elastic Beanstalk Developer Guide
The .NET platform
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Environment properties
The Environment Properties section lets you specify environment configuration settings on the Amazon
EC2 instances that are running your application. These settings are passed in as key-value pairs to the
application. Use System.GetEnvironmentVariable to read them. Identical keys can exist in both
web.config and as environment properties. Use the System.Configuration namespace to read
values from web.config.
See Environment properties and other software settings (p. 590) for more information.
The following example configuration file shows settings for each of the options available in this
namespace:
Example .ebextensions/dotnet-settings.config
option_settings:
aws:elasticbeanstalk:container:dotnet:apppool:
Target Runtime: 2.0
Enable 32-bit Applications: True
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
The Windows Server platform is currently at version 2 (v2). If your application uses any Windows Server
platform version earlier than v2, we recommend that you migrate to v2.
Version 2 (v2) of the Elastic Beanstalk Windows Server platform was released in February 2019. V2
brings the behavior of the Windows Server platform closer to that of the Elastic Beanstalk Linux-based
187
AWS Elastic Beanstalk Developer Guide
The .NET platform
platforms in several important ways. V2 is fully backward compatible with v1, making migration from v1
easy.
• Versioning – Each release gets a new version number, and you can refer to past versions (that are still
available to you) when creating and managing environments.
• Enhanced health – For details, see Enhanced health reporting and monitoring (p. 776).
• Immutable and Rolling with an Additional Batch deployments – For details about deployment policies,
see Deploying applications to Elastic Beanstalk environments (p. 441).
• Immutable updates – For details about update types, see Configuration changes (p. 452).
• Managed platform updates – For details, see Managed platform updates (p. 464).
Note
The new deployment and update features depend on enhanced health. Enable enhanced health
to use them. For details, see Enabling Elastic Beanstalk enhanced health reporting (p. 784).
Version 1.0.0 (v1) of the Elastic Beanstalk Windows Server platform was released in October 2015. This
version changes the order in which Elastic Beanstalk processes commands in configuration files (p. 683)
during environment creation and updates.
Previous platform versions don't have a version number in the solution stack name:
In earlier versions, the processing order for configuration files is inconsistent. During environment
creation, Container Commands run after the application source is deployed to IIS. During a deployment
to a running environment, container commands run before the new version is deployed. During a scale
up, configuration files are not processed at all.
In addition to this, IIS starts up before container commands run. This behavior has led some customers
to implement workarounds in container commands, pausing the IIS server before commands run, and
starting it again after they complete.
Version 1 fixes the inconsistency and brings the behavior of the Windows Server platform closer to
that of the Elastic Beanstalk Linux-based platforms. In the v1 platform, Elastic Beanstalk always runs
container commands before starting the IIS server.
The v1 platform solution stacks have a v1 after the Windows Server version:
Additionally, the v1 platform extracts the contents of your application source bundle to C:\staging\
before running container commands. After container commands complete, the contents of this folder are
compressed into a .zip file and deployed to IIS. This workflow allows you to modify the contents of your
application source bundle with commands or a script before deployment.
188
AWS Elastic Beanstalk Developer Guide
The .NET platform
From V1 to V2
The Windows Server platform v2 doesn't support .NET Core 1.x and 2.0. If you're migrating your
application from Windows Server v1 to v2, and your application uses one of these .NET Core versions,
update your application to a .NET Core version that v2 supports. For a list of supported versions, see
.NET on Windows Server with IIS in the AWS Elastic Beanstalk Platforms.
If your application uses a custom Amazon Machine Image (AMI), create a new custom AMI based
on a Windows Server platform v2 AMI. To learn more, see Using a custom Amazon machine image
(AMI) (p. 729).
Note
The deployment and update features that are new to Windows Server v2 depend on enhanced
health. When you migrate an environment to v2, enhanced health is disabled. Enable it to use
these features. For details, see Enabling Elastic Beanstalk enhanced health reporting (p. 784).
From pre-V1
In addition to considerations for migrating from v1, if you're migrating your application from a Windows
Server solution stack that's earlier than v1, and you currently use container commands, remove any
commands that you added to work around the processing inconsistencies when you migrate to a newer
version. Starting with v1, container commands are guaranteed to run completely before the application
source that is deployed and before IIS starts. This enables you to make any changes to the source in C:
\staging and modify IIS configuration files during this step without issue.
For example, you can use the AWS CLI to download a DLL file to your application source from Amazon
S3:
.ebextensions\copy-dll.config
container_commands:
copy-dll:
command: aws s3 cp s3://DOC-EXAMPLE-BUCKET/dlls/large-dll.dll .\lib\
For more information on using configuration files, see Advanced environment customization with
configuration files (.ebextensions) (p. 683).
Deployment manifests add support for .NET Core applications (p. 190) to Elastic Beanstalk. You can
deploy a .NET Framework application without a deployment manifest. However, .NET Core applications
require a deployment manifest to run on Elastic Beanstalk. When you use a deployment manifest, you
create a site archive for each application, and then bundle the site archives in a second ZIP archive that
contains the deployment manifest.
189
AWS Elastic Beanstalk Developer Guide
The .NET platform
Deployment manifests also add the ability to run multiple applications at different paths (p. 191). A
deployment manifest defines an array of deployment targets, each with a site archive and a path at
which IIS should run it. For example, you could run a web API at the /api path to serve asynchronous
requests, and a web app at the root path that consumes the API.
You can also use a deployment manifest to run multiple applications using application pools in IIS or
Kestrel (p. 192). You can configure an application pool to restart your applications periodically, run 32-
bit applications, or use a specific version of the .NET Framework runtime.
For full customization, you can write your own deployment scripts (p. 194) in Windows PowerShell and
tell Elastic Beanstalk which scripts to run to install, uninstall, and restart your application.
Deployment manifests and related features require a Windows Server platform version 1.2.0 or
newer (p. 187).
Sections
• .NET core apps (p. 190)
• Run multiple applications (p. 191)
• Configure application pools (p. 192)
• Define custom deployments (p. 194)
To run a .NET Core application on Elastic Beanstalk, you can run dotnet publish and package the
output in a ZIP archive, not including any containing directories. Place the site archive in a source bundle
with a deployment manifest with a deployment target of type aspNetCoreWeb.
The following deployment manifest runs a .NET Core application from a site archive named dotnet-
core-app.zip at the root path.
{
"manifestVersion": 1,
"deployments": {
"aspNetCoreWeb": [
{
"name": "my-dotnet-core-app",
"parameters": {
"archive": "dotnet-core-app.zip",
"iisPath": "/"
}
}
]
}
}
Bundle the manifest and site archive in a ZIP archive to create a source bundle.
190
AWS Elastic Beanstalk Developer Guide
The .NET platform
Example dotnet-core-bundle.zip
.
|-- aws-windows-deployment-manifest.json
`-- dotnet-core-app.zip
The site archive contains the compiled application code, dependencies, and web.config file.
Example dotnet-core-app.zip
.
|-- Microsoft.AspNetCore.Hosting.Abstractions.dll
|-- Microsoft.AspNetCore.Hosting.Server.Abstractions.dll
|-- Microsoft.AspNetCore.Hosting.dll
|-- Microsoft.AspNetCore.Http.Abstractions.dll
|-- Microsoft.AspNetCore.Http.Extensions.dll
|-- Microsoft.AspNetCore.Http.Features.dll
|-- Microsoft.AspNetCore.Http.dll
|-- Microsoft.AspNetCore.HttpOverrides.dll
|-- Microsoft.AspNetCore.Server.IISIntegration.dll
|-- Microsoft.AspNetCore.Server.Kestrel.dll
|-- Microsoft.AspNetCore.WebUtilities.dll
|-- Microsoft.Extensions.Configuration.Abstractions.dll
|-- Microsoft.Extensions.Configuration.EnvironmentVariables.dll
|-- Microsoft.Extensions.Configuration.dll
|-- Microsoft.Extensions.DependencyInjection.Abstractions.dll
|-- Microsoft.Extensions.DependencyInjection.dll
|-- Microsoft.Extensions.FileProviders.Abstractions.dll
|-- Microsoft.Extensions.FileProviders.Physical.dll
|-- Microsoft.Extensions.FileSystemGlobbing.dll
|-- Microsoft.Extensions.Logging.Abstractions.dll
|-- Microsoft.Extensions.Logging.dll
|-- Microsoft.Extensions.ObjectPool.dll
|-- Microsoft.Extensions.Options.dll
|-- Microsoft.Extensions.PlatformAbstractions.dll
|-- Microsoft.Extensions.Primitives.dll
|-- Microsoft.Net.Http.Headers.dll
|-- System.Diagnostics.Contracts.dll
|-- System.Net.WebSockets.dll
|-- System.Text.Encodings.Web.dll
|-- dotnet-core-app.deps.json
|-- dotnet-core-app.dll
|-- dotnet-core-app.pdb
|-- dotnet-core-app.runtimeconfig.json
`-- web.config
The following deployment manifest configures two .NET Core applications. The WebAPITest application
implements a few web APIs and serves asynchronous requests at the /api path. The ASPNetTest
application is a web application that serves requests at the root path.
{
"manifestVersion": 1,
191
AWS Elastic Beanstalk Developer Guide
The .NET platform
"deployments": {
"aspNetCoreWeb": [
{
"name": "WebAPITest",
"parameters": {
"appBundle": "webapi.zip",
"iisPath": "/api"
}
},
{
"name": "ASPNetTest",
"parameters": {
"appBundle": "aspnet.zip",
"iisPath": "/"
}
}
]
}
}
• You can use the out-of-process hosting model with the Kestrel web server. With this model, you
configure multiple applications to run in one application pool.
• You can use the in-process hosting model.With this model, you use multiple application pools to run
multiple applications with only one application in each pool. If you're using IIS server and need to run
multiple applications, you must use this approach.
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add
name="aspNetCore"
path="*" verb="*"
modules="AspNetCoreModuleV2"
resourceType="Unspecified" />
</handlers>
<aspNetCore
processPath="dotnet"
arguments=".\CoreWebApp-5-0.dll"
stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout"
hostingModel="OutofProcess" />
</system.webServer>
</location>
</configuration>
192
AWS Elastic Beanstalk Developer Guide
The .NET platform
{
"manifestVersion": 1,
"deployments": {"msDeploy": [
{"name": "Web-app1",
"parameters": {"archive": "site1.zip",
"iisPath": "/"
}
},
{"name": "Web-app2",
"parameters": {"archive": "site2.zip",
"iisPath": "/app2"
}
}
]
}
}
IIS doesn't support multiple applications in one application pool because it uses the in-process hosting
model. Therefore, you need to configure multiple applications by assigning each application to one
application pool. In other words, assign only one application to one application pool.
You can configure IIS to use different application pools in the aws-windows-deployment-
manifest.json file. Make the following updates as you refer to the next example file:
The following deployment manifest configures two application pools that restart their application every
10 minutes. They also attach their applications to a .NET Framework web application that runs at the
path specified.
{
"manifestVersion": 1,
"iisConfig": {"appPools": [
{"name": "MyFirstPool",
"recycling": {"regularTimeInterval": 10}
},
{"name": "MySecondPool",
"recycling": {"regularTimeInterval": 10}
}
]
},
"deployments": {"msDeploy": [
{"name": "Web-app1",
"parameters": {
"archive": "site1.zip",
"iisPath": "/",
"appPool": "MyFirstPool"
}
},
{"name": "Web-app2",
"parameters": {
"archive": "site2.zip",
193
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
"iisPath": "/app2",
"appPool": "MySecondPool"
}
}
]
}
}
The following deployment manifest tells Elastic Beanstalk to run an install script named
siteInstall.ps1. This script installs the website during instance launch and deployments. In addition
to this, the deployment manifest also tells Elastic Beanstalk to run an uninstall script before installing
a new version during a deployment and a restart script to restart the application when you choose
Restart App Server (p. 399) in the AWS management console.
{
"manifestVersion": 1,
"deployments": {
"custom": [
{
"name": "Custom site",
"scripts": {
"install": {
"file": "siteInstall.ps1"
},
"restart": {
"file": "siteRestart.ps1"
},
"uninstall": {
"file": "siteUninstall.ps1"
}
}
}
]
}
}
Include any artifacts required to run the application in your source bundle with the manifest and scripts.
Example Custom-site-bundle.zip
.
|-- aws-windows-deployment-manifest.json
|-- siteInstall.ps1
|-- siteRestart.ps1
|-- siteUninstall.ps1
`-- site-contents.zip
194
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
Note
This tutorial uses a sample ASP.NET Web application that you can download here. It also uses
the Toolkit for Visual Studio and was tested using Visual Studio Professional 2012.
When the environment is up and running, add an Amazon RDS database instance that the application
uses to store data. For DB engine, choose sqlserver-ex.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
1. Ensure that your environment launched successfully by checking the Health status in the Elastic
Beanstalk console. It should be Ok (green).
2. In Visual Studio, open BeanstalkDotNetSample.sln.
Note
If you haven't done so already, you can get the sample here.
3. On the View menu, choose Solution Explorer.
4. Expand Solution ‘BeanstalkDotNetSample’ (2 projects).
5. Open the context (right-click) menu for MVC5App, and then choose Publish to AWS.
195
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
6. On the Publish to AWS Elastic Beanstalk page, for Deployment Target, choose the environment
that you just created, and then choose Next.
196
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
7. On the Application Options page, accept all of the defaults, and then choose Next.
197
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
198
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
9. If you want to monitor deployment status, use the NuGet Package Manager in Visual Studio.
When the application has successfully been deployed, the Output box displays completed
successfully.
199
AWS Elastic Beanstalk Developer Guide
Tutorial - ASP.NET MVC5
10. Return to the Elastic Beanstalk console. In the navigation pane, choose Go to environment.
If you are done working with Elastic Beanstalk for now, you can terminate your .NET environment.
200
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions and then choose Terminate environment.
Elastic Beanstalk cleans up all AWS resources associated with your environment, including EC2 instances,
DB instance, load balancer, security groups, CloudWatch alarms, etc.
For more information, see Creating and deploying .NET applications on Elastic Beanstalk (p. 182), the
AWS .NET Development Blog , or the AWS Application Management Blog.
First, you will use the .NET Core SDK's dotnet command line tool to generate a basic .NET Core
command line application, install dependencies, compile code, and run applications locally. Next, you will
create the default Program.cs class, and add an ASP.NET Startup.cs class and configuration files to
make an application that serves HTTP requests with ASP.NET and IIS.
Finally, Elastic Beanstalk uses a deployment manifest (p. 189) to configure deployments for .NET
Core applications, custom applications, and multiple .NET Core or MSBuild applications on a single
server. To deploy a .NET Core application to a Windows Server environment, you add a site archive to
an application source bundle with a deployment manifest. The dotnet publish command generates
compiled classes and dependencies that you can bundle with a web.config file to create a site archive.
The deployment manifest tells Elastic Beanstalk the path at which the site should run and can be used to
configure application pools and run multiple applications at different paths.
Sections
• Prerequisites (p. 201)
• Generate a .NET core project (p. 202)
• Launch an Elastic Beanstalk environment (p. 203)
• Update the source code (p. 203)
• Deploy your application (p. 208)
• Cleanup (p. 209)
• Next steps (p. 209)
Prerequisites
This tutorial uses the .NET Core SDK to generate a basic .NET Core application, run it locally, and build a
deployable package.
201
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
Requirements
1. Download the installer from microsoft.com/net/core. Choose Windows. Choose Download .NET
SDK.
2. Run the installer and follow the instructions.
This tutorial uses a command line ZIP utility to create a source bundle that you can deploy to Elastic
Beanstalk. To use the zip command in Windows, you can install UnxUtils, a lightweight collection of
useful command line utilities like zip and ls. Alternatively, you can use Windows Explorer (p. 386) or
any other ZIP utility to create source bundle archives.
To install UnxUtils
1. Download UnxUtils.
2. Extract the archive to a local directory. For example, C:\Program Files (x86).
3. Add the path to the binaries to your Windows PATH user variable. For example, C:\Program Files
(x86)\UnxUtils\usr\local\wbin.
> zip -h
Copyright (C) 1990-1999 Info-ZIP
Type 'zip "-L"' for software license.
...
1. Open a new command prompt window and navigate to your user folder.
> cd %USERPROFILE%
2. Use the dotnet new command to generate a new .NET Core project.
202
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
C:\Users\username> cd dotnet-core-tutorial
4. Use the dotnet run command to build and run the application locally.
Environment creation takes about 10 minutes. During this time you can update your source code.
203
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
Example c:\users\username\dotnet-core-tutorial\Program.cs
using System;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace aspnetcoreapp
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
Example c:\users\username\dotnet-core-tutorial\Startup.cs
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace aspnetcoreapp
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
return context.Response.WriteAsync("Hello from ASP.NET Core!");
});
}
}
}
204
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
Example c:\users\username\dotnet-core-tutorial\web.config
Example c:\users\username\dotnet-core-tutorial\dotnet-core-tutorial.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel"
Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration"
Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<None Include="web.config" CopyToPublishDirectory="Always" />
</ItemGroup>
</Project>
Next, install the new dependencies and run the ASP.NET website locally.
205
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
To run the application on a web server, you need to bundle the compiled source code with a
web.config configuration file and runtime dependencies. The dotnet tool provides a publish
command that gathers these files in a directory based on the configuration in dotnet-core-
tutorial.csproj.
• Use the dotnet publish command to output compiled code and dependencies to a folder named
site.
To deploy the application to Elastic Beanstalk, bundle the site archive with a deployment
manifest (p. 189). This tells Elastic Beanstalk how to run it.
C:\users\username\dotnet-core-tutorial> cd site
C:\users\username\dotnet-core-tutorial\site> zip ../site.zip *
adding: dotnet-core-tutorial.deps.json (164 bytes security) (deflated 84%)
adding: dotnet-core-tutorial.dll (164 bytes security) (deflated 59%)
adding: dotnet-core-tutorial.pdb (164 bytes security) (deflated 28%)
adding: dotnet-core-tutorial.runtimeconfig.json (164 bytes security) (deflated 26%)
adding: Microsoft.AspNetCore.Authentication.Abstractions.dll (164 bytes security)
(deflated 49%)
adding: Microsoft.AspNetCore.Authentication.Core.dll (164 bytes security) (deflated
57%)
adding: Microsoft.AspNetCore.Connections.Abstractions.dll (164 bytes security)
(deflated 51%)
adding: Microsoft.AspNetCore.Hosting.Abstractions.dll (164 bytes security) (deflated
49%)
adding: Microsoft.AspNetCore.Hosting.dll (164 bytes security) (deflated 60%)
adding: Microsoft.AspNetCore.Hosting.Server.Abstractions.dll (164 bytes security)
(deflated 44%)
adding: Microsoft.AspNetCore.Http.Abstractions.dll (164 bytes security) (deflated
54%)
adding: Microsoft.AspNetCore.Http.dll (164 bytes security) (deflated 55%)
adding: Microsoft.AspNetCore.Http.Extensions.dll (164 bytes security) (deflated 50%)
adding: Microsoft.AspNetCore.Http.Features.dll (164 bytes security) (deflated 50%)
adding: Microsoft.AspNetCore.HttpOverrides.dll (164 bytes security) (deflated 49%)
adding: Microsoft.AspNetCore.Server.IISIntegration.dll (164 bytes security) (deflated
46%)
adding: Microsoft.AspNetCore.Server.Kestrel.Core.dll (164 bytes security) (deflated
63%)
adding: Microsoft.AspNetCore.Server.Kestrel.dll (164 bytes security) (deflated 46%)
adding: Microsoft.AspNetCore.Server.Kestrel.Https.dll (164 bytes security) (deflated
44%)
adding: Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll (164 bytes
security) (deflated 56%)
adding: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.dll (164 bytes
security) (deflated 51%)
adding: Microsoft.AspNetCore.WebUtilities.dll (164 bytes security) (deflated 55%)
adding: Microsoft.Extensions.Configuration.Abstractions.dll (164 bytes security)
(deflated 48%)
206
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
Example c:\users\username\dotnet-core-tutorial\aws-windows-deployment-
manifest.json
{
"manifestVersion": 1,
"deployments": {
"aspNetCoreWeb": [
{
"name": "test-dotnet-core",
"parameters": {
"appBundle": "site.zip",
"iisPath": "/",
"iisWebSite": "Default Web Site"
}
}
]
}
}
207
AWS Elastic Beanstalk Developer Guide
Tutorial - .NET core
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
The application simply writes Hello from ASP.NET Core! to the response and returns.
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
208
AWS Elastic Beanstalk Developer Guide
Adding a database
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and isn't
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
As you continue to develop your application, you'll probably want to manage environments and deploy
your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console.
The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use commands for
creating, configuring, and deploying applications to Elastic Beanstalk environments from the command
line.
If you use Visual Studio to develop your application, you can also use the AWS Toolkit for Visual Studio
to deploy changed, manage your Elastic Beanstalk environments, and manage other AWS resources. See
The AWS Toolkit for Visual Studio (p. 212) for more information.
For developing and testing, you might want to use the Elastic Beanstalk functionality for adding a
managed DB instance directly to your environment. For instructions on setting up a database inside your
environment, see Adding a database to your Elastic Beanstalk environment (p. 577).
Finally, if you plan to use your application in a production environment, configure a custom domain
name (p. 612) for your environment and enable HTTPS (p. 734) for secure connections.
209
AWS Elastic Beanstalk Developer Guide
Adding a database
If you are using Amazon RDS for the first time, add a DB instance (p. 210) to a test environment with
the Elastic Beanstalk console and verify that your application can connect to it.
To connect to a database, add the driver (p. 211) to your application, load the driver class in your code,
and create a connection string (p. 211) with the environment properties provided by Elastic Beanstalk.
The configuration and connection code vary depending on the database engine and framework that you
use.
Sections
• Adding a DB instance to your environment (p. 210)
• Downloading a driver (p. 211)
• Connecting to a database (p. 211)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577).
210
AWS Elastic Beanstalk Developer Guide
Adding a database
Downloading a driver
Download and install the EntityFramework package and a database driver for your development
environment with NuGet.
Connecting to a database
Elastic Beanstalk provides connection information for attached DB instances in environment properties.
Use ConfigurationManager.AppSettings to read the properties and configure a database
connection.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace MVC5App.Models
{
public class Helpers
{
public static string GetRDSConnectionString()
{
var appConfig = ConfigurationManager.AppSettings;
Example DBContext.cs
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace MVC5App.Models
211
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
{
public class RDSContext : DbContext
{
public RDSContext()
: base(GetRDSConnectionString())
{
}
1. In Visual Studio, on the File menu, click New and then click Project.
2. In the New Project dialog box, click Installed Templates, click Visual C#, and then click Web. Click
ASP.NET Empty Web Application, type a project name, and then click OK.
To run a project
Do one of the following:
1. Press F5.
2. Select Start Debugging from the Debug menu.
Test locally
Visual Studio makes it easy for you to test your application locally. To test or run ASP.NET web
applications, you need a web server. Visual Studio offers several options, such as Internet Information
Services (IIS), IIS Express, or the built-in Visual Studio Development Server. To learn about each of these
options and to decide which one is best for you, see Web Servers in Visual Studio for ASP.NET Web
Projects.
To deploy your application to Elastic Beanstalk using the AWS toolkit for Visual Studio
1. In Solution Explorer, right-click your application and then select Publish to AWS.
212
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
a. For AWS account to use for deployment, select your account or select Other to enter new
account information.
b. For Region, select the region where you want to deploy your application. For information about
available AWS Regions, see AWS Elastic Beanstalk Endpoints and Quotas in the AWS General
Reference. If you select a region that is not supported by Elastic Beanstalk, then the option to
deploy to Elastic Beanstalk will become unavailable.
c. Click Deploy new application with template and select Elastic Beanstalk. Then click Next.
213
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
e. Click Next.
4. On the Environment page, describe your environment details.
You can select either Load balanced, auto scaled or a Single instance environment. For more
information, see Environment types (p. 480).
Note
For single-instance environments, load balancing, auto scaling, and the health check
URL settings don't apply.
e. The environment URL automatically appears in the Environment URL once you move your
cursor to that box.
f. Click Check availability to make sure the environment URL is available.
214
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
g. Click Next.
5. On the AWS Options page, configure additional options and security information for your
deployment.
a. For Container Type, select 64bit Windows Server 2012 running IIS 8 or 64bit Windows Server
2008 running IIS 7.5.
b. For Instance Type, select Micro.
c. For Key pair, select Create new key pair. Type a name for the new key pair—in this example, we
use myuswestkeypair—and then click OK. A key pair enables remote-desktop access to your
Amazon EC2 instances. For more information on Amazon EC2 key pairs, see Using Credentials in
the Amazon Elastic Compute Cloud User Guide.
d. Select an instance profile.
If you do not have an instance profile, select Create a default instance profile. For information
about using instance profiles with Elastic Beanstalk, see Managing Elastic Beanstalk instance
profiles (p. 855).
e. If you have a custom VPC that you would like to use with your environment, click Launch
into VPC. You can configure the VPC information on the next page. For more information
about Amazon VPC, go to Amazon Virtual Private Cloud (Amazon VPC). For a list of supported
nonlegacy container types, see the section called “Why are some platform versions marked
legacy?” (p. 470)
215
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
f. Click Next.
6. If you selected to launch your environment inside a VPC, the VPC Options page appears; otherwise,
the Additional Options page appears. Here you'll configure your VPC options.
216
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
217
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
a. Select the VPC ID of the VPC in which you would like to launch your environment.
b. For a load-balanced, scalable environment, select private for ELB Scheme if you do not want
your elastic load balancer to be available to the Internet.
For a single-instance environment, this option is not applicable because the environment
doesn't have a load balancer. For more information, see Environment types (p. 480).
c. For a load-balanced, scalable environment, select the subnets for the elastic load balancer and
the EC2 instances. If you created public and private subnets, make sure the elastic load balancer
and the EC2 instances are associated with the correct subnet. By default, Amazon VPC creates
a default public subnet using 10.0.0.0/24 and a private subnet using 10.0.1.0/24. You can view
your existing subnets in the Amazon VPC console at https://console.aws.amazon.com/vpc/.
For a single-instance environment, your VPC only needs a public subnet for the instance.
Selecting a subnet for the load balancer is not applicable because the environment doesn't have
a load balancer. For more information, see Environment types (p. 480).
d. For a load-balanced, scalable environment, select the security group you created for your
instances, if applicable.
For a single-instance environment, you don't need a NAT device. Select the default security
group. Elastic Beanstalk assigns an Elastic IP address to the instance that lets the instance access
the Internet.
e. Click Next.
218
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
f. Click Next.
8. If you have previously set up an Amazon RDS database, the Amazon RDS DB Security Group
page appears. If you want to connect your Elastic Beanstalk environment to your Amazon RDS DB
Instance, then select one or more security groups. Otherwise, go on to the next step. When you're
ready, click Next.
219
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Your ASP.NET project will be exported as a web deploy file, uploaded to Amazon S3, and registered
as a new application version with Elastic Beanstalk. The Elastic Beanstalk deployment feature
will monitor your environment until it becomes available with the newly deployed code. On the
env:<environment name> tab, you will see status for your environment.
220
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Terminating an environment
To avoid incurring charges for unused AWS resources, you can terminate a running environment using
the AWS Toolkit for Visual Studio.
Note
You can always launch a new environment using the same version later.
To terminate an environment
1. Expand the Elastic Beanstalk node and the application node in AWS Explorer. Right-click your
application environment and select Terminate Environment.
2. When prompted, click Yes to confirm that you want to terminate the environment. It will take a few
minutes for Elastic Beanstalk to terminate the AWS resources running in the environment.
Note
When you terminate your environment, the CNAME associated with the terminated
environment becomes available for anyone to use.
1. In Solution Explorer, right-click your application, and then click Republish to Environment <your
environment name>. The Re-publish to AWS Elastic Beanstalk wizard opens.
221
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Your updated ASP.NET web project will be exported as a web deploy file with the new version label,
uploaded to Amazon S3, and registered as a new application version with Elastic Beanstalk. The
Elastic Beanstalk deployment feature monitors your existing environment until it becomes available
with the newly deployed code. On the env:<environment name> tab, you will see the status of
your environment.
You can also deploy an existing application to an existing environment if, for instance, you need to roll
back to a previous application version.
1. Right-click your Elastic Beanstalk application by expanding the Elastic Beanstalk node in AWS
Explorer. Select View Status.
2. In the App: <application name> tab, click Versions.
3. Click the application version you want to deploy and click Publish Version.
4. In the Publish Application Version wizard, click Next.
222
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Your ASP.NET project will be exported as a web deploy file and uploaded to Amazon S3. The Elastic
Beanstalk deployment feature will monitor your environment until it becomes available with
the newly deployed code. On the env:<environment name> tab, you will see status for your
environment.
223
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Managing environments (p. 396). This section discusses the specific service settings you can edit in the
AWS Toolkit for Visual Studio as part of your application environment configuration.
• Expand the Elastic Beanstalk node and your application node. Then right-click your Elastic Beanstalk
environment in AWS Explorer. Select View Status.
• Server
• Load balancing
• Autoscaling
• Notifications
• Environment properties
Configuring EC2 server instances using the AWS toolkit for Visual Studio
Amazon Elastic Compute Cloud (Amazon EC2) is a web service that you use to launch and manage server
instances in Amazon's data centers. You can use Amazon EC2 server instances at any time, for as long
as you need, and for any legal purpose. Instances are available in different sizes and configurations. For
more information, go to Amazon EC2.
You can edit the Elastic Beanstalk environment's Amazon EC2 instance configuration with the Server tab
inside your application environment tab in the AWS Toolkit for Visual Studio.
Instance type displays the instance types available to your Elastic Beanstalk application. Change the
instance type to select a server with the characteristics (including memory size and CPU power) that
224
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
are most appropriate to your application. For example, applications with intensive and long-running
operations can require more CPU or memory.
For more information about the Amazon EC2 instance types available for your Elastic Beanstalk
application, see Instance Types in the Amazon Elastic Compute Cloud User Guide.
You can control access to your Elastic Beanstalk application using an Amazon EC2 Security Group. A
security group defines firewall rules for your instances. These rules specify which ingress (i.e., incoming)
network traffic should be delivered to your instance. All other ingress traffic will be discarded. You can
modify rules for a group at any time. The new rules are automatically enforced for all running instances
and instances launched in the future.
You can set up your Amazon EC2 security groups using the AWS Management Console or by using the
AWS Toolkit for Visual Studio. You can specify which Amazon EC2 Security Groups control access to your
Elastic Beanstalk application by entering the names of one or more Amazon EC2 security group names
(delimited by commas) into the EC2 Security Groups text box.
Note
Make sure port 80 (HTTP) is accessible from 0.0.0.0/0 as the source CIDR range if you want to
enable health checks for your application. For more information about health checks, see Health
checks (p. 228).
To create a security group using the AWS toolkit for Visual Studio
1. In Visual Studio, in AWS Explorer, expand the Amazon EC2 node, and then double-click Security
Groups.
2. Click Create Security Group, and enter a name and description for your security group.
3. Click OK.
For more information on Amazon EC2 Security Groups, see Using Security Groups in the Amazon Elastic
Compute Cloud User Guide.
You can securely log in to the Amazon EC2 instances provisioned for your Elastic Beanstalk application
with an Amazon EC2 key pair.
Important
You must create an Amazon EC2 key pair and configure your Elastic Beanstalk–provisioned
Amazon EC2 instances to use the Amazon EC2 key pair before you can access your Elastic
Beanstalk–provisioned Amazon EC2 instances. You can create your key pair using the Publish to
AWS wizard inside the AWS Toolkit for Visual Studio when you deploy your application to Elastic
Beanstalk. If you want to create additional key pairs using the Toolkit, follow the steps below.
Alternatively, you can set up your Amazon EC2 key pairs using the AWS Management Console.
For instructions on creating a key pair for Amazon EC2, see the Amazon Elastic Compute Cloud
Getting Started Guide.
The Existing Key Pair text box lets you specify the name of an Amazon EC2 key pair you can use to
securely log in to the Amazon EC2 instances running your Elastic Beanstalk application.
225
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
For more information about Amazon EC2 key pairs, go to Using Amazon EC2 Credentials in the Amazon
Elastic Compute Cloud User Guide. For more information about connecting to Amazon EC2 instances, see
Listing and connecting to server instances (p. 234).
Monitoring interval
By default, only basic Amazon CloudWatch metrics are enabled. They return data in five-minute periods.
You can enable more granular one-minute CloudWatch metrics by selecting 1 minute for the Monitoring
Interval in the Server section of the Configuration tab for your environment in the AWS Toolkit for
Eclipse.
Note
Amazon CloudWatch service charges can apply for one-minute interval metrics. See Amazon
CloudWatch for more information.
Custom AMI ID
You can override the default AMI used for your Amazon EC2 instances with your own custom AMI by
entering the identifier of your custom AMI into the Custom AMI ID box in the Server section of the
Configuration tab for your environment in the AWS Toolkit for Eclipse.
Important
Using your own AMI is an advanced task that you should do with care. If you need a custom
AMI, we recommend you start with the default Elastic Beanstalk AMI and then modify it.
To be considered healthy, Elastic Beanstalk expects Amazon EC2 instances to meet a set of
requirements, including having a running host manager. If these requirements are not met, your
environment might not work properly.
Configuring Elastic Load Balancing using the AWS toolkit for Visual Studio
Elastic Load Balancing is an Amazon web service that helps you improve the availability and scalability of
your application. This service makes it easy for you to distribute application loads between two or more
Amazon EC2 instances. Elastic Load Balancing enables availability through redundancy and supports
traffic growth for your application.
Elastic Load Balancing lets you automatically distribute and balance the incoming application traffic
among all the instances you are running. The service also makes it easy to add new instances when you
need to increase the capacity of your application.
Elastic Beanstalk automatically provisions Elastic Load Balancing when you deploy an application. You
can edit the Elastic Beanstalk environment's Amazon EC2 instance configuration with the Load Balancer
tab inside your application environment tab in AWS Toolkit for Visual Studio.
226
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
The following sections describe the Elastic Load Balancing parameters you can configure for your
application.
Ports
The load balancer provisioned to handle requests for your Elastic Beanstalk application sends requests to
the Amazon EC2 instances that are running your application. The provisioned load balancer can listen for
requests on HTTP and HTTPS ports and route requests to the Amazon EC2 instances in your AWS Elastic
Beanstalk application. By default, the load balancer handles requests on the HTTP port. At least one of
the ports (either HTTP or HTTPS) must be turned on.
Important
Make sure that the port you specified is not locked down; otherwise, users will not be able to
connect to your Elastic Beanstalk application.
For example, using the AWS CLI for Application Load Balancers, type the following command,
replacing LOAD_BALANCER_ARN with the ARN of your load balancer for Elastic Beanstalk.
227
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
If you want Elastic Beanstalk to monitor your environment, do not remove the listener on port
80.
Elastic Load Balancing supports the HTTPS/TLS protocol to enable traffic encryption for client
connections to the load balancer. Connections from the load balancer to the EC2 instances use plaintext
encryption. By default, the HTTPS port is turned off.
1. Create a new certificate using AWS Certificate Manager (ACM) or upload a certificate and key to AWS
Identity and Access Management (IAM). For more information about requesting an ACM certificate,
see Request a Certificate in the AWS Certificate Manager User Guide. For more information about
importing third-party certificates into ACM, see Importing Certificates in the AWS Certificate
Manager User Guide. If ACM is not available in your region, use AWS Identity and Access Management
(IAM) to upload a third-party certificate. The ACM and IAM services store the certificate and provide
an Amazon Resource Name (ARN) for the SSL certificate. For more information about creating and
uploading certificates to IAM, see Working with Server Certificates in IAM User Guide.
2. Specify the HTTPS port by selecting a port for HTTPS Listener Port.
3. For SSL Certificate ID, enter the Amazon Resources Name (ARN) of your
SSL certificate. For example, arn:aws:iam::123456789012:server-
certificate/abc/certs/build or arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678. Use the SSL
certificate that you created or uploaded in step 1.
To turn off the HTTPS port, select OFF for HTTPS Listener Port.
Health checks
The health check definition includes a URL to be queried for instance health. By default, Elastic Beanstalk
uses TCP:80 for nonlegacy containers and HTTP:80 for legacy containers. You can override the default
URL to match an existing resource in your application (e.g., /myapp/default.aspx) by entering it in
the Application Health Check URL box. If you override the default URL, then Elastic Beanstalk uses
HTTP to query the resource. To check if you are using a legacy container type, see the section called
“Why are some platform versions marked legacy?” (p. 470)
You can control the settings for the health check using the EC2 Instance Health Check section of the
Load Balancing panel.
228
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
The health check definition includes a URL to be queried for instance health. Override the default
URL to match an existing resource in your application (e.g., /myapp/index.jsp) by entering it in the
Application Health Check URL box.
The following list describes the health check parameters you can set for your application.
• For Health Check Interval (seconds), enter the number of seconds Elastic Load Balancing waits
between health checks for your application's Amazon EC2 instances.
• For Health Check Timeout (seconds), specify the number of seconds Elastic Load Balancing waits for a
response before it considers the instance unresponsive.
• For Healthy Check Count Threshold and Unhealthy Check Count Threshold, specify the number of
consecutive successful or unsuccessful URL probes before Elastic Load Balancing changes the instance
health status. For example, specifying 5 for Unhealthy Check Count Threshold means that the URL
would have to return an error message or timeout five consecutive times before Elastic Load Balancing
considers the health check failed.
Sessions
By default, a load balancer routes each request independently to the server instance with the smallest
load. By comparison, a sticky session binds a user's session to a specific server instance so that all
requests coming from the user during the session are sent to the same server instance.
Elastic Beanstalk uses load balancer–generated HTTP cookies when sticky sessions are enabled for an
application. The load balancer uses a special load balancer–generated cookie to track the application
instance for each request. When the load balancer receives a request, it first checks to see if this cookie
is present in the request. If so, the request is sent to the application instance specified in the cookie.
If there is no cookie, the load balancer chooses an application instance based on the existing load
balancing algorithm. A cookie is inserted into the response for binding subsequent requests from
the same user to that application instance. The policy configuration defines a cookie expiry, which
establishes the duration of validity for each cookie.
You can use the Sessions section on the Load Balancer tab to specify whether or not the load balancer
for your application allows session stickiness.
For more information on Elastic Load Balancing, go to the Elastic Load Balancing Developer Guide.
Configuring Auto Scaling using the AWS toolkit for Visual Studio
Amazon EC2 Auto Scaling is an Amazon web service designed to automatically launch or terminate
Amazon EC2 instances based on user-defined triggers. Users can set up Auto Scaling groups and
associate triggers with these groups to automatically scale computing resources based on metrics such
as bandwidth usage or CPU utilization. Amazon EC2 Auto Scaling works with Amazon CloudWatch to
retrieve metrics for the server instances running your application.
Amazon EC2 Auto Scaling lets you take a group of Amazon EC2 instances and set various parameters
to have this group automatically increase or decrease in number. Amazon EC2 Auto Scaling can add or
remove Amazon EC2 instances from that group to help you seamlessly deal with traffic changes to your
application.
Amazon EC2 Auto Scaling also monitors the health of each Amazon EC2 instance that it launches. If any
instance terminates unexpectedly, Amazon EC2 Auto Scaling detects the termination and launches a
replacement instance. This capability enables you to maintain a fixed, desired number of Amazon EC2
instances automatically.
229
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Elastic Beanstalk provisions Amazon EC2 Auto Scaling for your application. You can edit the Elastic
Beanstalk environment's Amazon EC2 instance configuration with the Auto Scaling tab inside your
application environment tab in the AWS Toolkit for Visual Studio.
The following section discusses how to configure Auto Scaling parameters for your application.
You can edit the launch configuration to control how your Elastic Beanstalk application provisions
Amazon EC2 Auto Scaling resources.
The Minimum Instance Count and Maximum Instance Count boxes let you specify the minimum and
maximum size of the Auto Scaling group that your Elastic Beanstalk application uses.
Note
To maintain a fixed number of Amazon EC2 instances, set Minimum Instance Count and
Maximum Instance Count to the same value.
The Availability Zones box lets you specify the number of Availability Zones you want your Amazon EC2
instances to be in. It is important to set this number if you want to build fault-tolerant applications. If
one Availability Zone goes down, your instances will still be running in your other Availability Zones.
Note
Currently, it is not possible to specify which Availability Zone your instance will be in.
230
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Triggers
A trigger is an Amazon EC2 Auto Scaling mechanism that you set to tell the system when you want to
increase (scale out) the number of instances, and when you want to decrease (scale in) the number of
instances. You can configure triggers to fire on any metric published to Amazon CloudWatch, such as
CPU utilization, and determine if the conditions you specified have been met. When the upper or lower
thresholds of the conditions you have specified for the metric have been breached for the specified
period of time, the trigger launches a long-running process called a Scaling Activity.
You can define a scaling trigger for your Elastic Beanstalk application using AWS Toolkit for Visual
Studio.
Amazon EC2 Auto Scaling triggers work by watching a specific Amazon CloudWatch metric for
an instance. Triggers include CPU utilization, network traffic, and disk activity. Use the Trigger
Measurement setting to select a metric for your trigger.
The following list describes the trigger parameters you can configure using the AWS Management
Console.
• You can specify which statistic the trigger should use. You can select Minimum, Maximum, Sum, or
Average for Trigger Statistic.
• For Unit of Measurement, specify the unit for the trigger measurement.
• The value in the Measurement Period box specifies how frequently Amazon CloudWatch measures the
metrics for your trigger. The Breach Duration is the amount of time a metric can be beyond its defined
limit (as specified for the Upper Threshold and Lower Threshold) before the trigger fires.
• For Upper Breach Scale Increment and Lower Breach Scale Increment, specify how many Amazon
EC2 instances to add or remove when performing a scaling activity.
For more information on Amazon EC2 Auto Scaling, see the Amazon EC2 Auto Scaling section on Amazon
Elastic Compute Cloud Documentation.
231
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
Configuring .NET containers using the AWS toolkit for Visual Studio
The Container/.NET Options panel lets you fine-tune the behavior of your Amazon EC2 instances and
enable or disable Amazon S3 log rotation. You can use the AWS Toolkit for Visual Studio to configure
your container information.
Note
You can modify your configuration settings with zero downtime by swapping the CNAME
for your environments. For more information, see Blue/Green deployments with Elastic
Beanstalk (p. 449).
If you want to, you can extend the number of parameters. For information about extending parameters,
see Option settings (p. 684).
To access the Container/.NET options panel for your Elastic Beanstalk application
1. In AWS Toolkit for Visual Studio, expand the Elastic Beanstalk node and your application node.
2. In AWS Explorer, double-click your Elastic Beanstalk environment.
3. At the bottom of the Overview pane, click the Configuration tab.
4. Under Container, you can configure container options.
232
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
You can choose the version of .NET Framework for your application. Choose either 2.0 or 4.0 for Target
runtime. Select Enable 32-bit Applications if you want to enable 32-bit applications.
Application settings
The Application Settings section lets you specify environment variables that you can read from your
application code.
Managing accounts
If you want to set up different AWS accounts to perform different tasks, such as testing, staging, and
production, you can add, edit, and delete accounts using the AWS Toolkit for Visual Studio.
233
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
1. In Visual Studio, in AWS Explorer, expand the Amazon EC2 node and double-click Instances.
2. Right-click the instance ID for the Amazon EC2 instance running in your application's load balancer
in the Instance column and select Open Remote Desktop from the context menu.
3. Select Use EC2 keypair to log on and paste the contents of your private key file that you used to
deploy your application in the Private key box. Alternatively, enter your user name and password in
the User name and Password text boxes.
Note
If the key pair is stored inside the Toolkit, the text box does not appear.
4. Click OK.
234
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
For information about the health monitoring provided by Elastic Beanstalk, see Basic health
reporting (p. 773).
You can access operational information about your application by using either the AWS Toolkit for Visual
Studio or the AWS Management Console.
The toolkit displays your environment's status and application health in the Status field.
1. In the AWS Toolkit for Visual Studio, in AWS Explorer, expand the Elastic Beanstalk node, and then
expand your application node.
2. Right-click your Elastic Beanstalk environment, and then click View Status.
3. On your application environment tab, click Monitoring.
The Monitoring panel includes a set of graphs showing resource usage for your particular
application environment.
Note
By default, the time range is set to the last hour. To modify this setting, in the Time Range
list, click a different time range.
You can use the AWS Toolkit for Visual Studio or the AWS Management Console to view events
associated with your application.
235
AWS Elastic Beanstalk Developer Guide
The AWS Toolkit for Visual Studio
1. In the AWS Toolkit for Visual Studio, in AWS Explorer, expand the Elastic Beanstalk node and your
application node.
2. Right-click your Elastic Beanstalk environment in AWS Explorer and then click View Status.
3. In your application environment tab, click Events.
The deployment tool supports both initial deployments and redeployments. If you previously deployed
your application using the deployment tool, you can redeploy using the deployment wizard within Visual
Studio. Similarly, if you have deployed using the wizard, you can redeploy using the deployment tool.
Note
The deployment tool does not apply recommended values (p. 614) for configuration options
like the console or EB CLI. Use configuration files (p. 683) to ensure that any settings that you
need are configured when you launch your environment.
This chapter walks you through deploying a sample .NET application to Elastic Beanstalk using the
deployment tool, and then redeploying the application using an incremental deployment. For a more in-
depth discussion about the deployment tool, including the parameter options, see Deployment Tool.
Prerequisites
To use the deployment tool, you need to install the AWS Toolkit for Visual Studio. For information on
prerequisites and installation instructions, see AWS Toolkit for Microsoft Visual Studio.
The deployment tool is typically installed in one of the following directories on Windows:
32-bit 64-bit
236
AWS Elastic Beanstalk Developer Guide
Migrating on-premises application
1. From the Samples subdirectory where the deployment tool is installed, open
ElasticBeanstalkDeploymentSample.txt and enter your AWS access key and AWS secret key
as in the following example.
### AWS Access Key and Secret Key used to create and deploy the application instance
AWSAccessKey = AKIAIOSFODNN7EXAMPLE
AWSSecretKey = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Note
For API access, you need an access key ID and secret access key. Use IAM user access keys
instead of AWS account root user access keys. For more information about creating access
keys, see Managing access keys for IAM users in the IAM User Guide.
2. At the command line prompt, type the following:
It takes a few minutes to deploy your application. If the deployment succeeds, you will see the
message, Application deployment completed; environment health is Green.
Note
If you receive the following error, the CNAME already exists.
[Error]: Deployment to AWS Elastic Beanstalk failed with exception: DNS name
(MyAppEnv.elasticbeanstalk.com) is not available.
237
AWS Elastic Beanstalk Developer Guide
Resources
For more information about the .NET Migration Assistant for AWS Elastic Beanstalk and to download it,
see the https://github.com/awslabs/windows-web-app-migration-assistant repository on GitHub.
If your application includes Microsoft SQL Server databases, the assistant's documentation on GitHub
includes several options for migrating them.
Resources
There are several places you can go to get additional help when developing your .NET applications:
Resource Description
.NET Developer Center One-stop shop for sample code, documentation, tools, and
additional resources.
AWS SDK for .NET Documentation Read about setting up the SDK and running code samples,
features of the SDK, and detailed information about the API
operations for the SDK.
AWS Elastic Beanstalk for Node.js makes it easy to deploy, manage, and scale your Node.js web
applications using Amazon Web Services. Elastic Beanstalk for Node.js is available to anyone developing
or hosting a web application using Node.js. This chapter provides step-by-step instructions for deploying
your Node.js web application to Elastic Beanstalk using the Elastic Beanstalk management console, and
provides walkthroughs for common tasks such as database integration and working with the Express
framework.
After you deploy your Elastic Beanstalk application, you can continue to use EB CLI to manage your
application and environment, or you can use the Elastic Beanstalk console, AWS CLI, or the APIs.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
238
AWS Elastic Beanstalk Developer Guide
Development environment
Samples
Web Server with nodejs- Hiking log application that uses the Express framework and
Amazon RDS express- an RDS database.
hiking-
v1.zip Tutorial (p. 250)
Web Server nodejs- Express web application that uses Amazon ElastiCache for
with Amazon example- clustering. Clustering enhances your web application's high
ElastiCache express- availability, performance, and security.
elasticache.zip
Tutorial (p. 254)
Web Server with eb-node- Express web site that collects user contact information for a
DynamoDB, express- new company's marketing campaign. Uses the AWS SDK for
Amazon SNS sample- JavaScript in Node.js to write entries to a DynamoDB table,
and Amazon v1.0.zip and Elastic Beanstalk configuration files to create resources
SQS in DynamoDB, Amazon SNS and Amazon SQS.
Clone the
repo at Tutorial (p. 262)
GitHub.com
Next steps
After you have an environment running an application, you can deploy a new version of the application
or a completely different application at any time. Deploying a new application version is very quick
because it doesn't require provisioning or restarting EC2 instances. For details about application
deployment, see Deploy a New Version of Your Application (p. 7).
After you've deployed a sample application or two and are ready to start developing and running Node.js
applications locally, see the next section (p. 239) to set up a Node.js development environment with all
of the tools that you will need.
For common setup steps and tools that apply to all languages, see Configuring your development
machine (p. 953).
Topics
239
AWS Elastic Beanstalk Developer Guide
Development environment
Install Node.js
Install Node.js to run Node.js applications locally. If you don't have a preference, get the latest version
supported by Elastic Beanstalk. See Node.js in the AWS Elastic Beanstalk Platforms document for a list of
supported versions.
$ npm -v
Visit the AWS SDK for JavaScript in Node.js homepage for more information.
Install Express
Express is a web application framework that runs on Node.js. To use it, set up Express and create the
project structure. The following walks you through setting up Express on a Linux operating system.
Note
Depending on your permission level to system directories, you might need to prefix some of
these commands with sudo.
~$ mkdir node-express
~$ cd node-express
2. Install Express globally so that you have access to the express command.
3. Depending on your operating system, you may need to set your path to run the express command.
If you need to set your path, use the output from the previous step when you installed Express. The
following is an example.
240
AWS Elastic Beanstalk Developer Guide
The Node.js platform
4. Run the express command. This generates package.json, app.js, and a few directories.
~/node-express$ express
6. Verify it works.
The server runs on port 3000 by default. To test it, run curl http://localhost:3000 in another
terminal, or open a browser on the local computer and go to http://localhost:3000.
Elastic Beanstalk provides configuration options (p. 613) that you can use to customize the software
that runs on the EC2 instances in your Elastic Beanstalk environment. You can configure the environment
variables that are needed by your application, enable log rotation to Amazon S3, and map folders in your
application source that contain static files to paths served by the proxy server.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
You can include a Package.json file (p. 246) in your source bundle to install packages during
deployment, to provide a start command, and to specify the Node.js version you want your application to
use. You can include an npm-shrinkwrap.json file (p. 247) to lock down dependency versions.
The Node.js platform includes a proxy server to serve static assets, forward traffic to your application,
and compress responses. You can extend or override the default proxy configuration (p. 248) for
advanced scenarios.
There are several options to start your application. You can add a Procfile (p. 246) to your source
bundle to specify the command that starts your application. When you don't provide a Procfile, Elastic
241
AWS Elastic Beanstalk Developer Guide
The Node.js platform
Beanstalk runs npm start if you provide a package.json file. If you don't provide that either, Elastic
Beanstalk looks for the file app.js or server.js, in this order, and runs it.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
Use the Elastic Beanstalk console to enable log rotation to Amazon S3 and configure variables that your
application can read from the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Container options
You can specify these platform-specific options:
• Proxy server – The proxy server to use on your environment instances. By default, NGNIX is used.
Log options
The Log Options section has two settings:
• Instance profile – Specifies the instance profile that has permission to access the Amazon S3 bucket
that's associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
242
AWS Elastic Beanstalk Developer Guide
The Node.js platform
Environment properties
Use the Environment Properties section to specify environment configuration settings on the Amazon
EC2 instances that are running your application. These settings are passed in as key-value pairs to the
application.
Inside the Node.js environment running in AWS Elastic Beanstalk, you can access the environment
variables using process.env.ENV_VARIABLE similar to the following example.
The Node.js platform sets the PORT environment variable to the port that the proxy server passes traffic
to. For more information, see Configuring the proxy server (p. 248).
See Environment properties and other software settings (p. 590) for more information.
Container options
• Proxy server – Specifies which web server to use to proxy connections to Node.js. By default, NGINX is
used. If you select none, static file mappings don't take effect, and GZIP compression is disabled.
• Node.js version – Specifies the version of Node.js. For a list of supported Node.js versions, see Node.js
in the AWS Elastic Beanstalk Platforms guide.
• Gzip compression – Specifies whether GZIP compression is enabled. By default, GZIP compression is
enabled.
• Node command – Lets you enter the command used to start the Node.js application. An empty string
(the default) means Elastic Beanstalk uses app.js, then server.js, and then npm start.
You can choose the proxy to use on the instances for your environment by using the
aws:elasticbeanstalk:environment:proxy namespace. The following example configures your
environment to use the Apache HTTPD proxy server.
Example .ebextensions/nodejs-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: apache
You can configure the proxy to serve static files by using the
aws:elasticbeanstalk:environment:proxy:staticfiles namespace. For more information and
an example, see the section called “Static files” (p. 732).
243
AWS Elastic Beanstalk Developer Guide
The Node.js platform
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
For proxy server, you can use an NGINX or Apache proxy server. You can set the none value to the
ProxyServer option. With this setting, Elastic Beanstalk runs your application as standalone, not
behind any proxy server. If your environment runs a standalone application, update your code to listen to
the port that NGINX forwards traffic to.
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:%s', port);
});
You can use a platform-specific configuration option to set the language version. For instructions,
see the section called “Configuring your Node.js environment” (p. 242). Alternatively, use the Elastic
Beanstalk console to update the Node.js version that your environment uses as part of updating your
platform version.
Note
When support for the version of Node.js that you are using is removed from the platform, you
must change or remove the version setting prior to doing a platform update (p. 459). This
might occur when a security vulnerability is identified for one or more versions of Node.js.
When this happens, attempting to update to a new version of the platform that doesn't support
the configured NodeVersion (p. 678) fails. To avoid needing to create a new environment,
change the NodeVersion configuration option to a Node.js version that is supported by both the
old platform version and the new one, or remove the option setting (p. 624), and then perform
the platform update.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, under Platform, choose Change.
4. In the Update platform version dialog box, select a Node.js version.
244
AWS Elastic Beanstalk Developer Guide
The Node.js platform
5. Choose Save.
The following configuration file tells Elastic Beanstalk to use npm start to run the application. It also
sets the proxy type to Apache and enables compression. Last, it configures the proxy to serve static files
from two source directories. One source is HTML files at the html path under the website's root from the
statichtml source directory. The other source is image files at the images path under the website's
root from the staticimages source directory.
Example .ebextensions/node-settings.config
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: "npm start"
ProxyServer: apache
GzipCompression: true
aws:elasticbeanstalk:container:nodejs:staticfiles:
/html: statichtml
245
AWS Elastic Beanstalk Developer Guide
The Node.js platform
/images: staticimages
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
Example Procfile
For information about Procfile usage, expand the Buildfile and Procfile section in the section called
“Extending Linux platforms” (p. 31).
Note
This feature replaces the legacy NodeCommand option in the
aws:elasticbeanstalk:container:nodejs namespace.
Use the scripts keyword to provide a start command. The scripts keyword is now used instead of
the legacy NodeCommand option in the aws:elasticbeanstalk:container:nodejs namespace.
{
"name": "my-app",
"version": "0.0.1",
"private": true,
"dependencies": {
"ejs": "latest",
"aws-sdk": "latest",
"express": "latest",
"body-parser": "latest"
},
"scripts": {
"start": "node app.js"
}
}
Use the engines keyword in the package.json file to specify the Node.js version that you want your
application to use. You can also specify a version range using npm notation. For more information
about the syntax for version ranges, see Semantic Versioning using npm on the Node.js website. The
246
AWS Elastic Beanstalk Developer Guide
The Node.js platform
engines keyword in the Node.js package.json file replaces the legacy NodeVersion option in the
aws:elasticbeanstalk:container:nodejs namespace.
{
...
"engines": { "node" : "14.16.0" }
}
{
...
"engines": { "node" : ">=10 <11" }
}
When a version range is indicated, Elastic Beanstalk installs the latest Node.js version that the platform
has available within the range. In this example, the range indicates that the version must be greater than
or equal to version 10, but less then version 11. As a result, Elastic Beanstalk installs the latest Node.js
version 10.x.y, which is available on the supported platform.
Be aware that you can only specify a Node.js version that corresponds with your platform branch. For
example, if you're using the Node.js 14 platform branch, you can only specify a 14.x.y Node.js version.
You can use the version range options supported by npm to allow for more flexibility. For valid Node.js
versions for each platform branch, see Node.js in the AWS Elastic Beanstalk Platforms guide.
247
AWS Elastic Beanstalk Developer Guide
The Node.js platform
You can avoid upgrading dependencies by creating an npm-shrinkwrap.json file that locks down your
application's dependencies to the current version.
$ npm install
$ npm shrinkwrap
wrote npm-shrinkwrap.json
Include this file in your source bundle to ensure that dependencies are only installed once.
By default, Elastic Beanstalk configures the proxy to forward requests to your application on port 8080.
You can override the default port by setting the PORT environment property (p. 242) to the port that
your main application listens on.
Notes
• The port that your application listens on doesn't affect the port that the nginx server listens
to receive requests from the load balancer.
• On Amazon Linux AMI Node.js platform versions (preceding Amazon Linux 2), Elastic
Beanstalk configures the proxy to forward requests to your application on port 8081. For
instructions, see the section called “Configuring the proxy on Amazon Linux AMI (preceding
Amazon Linux 2)” (p. 248) on this page.
All Amazon Linux 2 platforms support a uniform proxy configuration feature. For instructions on
how to configure the proxy server on the new Amazon Corretto platform versions that run Amazon
Linux 2, expand the Reverse Proxy Configuration section in the section called “Extending Linux
platforms” (p. 31).
The Node.js platform uses a reverse proxy to relay requests from port 80 on the instance to your
application listening on port 8081. Elastic Beanstalk provides a default proxy configuration that you can
either extend or completely override with your own configuration.
To extend the default configuration, add .conf files to /etc/nginx/conf.d with a configuration file.
For a specific example, see Terminating HTTPS on EC2 instances running Node.js (p. 747).
The Node.js platform sets the PORT environment variable to the port that the proxy server passes traffic
to. Read this variable in your code to configure the port for your application.
248
AWS Elastic Beanstalk Developer Guide
The Node.js platform
The default NGINX configuration forwards traffic to an upstream server that's named nodejs at
127.0.0.1:8081. It's possible to remove the default configuration and provide your own in a
configuration file (p. 683).
Example .ebextensions/proxy.config
The following example removes the default configuration and adds a custom configuration that forwards
traffic to port 5000, instead of 8081.
files:
/etc/nginx/conf.d/proxy.conf:
mode: "000644"
owner: root
group: root
content: |
upstream nodejs {
server 127.0.0.1:5000;
keepalive 256;
}
server {
listen 8080;
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
set $hour $4;
}
access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;
access_log /var/log/nginx/access.log main;
location / {
proxy_pass http://nodejs;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
gzip on;
gzip_comp_level 4;
gzip_types text/html text/plain text/css application/json application/x-javascript
text/xml application/xml application/xml+rss text/javascript;
location /static {
alias /var/app/current/static;
}
/opt/elasticbeanstalk/hooks/configdeploy/post/99_kill_default_nginx.sh:
mode: "000755"
owner: root
group: root
content: |
#!/bin/bash -xe
rm -f /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf
service nginx stop
service nginx start
container_commands:
removeconfig:
249
AWS Elastic Beanstalk Developer Guide
Tutorial - Express
The removeconfig command removes the default configuration for the container' so that the
proxy server uses the custom configuration. Elastic Beanstalk recreates the default configuration
when each configuration is deployed. To account for this, in the following example, a post-
configuration-deployment hook (/opt/elasticbeanstalk/hooks/configdeploy/
post/99_kill_default_nginx.sh) is added. This removes the default configuration and restarts the
proxy server.
Note
The default configuration might change in future versions of the Node.js platform. Use the
latest version of the configuration as a base for your customizations to ensure compatibility.
If you override the default configuration, you must define any static file mappings and GZIP compression.
This is because the platform can't apply the standard settings (p. 243).
Prerequisites
This tutorial requires the Node.js language, its package manager called npm, and the Express
web application framework. For details on installing these components and setting up your local
development environment, see Setting up your Node.js development environment (p. 239).
Note
For this tutorial, you don't need to install the AWS SDK for Node.js, which is also mentioned in
Setting up your Node.js development environment (p. 239).
The tutorial also requires the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing
and configuring the EB CLI, see Install the EB CLI (p. 957) and Configure the EB CLI (p. 964).
Initialize Git
The prerequisite Node.js and Express setup results in an Express project structure in the node-express
folder. If you haven't already generated an Express project, run the following command. For more details,
see Install Express (p. 240).
1. Initialize the Git repository. If you don't have Git installed, download it from the Git downloads site.
2. Create a file named .gitignore and add the following files and directories to it. These files will be
excluded from being added to the repository. This step is not required, but it is recommended.
250
AWS Elastic Beanstalk Developer Guide
Tutorial - Express
node-express/.gitignore
node_modules/
.gitignore
.elasticbeanstalk/
This command creates a configuration file in a folder named .elasticbeanstalk that specifies
settings for creating environments for your application, and creates an Elastic Beanstalk application
named after the current folder.
2. Create an environment running a sample application with the eb create command.
This command creates a load-balanced environment with the default settings for the Node.js
platform and the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to
run web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it,
serves static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running
your web app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to
the instances running your application. A load balancer also eliminates the need to expose your
instances directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound
traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By
default, traffic isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated
or becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are
created when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances
in your environment and that are triggered if the load is too high or too low. When an alarm is
triggered, your Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources
in your environment and propagate configuration changes. The resources are defined in a
template that you can view in the AWS CloudFormation console.
251
AWS Elastic Beanstalk Developer Guide
Tutorial - Express
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
3. When environment creation completes, use the eb open command to open the environment's URL in
the default browser.
~/node-express$ eb open
1. On your local computer, create an .ebextensions directory in the top-level directory of your
source bundle. In this example, we use node-express/.ebextensions.
2. Add a configuration file that sets the Node Command to "npm start":
node-express/.ebextensions/nodecommand.config
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: "npm start"
For more information, see Advanced environment customization with configuration files
(.ebextensions) (p. 683).
3. Stage the files:
~/node-express$ eb deploy
5. Once the environment is green and ready, refresh the URL to verify it worked. You should see a web
page that says Welcome to Express.
Next, let's update the Express application to serve static files and add a new page.
To configure static files and add a new page to your Express application
node-express/.ebextensions/staticfiles.config
option_settings:
aws:elasticbeanstalk:container:nodejs:staticfiles:
/public: /public
This setting configures the proxy server to serve files in the public folder at the /public path
of the application. Serving files statically (p. 243) from the proxy reduces the load on your
application.
252
AWS Elastic Beanstalk Developer Guide
Tutorial - Express
2. Comment out the static mapping in node-express/app.js. This step is not required, but it is a
good test to confirm that static mappings are configured correctly.
// app.use(express.static(path.join(__dirname, 'public')));
3. Add your updated files to your local repository and commit your changes.
First, add the following line to add a require for this route:
Then, add the following two lines to node-express/app.js after var app = express();
app.get('/hikes', hike.index);
app.post('/add_hike', hike.add_hike);
7. Add your files to the local repository, commit your changes, and deploy your updated application.
8. Your environment will be updated after a few minutes. After your environment is green and ready,
verify it worked by refreshing your browser and appending hikes at the end of the URL (e.g.,
http://node-express-env-syypntcz2q.elasticbeanstalk.com/hikes).
253
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
Clean up
If you are done working with Elastic Beanstalk, you can terminate your environment.
Use the eb terminate command to terminate your environment and all of the resources that it contains.
~/node-express$ eb terminate
The environment "node-express-env" and all associated instances will be terminated.
To confirm, type the environment name: node-express-env
INFO: terminateEnvironment is starting.
...
Prerequisites
This tutorial requires the Node.js language, its package manager called npm, and the Express
web application framework. For details on installing these components and setting up your local
development environment, see Setting up your Node.js development environment (p. 239).
Note
For this tutorial, you don't need to install the AWS SDK for Node.js, which is also mentioned in
Setting up your Node.js development environment (p. 239).
The tutorial also requires the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing
and configuring the EB CLI, see Install the EB CLI (p. 957) and Configure the EB CLI (p. 964).
This command creates a configuration file in a folder named .elasticbeanstalk that specifies
settings for creating environments for your application, and creates an Elastic Beanstalk application
named after the current folder.
2. Create an environment running a sample application with the eb create command.
254
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
This command creates a load-balanced environment with the default settings for the Node.js
platform and the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to
run web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it,
serves static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running
your web app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to
the instances running your application. A load balancer also eliminates the need to expose your
instances directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound
traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By
default, traffic isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated
or becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are
created when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances
in your environment and that are triggered if the load is too high or too low. When an alarm is
triggered, your Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources
in your environment and propagate configuration changes. The resources are defined in a
template that you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
3. When environment creation completes, use the eb open command to open the environment's URL in
the default browser.
~/node-express$ eb open
255
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
3. On your local computer, create a file named node-express/app.js with the following code.
function spawn(){
var worker = cluster.fork();
workers[worker.pid] = worker;
return worker;
}
if (cluster.isMaster) {
for (var i = 0; i < count; i++) {
spawn();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died. spawning a new process...');
delete workers[worker.pid];
spawn();
});
} else {
app.listen(process.env.PORT || 5000);
}
node-express$ eb deploy
5. Your environment will be updated after a few minutes. Once the environment is green and ready,
refresh the URL to verify it worked. You should see a web page that says "Welcome to Express".
You can access the logs for your EC2 instances running your application. For instructions on accessing
your logs, see Viewing logs from Amazon EC2 instances in your Elastic Beanstalk environment (p. 820).
1. On your local computer, create an .ebextensions directory in the top-level directory of your
source bundle. In this example, we use node-express/.ebextensions.
2. Create a configuration file node-express/.ebextensions/elasticache-iam-with-
script.config with the following snippet. For more information about the configuration file, see
Node.js configuration namespace (p. 243). This creates an IAM user with the permissions required
to discover the elasticache nodes and writes to a file anytime the cache changes. You can also copy
the file from nodejs-example-express-elasticache.zip. For more information on the ElastiCache
properties, see Example: ElastiCache (p. 710).
256
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
Note
YAML relies on consistent indentation. Match the indentation level when replacing content
in an example configuration file and ensure that your text editor uses spaces, not tab
characters, to indent.
Resources:
MyCacheSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: "Lock cache down to webserver access only"
SecurityGroupIngress:
- IpProtocol: tcp
FromPort:
Fn::GetOptionSetting:
OptionName: CachePort
DefaultValue: 11211
ToPort:
Fn::GetOptionSetting:
OptionName: CachePort
DefaultValue: 11211
SourceSecurityGroupName:
Ref: AWSEBSecurityGroup
MyElastiCache:
Type: 'AWS::ElastiCache::CacheCluster'
Properties:
CacheNodeType:
Fn::GetOptionSetting:
OptionName: CacheNodeType
DefaultValue: cache.t2.micro
NumCacheNodes:
Fn::GetOptionSetting:
OptionName: NumCacheNodes
DefaultValue: 1
Engine:
Fn::GetOptionSetting:
OptionName: Engine
DefaultValue: redis
VpcSecurityGroupIds:
-
Fn::GetAtt:
- MyCacheSecurityGroup
- GroupId
AWSEBAutoScalingGroup :
Metadata :
ElastiCacheConfig :
CacheName :
Ref : MyElastiCache
CacheSize :
Fn::GetOptionSetting:
OptionName : NumCacheNodes
DefaultValue: 1
WebServerUser :
Type : AWS::IAM::User
Properties :
Path : "/"
Policies:
-
PolicyName: root
PolicyDocument :
Statement :
-
Effect : Allow
Action :
- cloudformation:DescribeStackResource
257
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
- cloudformation:ListStackResources
- elasticache:DescribeCacheClusters
Resource : "*"
WebServerKeys :
Type : AWS::IAM::AccessKey
Properties :
UserName :
Ref: WebServerUser
Outputs:
WebsiteURL:
Description: sample output only here to show inline string function parsing
Value: |
http://`{ "Fn::GetAtt" : [ "AWSEBLoadBalancer", "DNSName" ] }`
MyElastiCacheName:
Description: Name of the elasticache
Value:
Ref : MyElastiCache
NumCacheNodes:
Description: Number of cache nodes in MyElastiCache
Value:
Fn::GetOptionSetting:
OptionName : NumCacheNodes
DefaultValue: 1
files:
"/etc/cfn/cfn-credentials" :
content : |
AWSAccessKeyId=`{ "Ref" : "WebServerKeys" }`
AWSSecretKey=`{ "Fn::GetAtt" : ["WebServerKeys", "SecretAccessKey"] }`
mode : "000400"
owner : root
group : root
"/etc/cfn/get-cache-nodes" :
content : |
# Define environment variables for command line tools
export AWS_ELASTICACHE_HOME="/home/ec2-user/elasticache/$(ls /home/ec2-user/
elasticache/)"
export AWS_CLOUDFORMATION_HOME=/opt/aws/apitools/cfn
export PATH=$AWS_CLOUDFORMATION_HOME/bin:$AWS_ELASTICACHE_HOME/bin:$PATH
export AWS_CREDENTIAL_FILE=/etc/cfn/cfn-credentials
export JAVA_HOME=/usr/lib/jvm/jre
# Grab the Cache node names and configure the PHP page
aws cloudformation list-stack-resources --stack `{ "Ref" : "AWS::StackName" }`
--region `{ "Ref" : "AWS::Region" }` --output text | grep MyElastiCache | awk '{print
$4}' | xargs -I {} aws elasticache describe-cache-clusters --cache-cluster-id {}
--region `{ "Ref" : "AWS::Region" }` --show-cache-node-info --output text | grep
'^ENDPOINT' | awk '{print $2 ":" $3}' > `{ "Fn::GetOptionSetting" : { "OptionName" :
"NodeListPath", "DefaultValue" : "/var/www/html/nodelist" } }`
mode : "000500"
owner : root
group : root
"/etc/cfn/hooks.d/cfn-cache-change.conf" :
"content": |
[cfn-cache-size-change]
triggers=post.update
path=Resources.AWSEBAutoScalingGroup.Metadata.ElastiCacheConfig
action=/etc/cfn/get-cache-nodes
runas=root
sources :
"/home/ec2-user/elasticache" : "https://elasticache-downloads.s3.amazonaws.com/
AmazonElastiCacheCli-latest.zip"
258
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
commands:
make-elasticache-executable:
command: chmod -R ugo+x /home/ec2-user/elasticache/*/bin/*
packages :
"yum" :
"aws-apitools-cfn" : []
container_commands:
initial_cache_nodes:
command: /etc/cfn/get-cache-nodes
option_settings:
"aws:elasticbeanstalk:customoption":
CacheNodeType: cache.t2.micro
NumCacheNodes: 1
Engine: memcached
NodeListPath: /var/nodelist
4. On your local computer, replace node-express/express-app.js with the following snippet. This
file reads the nodes list from disk (/var/nodelist) and configures express to use memcached as a
session store if nodes are present. Your file should look like the following.
/**
* Module dependencies.
*/
function setup(cacheNodes) {
app.use(bodyParser.raw());
app.use(methodOverride());
if (cacheNodes) {
app.use(cookieParser());
app.use(session({
secret: 'your secret here',
resave: false,
saveUninitialized: false,
store: new MemcachedStore({'hosts': cacheNodes})
}));
} else {
console.log('Not using memcached store.');
app.use(cookieParser('your secret here'));
app.use(session());
}
259
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
if (req.session.views) {
req.session.views++
resp.setHeader('Content-Type', 'text/html')
resp.write('Views: ' + req.session.views)
resp.end()
} else {
req.session.views = 1
resp.end('Refresh the page!')
}
});
if (!module.parent) {
console.log('Running express without cluster.');
app.listen(process.env.PORT || 5000);
}
}
{
"name": "node-express",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "*",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"connect-memcached": "*",
"express-session": "*",
"body-parser": "*",
"method-override": "*"
}
}
node-express$ eb deploy
7. Your environment will be updated after a few minutes. After your environment is green and ready,
verify that the code worked.
260
AWS Elastic Beanstalk Developer Guide
Tutorial - Express with clustering
a. Check the Amazon CloudWatch console to view your ElastiCache metrics. To view your
ElastiCache metrics, select Metrics in the left pane, and then search for CurrItems. Select
ElastiCache > Cache Node Metrics, and then select your cache node to view the number of
items in the cache.
Note
Make sure you are looking at the same region that you deployed your application to.
If you copy and paste your application URL into another web browser and refresh the page, you
should see your CurrItem count go up after 5 minutes.
b. Take a snapshot of your logs. For more information about retrieving logs, see Viewing logs from
Amazon EC2 instances in your Elastic Beanstalk environment (p. 820).
c. Check the file /var/log/nodejs/nodejs.log in the log bundle. You should see something
similar to the following:
261
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
Clean up
If you no longer want to run your application, you can clean up by terminating your environment and
deleting your application.
Use the eb terminate command to terminate your environment and the eb delete command to
delete your application.
From the directory where you created your local repository, run eb terminate.
$ eb terminate
This process can take a few minutes. Elastic Beanstalk displays a message once the environment is
successfully terminated.
The tutorial's sample application uses a DynamoDB table to store user-provided text data. The sample
application uses configuration files (p. 683) to create the table and an Amazon Simple Notification
Service topic. It also shows how to use a package.json file (p. 246) to install packages during
deployment.
Sections
• Prerequisites (p. 262)
• Launch an Elastic Beanstalk environment (p. 263)
• Add permissions to your environment's instances (p. 264)
• Deploy the sample application (p. 265)
• Create a DynamoDB table (p. 267)
• Update the application's configuration files (p. 267)
• Configure your environment for high availability (p. 270)
• Cleanup (p. 270)
• Next steps (p. 270)
Prerequisites
• Before you start, download the sample application source bundle from GitHub: eb-node-express-
sample-v1.1.zip.
• You will also need a command line terminal or shell to run the commands in the procedures. Example
commands are preceded by a prompt symbol ($) and the name of the current directory, when
appropriate:
262
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
this is output
Note
You can run all commands in this tutorial on a Linux virtual machine, an OS X machine, or an
Amazon EC2 instance running Amazon Linux. If you need a development environment, you
can launch a single-instance Elastic Beanstalk environment and connect to it with SSH.
• This tutorial uses a command line ZIP utility to create a source bundle that you can deploy to Elastic
Beanstalk. To use the zip command in Windows, you can install UnxUtils, a lightweight collection of
useful command-line utilities like zip and ls. (Alternatively, you can use Windows Explorer (p. 386)
or any other ZIP utility to create source bundle archives.)
To install UnxUtils
1. Download UnxUtils.
2. Extract the archive to a local directory. For example, C:\Program Files (x86).
3. Add the path to the binaries to your Windows PATH user variable. For example, C:\Program
Files (x86)\UnxUtils\usr\local\wbin.
> zip -h
Copyright (C) 1990-1999 Info-ZIP
Type 'zip "-L"' for software license.
...
Elastic Beanstalk takes about five minutes to create the environment with the following resources:
263
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
Elastic Beanstalk manages all of these resources. When you terminate your environment, Elastic
Beanstalk terminates all of the resources that it contains.
Note
The S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted
during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
The sample application uses instance permissions to write data to a DynamoDB table, and to send
notifications to an Amazon SNS topic with the SDK for JavaScript in Node.js. Add the following managed
policies to the default instance profile (p. 21) to grant the EC2 instances in your environment permission
to access DynamoDB and Amazon SNS:
• AmazonDynamoDBFullAccess
• AmazonSNSFullAccess
264
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
2. Choose aws-elasticbeanstalk-ec2-role.
3. On the Permissions tab, choose Attach policies.
4. Select the managed policy for the additional services that your application uses. For example,
AmazonSNSFullAccess or AmazonDynamoDBFullAccess.
5. Choose Attach policy.
See Managing Elastic Beanstalk instance profiles (p. 855) for more on managing instance profiles.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
The site collects user contact information and uses a DynamoDB table to store the data. To add an entry,
choose Sign up today, enter a name and email address, and then choose Sign Up!. The web app writes
the form contents to the table and triggers an Amazon SNS email notification.
265
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
Right now, the Amazon SNS topic is configured with a placeholder email for notifications. You will
update the configuration soon, but in the meantime you can verify the DynamoDB table and Amazon
SNS topic in the AWS Management Console.
266
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
The table contains an entry for every email address submitted on the signup site. In addition to writing
to the table, the application sends a message to an Amazon SNS topic that has two subscriptions, one
for email notifications to you, and another for an Amazon Simple Queue Service queue that a worker
application can read from to process requests and send emails to interested customers.
The application (app.js) defines two routes. The root path (/) returns a webpage rendered from an
Embedded JavaScript (EJS) template with a form that the user fills out to register their name and email
address. Submitting the form sends a POST request with the form data to the /signup route, which
writes an entry to the DynamoDB table and publishes a message to the Amazon SNS topic to notify the
owner of the signup.
The sample application includes configuration files (p. 683) that create the DynamoDB table, Amazon
SNS topic, and Amazon SQS queue used by the application. This lets you create a new environment
and test the functionality immediately, but has the drawback of tying the DynamoDB table to the
environment. For a production environment, you should create the DynamoDB table outside of your
environment to avoid losing it when you terminate the environment or update its configuration.
267
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
~$ mkdir nodejs-tutorial
~$ cd nodejs-tutorial
~/nodejs-tutorial$ unzip ~/Downloads/eb-node-express-sample-v1.0.zip
Example .ebextensions/options.config
option_settings:
aws:elasticbeanstalk:customoption:
NewSignupEmail: you@example.com
aws:elasticbeanstalk:application:environment:
THEME: "flatly"
AWS_REGION: '`{"Ref" : "AWS::Region"}`'
STARTUP_SIGNUP_TABLE: nodejs-tutorial
NEW_SIGNUP_TOPIC: '`{"Ref" : "NewSignupTopic"}`'
aws:elasticbeanstalk:container:nodejs:
ProxyServer: nginx
aws:elasticbeanstalk:container:nodejs:staticfiles:
/static: /static
aws:autoscaling:asg:
Cooldown: "120"
aws:autoscaling:trigger:
Unit: "Percent"
Period: "1"
BreachDuration: "2"
UpperThreshold: "75"
LowerThreshold: "30"
MeasureName: "CPUUtilization"
This configures the application to use the nodejs-tutorial table instead of the one created by
.ebextensions/create-dynamodb-table.config, and sets the email address that the Amazon
SNS topic uses for notifications.
3. Remove .ebextensions/create-dynamodb-table.config.
~/nodejs-tutorial$ rm .ebextensions/create-dynamodb-table.config
The next time you deploy the application, the table created by this configuration file will be deleted.
4. Create a source bundle from the modified code.
268
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
When you deploy, Elastic Beanstalk updates the configuration of the Amazon SNS topic and deletes the
DynamoDB table that it created when you deployed the first version of the application.
Now, when you terminate the environment, the nodejs-tutorial table will not be deleted. This lets you
perform blue/green deployments, modify configuration files, or take down your website without risking
data loss.
Open your site in a browser and verify that the form works as you expect. Create a few entries, and then
check the DynamoDB console to verify the table.
You can also see that Elastic Beanstalk deleted the table that it created previously.
269
AWS Elastic Beanstalk Developer Guide
Tutorial - Node.js w/ DynamoDB
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, set Min instances to 2.
6. Choose Apply.
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
You can also delete the external DynamoDB tables that you created.
Next steps
As you continue to develop your application, you'll probably want to manage environments and deploy
your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console.
270
AWS Elastic Beanstalk Developer Guide
Adding a database
The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use commands for
creating, configuring, and deploying applications to Elastic Beanstalk environments from the command
line.
The sample application uses configuration files to configure software settings and create AWS resources
as part of your environment. See Advanced environment customization with configuration files
(.ebextensions) (p. 683) for more information about configuration files and their use.
The sample application for this tutorial uses the Express web framework for Node.js. For more
information about Express, see the official documentation at expressjs.com.
Finally, if you plan on using your application in a production environment, configure a custom domain
name (p. 612) for your environment and enable HTTPS (p. 734) for secure connections.
If you are using Amazon RDS for the first time, add a DB instance (p. 271) to a test environment with
the Elastic Beanstalk Management Console and verify that your application is able to connect to it.
To connect to a database, add the driver (p. 272) to your application, load the driver in your code, and
create a connection object (p. 272) with the environment properties provided by Elastic Beanstalk. The
configuration and connection code vary depending on the database engine and framework that you use.
Sections
• Adding a DB instance to your environment (p. 271)
• Downloading a driver (p. 272)
• Connecting to a database (p. 272)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
271
AWS Elastic Beanstalk Developer Guide
Adding a database
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577).
Downloading a driver
Add the database driver to your project's package.json file (p. 246) under dependencies.
{
"name": "my-app",
"version": "0.0.1",
"private": true,
"dependencies": {
"ejs": "latest",
"aws-sdk": "latest",
"express": "latest",
"body-parser": "latest",
"mysql": "latest"
},
"scripts": {
"start": "node app.js"
}
}
• MySQL – mysql
• PostgreSQL – node-postgres
• SQL Server – node-mssql
• Oracle – node-oracledb
Connecting to a database
Elastic Beanstalk provides connection information for attached DB instances in environment properties.
Use process.env.VARIABLE to read the properties and configure a database connection.
272
AWS Elastic Beanstalk Developer Guide
Resources
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
For more information about constructing a connection string using node-mysql, see npmjs.org/package/
mysql.
Resources
There are several places you can go to get additional help when developing your Node.js applications:
Resource Description
AWS SDK for Node.js (Developer One-stop shop for sample code, documentation, tools, and
Preview) additional resources.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
If you need help with PHP application development, there are several places you can go:
273
AWS Elastic Beanstalk Developer Guide
Development environment
Resource Description
PHP Developer Center One-stop shop for sample code, documentation, tools, and
additional resources.
AWS SDK for PHP FAQs Get answers to commonly asked questions.
Topics
• Setting up your PHP development environment (p. 274)
• Using the Elastic Beanstalk PHP platform (p. 276)
• Deploying a Laravel application to Elastic Beanstalk (p. 280)
• Deploying a CakePHP application to Elastic Beanstalk (p. 287)
• Deploying a Symfony application to Elastic Beanstalk (p. 292)
• Deploying a high-availability PHP application with an external Amazon RDS database to Elastic
Beanstalk (p. 296)
• Deploying a high-availability WordPress website with an external Amazon RDS database to Elastic
Beanstalk (p. 305)
• Deploying a high-availability Drupal website with an external Amazon RDS database to Elastic
Beanstalk (p. 316)
• Adding an Amazon RDS DB instance to your PHP application environment (p. 329)
For common setup steps and tools that apply to all languages, see Configuring your development
machine (p. 953).
Sections
• Installing PHP (p. 274)
• Install Composer (p. 275)
• Installing the AWS SDK for PHP (p. 276)
• Installing an IDE or text editor (p. 276)
Installing PHP
Install PHP and some common extensions. If you don't have a preference, get the latest version.
Depending on your platform and available package manager, the steps will vary.
274
AWS Elastic Beanstalk Developer Guide
Development environment
Note
To get specific PHP package versions that match the version on your Elastic Beanstalk PHP
platform version, use the command yum search php to find available package versions, such
as php72, php72-mbstring, and php72-intl. Then use sudo yum install package to
install them.
Note
To get specific PHP package versions that match the version on your Elastic Beanstalk PHP
platform version, see Homebrew Formulae for available PHP versions, such as php@7.2. Then
use brew install package to install them.
Depending on the version, php-intl might be included in the main PHP package and not exist
as a separate package.
On Windows 10, install the Windows Subsystem for Linux to get Ubuntu and install PHP with apt.
For earlier versions, visit the download page at windows.php.net to get PHP, and read this page for
information about extensions.
After installing PHP, reopen your terminal and run php --version to ensure that the new version has
been installed and is the default.
Install Composer
Composer is a dependency manager for PHP. You can use it to install libraries, track your application's
dependencies, and generate projects for popular PHP frameworks.
The installer generates a PHAR file in the current directory. Move this file to a location in your
environment PATH so that you can use it as an executable.
$ mv composer.phar ~/.local/bin/composer
Composer adds libraries that you install locally to your project's composer.json file (p. 279). When
you deploy your project code, Elastic Beanstalk uses Composer to install the libraries listed in this file on
your environment's application instances.
If you run into issues installing Composer, see the composer documentation.
275
AWS Elastic Beanstalk Developer Guide
The PHP platform
Visit the AWS SDK for PHP homepage for more information and installation instructions.
• Install Eclipse
• Install PhpStorm
Note
An IDE might add files to your project folder that you might not want to commit to source
control. To prevent committing these files to source control, use .gitignore or your source
control tool's equivalent.
If you just want to begin coding and don't need all of the features of an IDE, consider installing Sublime
Text.
Elastic Beanstalk provides configuration options (p. 613) that you can use to customize the software
that runs on the EC2 instances in your Elastic Beanstalk environment. You can configure environment
variables required by your application, enable log rotation to Amazon S3, map folders in your application
source that contain static files to paths served by the proxy server, and set common PHP initialization
settings.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
If you use Composer, you can include a composer.json file (p. 279) in your source bundle to install
packages during deployment.
For advanced PHP configuration and PHP settings that are not provided as configuration options, you
can use configuration files to provide an INI file (p. 280) that can extend and override the default
settings applied by Elastic Beanstalk, or install additional extensions.
276
AWS Elastic Beanstalk Developer Guide
The PHP platform
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
PHP settings
• Proxy server – The proxy server to use on your environment instances. By default, nginx is used.
• Document root – The folder that contains your site's default page. If your welcome page is not at the
root of your source bundle, specify the folder that contains it relative to the root path. For example, /
public if the welcome page is in a folder named public.
• Memory limit – The maximum amount of memory that a script is allowed to allocate. For example,
512M.
• Zlib output compression – Set to On to compress responses.
• Allow URL fopen – Set to Off to prevent scripts from downloading files from remote locations.
• Display errors – Set to On to show internal error messages for debugging.
• Max execution time – The maximum time in seconds that a script is allowed to run before the
environment terminates it.
Log options
The Log Options section has two settings:
• Instance profile– Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
277
AWS Elastic Beanstalk Developer Guide
The PHP platform
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
Environment properties
The Environment Properties section lets you specify environment configuration settings on the Amazon
EC2 instances that are running your application. These settings are passed in as key-value pairs to the
application.
Your application code can access environment properties by using $_SERVER or the get_cfg_var
function.
$endpoint = $_SERVER['API_ENDPOINT'];
See Environment properties and other software settings (p. 590) for more information.
The following example configuration file (p. 683) specifies a static files option that maps a directory
named staticimages to the path /images, and shows settings for each of the options available in the
aws:elasticbeanstalk:container:php:phpini namespace:
Example .ebextensions/php-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:
ProxyServer: apache
aws:elasticbeanstalk:environment:proxy:staticfiles:
/images: staticimages
aws:elasticbeanstalk:container:php:phpini:
document_root: /public
memory_limit: 128M
zlib.output_compression: "Off"
allow_url_fopen: "On"
display_errors: "Off"
max_execution_time: 60
composer_options: vendor/package
278
AWS Elastic Beanstalk Developer Guide
The PHP platform
Note
The aws:elasticbeanstalk:environment:proxy:staticfiles namespace isn't defined
on Amazon Linux AMI PHP platform branches (preceding Amazon Linux 2).
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
Example composer.json
{
"require": {
"monolog/monolog": "1.0.*"
}
}
When a composer.json file is present, Elastic Beanstalk runs composer.phar install to install
dependencies. You can add options to append to the command by setting the composer_options
option (p. 278) in the aws:elasticbeanstalk:container:php:phpini namespace.
To avoid the negative impact on deployment time, use Composer in your development environment to
resolve dependencies and install them into the vendor folder.
% composer install
2. Include the generated vendor folder in the root of your application source bundle.
When Elastic Beanstalk finds a vendor folder on the instance, it ignores the composer.json file (even
if it exists). Your application then uses dependencies from the vendor folder.
Updating Composer
You may have to update Composer if you see an error when you try to install packages with a Composer
file, or if you are unable to use the latest platform version. Between platform updates, you can use a
configuration file (p. 683) to update Composer on the instances in your environment.
279
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
Example .ebextensions/composer.config
commands:
01updateComposer:
command: export COMPOSER_HOME=/root && /usr/bin/composer.phar self-update 1.9.3
option_settings:
- namespace: aws:elasticbeanstalk:application:environment
option_name: COMPOSER_HOME
value: /root
This configuration file configures composer to update itself to version 1.9.3. Check the Composer
releases page on GitHub to find the latest version.
For more information about the Elastic Beanstalk PHP Platforms, including the version of Composer, see
PHP platform versions in the document AWS Elastic Beanstalk Platforms.
Note
If you omit the version number from the composer.phar self-update command, Composer
will update to the latest version available every time you deploy your source code, and
when new instances are provisioned by Auto Scaling. This could cause scaling operations
and deployments to fail if a version of Composer is released that is incompatible with your
application.
Extending php.ini
Use a configuration file with a files block to add a .ini file to /etc/php.d/ on the instances in
your environment. The main configuration file, php.ini, pulls in settings from files in this folder in
alphabetical order. Many extensions are enabled by default by files in this folder.
Example .ebextensions/mongo.config
files:
"/etc/php.d/99mongo.ini":
mode: "000755"
owner: root
group: root
content: |
extension=mongo.so
Sections
• Prerequisites (p. 281)
• Launch an Elastic Beanstalk environment (p. 281)
• Install Laravel and generate a website (p. 282)
• Deploy your application (p. 282)
• Configure Composer settings (p. 283)
• Add a database to your environment (p. 284)
• Cleanup (p. 286)
280
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Laravel 6 requires PHP 7.2 or later. It also requires the PHP extensions listed in the server requirements
topic in the official Laravel documentation. Follow the instructions in the topic Setting up your PHP
development environment (p. 274) to install PHP and Composer.
For Laravel support and maintenance information, see the support policy topic on the official Laravel
documentation.
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
281
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
Composer installs Laravel and its dependencies, and generates a default project.
If you run into any issues installing Laravel, go to the installation topic in the official documentation:
https://laravel.com/docs/6.x.
Upload the source bundle to Elastic Beanstalk to deploy Laravel to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
282
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Note
To optimize the source bundle further, initialize a Git repository and use the git archive
command (p. 386) to create the source bundle. The default Laravel project includes a
.gitignore file that tells Git to exclude the vendor folder and other files that are not required
for deployment.
What's this? By default, Elastic Beanstalk serves the root of your project at the root path of the
website. In this case, though, the default page (index.php) is one level down in the public
folder. You can verify this by adding /public to the URL. For example, http://laravel.us-
east-2.elasticbeanstalk.com/public.
To serve the Laravel application at the root path, use the Elastic Beanstalk console to configure the
document root for the website.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. For Document Root, enter /public.
6. Choose Apply.
7. When the update is complete, click the URL to reopen your site in the browser.
283
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
So far, so good. Next you'll add a database to your environment and configure Laravel to connect to it.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. For Engine, choose mysql.
6. Type a master username and password. Elastic Beanstalk will provide these values to your
application using environment properties.
7. Choose Apply.
Creating a database instance takes about 10 minutes. For more information about databases
coupled to an Elastic Beanstalk environment, see Adding a database to your Elastic Beanstalk
environment (p. 577).
In the meantime, you can update your source code to read connection information from the
environment. Elastic Beanstalk provides connection details using environment variables, such as
RDS_HOSTNAME, that you can access from your application.
Laravel's database configuration is stored in a file named database.php in the config folder in your
project code. Find the mysql entry and modify the host, database, username, and password
variables to read the corresponding values from Elastic Beanstalk:
Example ~/Eb-laravel/config/database.php
...
'connections' => [
284
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('RDS_HOSTNAME', '127.0.0.1'),
'port' => env('RDS_PORT', '3306'),
'database' => env('RDS_DB_NAME', 'forge'),
'username' => env('RDS_USERNAME', 'forge'),
'password' => env('RDS_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
...
To verify that the database connection is configured correctly, add code to index.php to connect to the
database and add some code to the default response:
Example ~/Eb-laravel/public/index.php
...
if(DB::connection()->getDatabaseName())
{
echo "Connected to database ".DB::connection()->getDatabaseName();
}
$response->send();
...
When the DB instance has finished launching, bundle and deploy the updated application to your
environment.
2. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
3. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
4. Choose Upload and Deploy.
5. Choose Browse, and upload laravel-v2-rds.zip.
6. Choose Deploy.
Deploying a new version of your application takes less than a minute. When the deployment is complete,
refresh the web page again to verify that the database connection succeeded:
285
AWS Elastic Beanstalk Developer Guide
Tutorial - Laravel
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
In addition, you can terminate database resources that you created outside of your Elastic Beanstalk
environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the
data to another instance later.
Next steps
For more information about Laravel, go to the Laravel official website at laravel.com.
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
286
AWS Elastic Beanstalk Developer Guide
Tutorial - CakePHP
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
In this tutorial, you used the Elastic Beanstalk console to configure composer options. To make this
configuration part of your application source, you can use a configuration file like the following.
Example .ebextensions/composer.config
option_settings:
aws:elasticbeanstalk:container:php:phpini:
document_root: /public
For more information, see Advanced environment customization with configuration files
(.ebextensions) (p. 683).
Running an Amazon RDS DB instance in your Elastic Beanstalk environment is great for development
and testing, but it ties the lifecycle of your database to your environment. See Adding an Amazon RDS
DB instance to your PHP application environment (p. 329) for instructions on connecting to a database
running outside of your environment.
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
Sections
• Prerequisites (p. 287)
• Launch an Elastic Beanstalk environment (p. 288)
• Install CakePHP and generate a website (p. 289)
• Deploy your application (p. 289)
• Add a database to your environment (p. 290)
• Cleanup (p. 291)
• Next steps (p. 292)
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
287
AWS Elastic Beanstalk Developer Guide
Tutorial - CakePHP
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
CakePHP 4 requires PHP 7.2 or later. It also requires the PHP extensions listed in the official CakePHP
installation documentation. Follow the instructions in the Setting up your PHP development
environment (p. 274) topic to install PHP and Composer.
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
288
AWS Elastic Beanstalk Developer Guide
Tutorial - CakePHP
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
Composer installs CakePHP and around 20 dependencies, and generates a default project.
If you run into any issues installing CakePHP, visit the installation topic in the official documentation:
http://book.cakephp.org/4.0/en/installation.html
Upload the source bundle to Elastic Beanstalk to deploy CakePHP to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Note
To optimize the source bundle further, initialize a Git repository and use the git archive
command (p. 386) to create the source bundle. The default Symfony project includes a
.gitignore file that tells Git to exclude the vendor folder and other files that are not required
for deployment.
When the process completes, click the URL to open your CakePHP application in the browser.
So far, so good. Next you'll add a database to your environment and configure CakePHP to connect to it.
289
AWS Elastic Beanstalk Developer Guide
Tutorial - CakePHP
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. Under Database, choose Edit.
5. For DB engine, choose postgres.
6. Type a master username and password. Elastic Beanstalk will provide these values to your
application using environment properties.
7. Choose Apply.
Creating a database instance takes about 10 minutes. In the meantime, you can update your source code
to read connection information from the environment. Elastic Beanstalk provides connection details
using environment variables such as RDS_HOSTNAME that you can access from your application.
CakePHP's database configuration is in a file named app.php in the config folder in your project code.
Open this file and add some code that reads the environment variables from $_SERVER and assigns
them to local variables. Insert the highlighted lines in the below example after the first line (<?php):
Example ~/Eb-cake/config/app.php
<?php
if (!defined('RDS_HOSTNAME')) {
define('RDS_HOSTNAME', $_SERVER['RDS_HOSTNAME']);
define('RDS_USERNAME', $_SERVER['RDS_USERNAME']);
define('RDS_PASSWORD', $_SERVER['RDS_PASSWORD']);
define('RDS_DB_NAME', $_SERVER['RDS_DB_NAME']);
}
return [
...
The database connection is configured further down in app.php. Find the following section and modify
the default datasources configuration with the name of the driver that matches your database engine
(Mysql, Sqlserver, or Postgres), and set the host, username, password and database variables to
read the corresponding values from Elastic Beanstalk:
Example ~/Eb-cake/config/app.php
...
/**
* Connection information used by the ORM to connect
* to your application's datastores.
* Drivers include Mysql Postgres Sqlite Sqlserver
* See vendor\cakephp\cakephp\src\Database\Driver for complete list
*/
'Datasources' => [
'default' => [
290
AWS Elastic Beanstalk Developer Guide
Tutorial - CakePHP
When the DB instance has finished launching, bundle up and deploy the updated application to your
environment:
2. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
3. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
4. Choose Upload and Deploy.
5. Choose Browse and upload cake-v2-rds.zip.
6. Choose Deploy.
Deploying a new version of your application takes less than a minute. When the deployment is complete,
refresh the web page again to verify that the database connection succeeded:
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
291
AWS Elastic Beanstalk Developer Guide
Tutorial - Symfony
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
In addition, you can terminate database resources that you created outside of your Elastic Beanstalk
environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the
data to another instance later.
Next steps
For more information about CakePHP, read the book at book.cakephp.org.
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
Running an Amazon RDS DB instance in your Elastic Beanstalk environment is great for development
and testing, but it ties the lifecycle of your database to your environment. See Adding an Amazon RDS
DB instance to your PHP application environment (p. 329) for instructions on connecting to a database
running outside of your environment.
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
Sections
292
AWS Elastic Beanstalk Developer Guide
Tutorial - Symfony
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Symfony 4.4.9 requires PHP 7.1.3 or later. It also requires the PHP extensions listed in the technical
requirements topic in the official Symfony installation documentation. In this tutorial, we use PHP 7.2
and the corresponding Elastic Beanstalk platform version. Follow the instructions in the Setting up your
PHP development environment (p. 274) topic to install PHP and Composer.
For Symfony support and maintenance information, see the symfony releases topic on the Symfony
website. For more information about updates related to PHP version support for Symfony 4.4.9, see the
Symfony 4.4.9 release notes topic on the Symfony website.
Environment creation takes about 5 minutes and creates the following resources:
293
AWS Elastic Beanstalk Developer Guide
Tutorial - Symfony
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
Composer installs Symfony and its dependencies, and generates a default project.
If you run into any issues installing Symfony, go to the installation topic in the official Symfony
documentation.
~$ cd eb-symfony
294
AWS Elastic Beanstalk Developer Guide
Tutorial - Symfony
Create a source bundle (p. 385) containing the files created by Composer. The following command
creates a source bundle named symfony-default.zip. It excludes files in the vendor folder, which
take up a lot of space and are not necessary for deploying your application to Elastic Beanstalk.
Upload the source bundle to Elastic Beanstalk to deploy Symfony to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Note
To optimize the source bundle further, initialize a Git repository and use the git archive
command (p. 386) to create the source bundle. The default Symfony project includes a
.gitignore file that tells Git to exclude the vendor folder and other files that are not required
for deployment.
What's this? By default, Elastic Beanstalk serves the root of your project at the root path of
the web site. In this case, though, the default page (app.php) is one level down in the web
folder. You can verify this by adding /public to the URL. For example, http://symfony.us-
east-2.elasticbeanstalk.com/public.
To serve the Symfony application at the root path, use the Elastic Beanstalk console to configure the
document root for the web site.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. For Document root, enter /public.
6. Choose Apply.
7. When the update is complete, click the URL to reopen your site in the browser.
295
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
For more information about Symfony, see What is Symfony? at symfony.com.
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
In this tutorial, you used the Elastic Beanstalk console to configure composer options. To make this
configuration part of your application source, you can use a configuration file like the following.
Example .ebextensions/composer.config
option_settings:
aws:elasticbeanstalk:container:php:phpini:
document_root: /public
For more information, see Advanced environment customization with configuration files
(.ebextensions) (p. 683).
Symfony uses its own configuration files to configure database connections. For instructions on
connecting to a database with Symfony, see Connecting to a database with Symfony (p. 331).
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
296
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
your environment. This lets you connect to the same database from multiple environments, swap out
one database for another, or perform a blue/green deployment without affecting your database.
The tutorial uses a sample PHP application that uses a MySQL database to store user-provided text
data. The sample application uses configuration files (p. 683) to configure PHP settings (p. 278)
and to create a table in the database for the application to use. It also shows how to use a Composer
file (p. 279) to install packages during deployment.
Sections
• Prerequisites (p. 297)
• Launch a DB instance in Amazon RDS (p. 297)
• Create an Elastic Beanstalk environment (p. 299)
• Configure security groups, environment properties, and scaling (p. 300)
• Deploy the sample application (p. 303)
• Cleanup (p. 303)
• Next steps (p. 304)
Prerequisites
Before you start, download the sample application source bundle from GitHub: eb-demo-php-simple-
app-1.3.zip
The procedures in this tutorial for Amazon Relational Database Service (Amazon RDS) tasks assume that
you are launching resources in a default Amazon Virtual Private Cloud (Amazon VPC). All new accounts
include a default VPC in each region. If you don't have a default VPC, the procedures will vary. See Using
Elastic Beanstalk with Amazon RDS (p. 923) for instructions for EC2-Classic and custom VPC platforms.
Use the Amazon RDS console to launch a Multi-AZ MySQL DB instance. Choosing a Multi-AZ deployment
ensures that your database will fail over and continue to be available if the source DB instance goes out
of service.
• DB instance class – Choose an instance size that has an appropriate amount of memory and CPU
power for your workload.
297
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
• Multi-AZ deployment – For high availability, set this to Create an Aurora Replica/Reader node in
a different AZ.
• Master username and Master password – The database username and password. Make a note of
these settings because you will use them later.
7. Verify the default settings for the remaining options, and then choose Create database.
Next, modify the security group attached to your DB instance to allow inbound traffic on the appropriate
port. This is the same security group that you will attach to your Elastic Beanstalk environment later, so
the rule that you add will grant ingress permission to other resources in the same security group.
To modify the inbound rules on the security group that's attached to your RDS instance
298
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
Creating a DB instance takes about 10 minutes. In the meantime, create your Elastic Beanstalk
environment.
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
299
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains. The RDS DB instance that you launched is outside
of your environment, so you are responsible for managing its lifecycle.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Environments, and then choose the name of your
environment from the list.
Note
If you have many environments, use the search bar to filter the environment list.
c. In the navigation pane, choose Configuration.
d. In the Instances configuration category, choose Edit.
e. Under EC2 security groups, choose the security group to attach to the instances, in
addition to the instance security group that Elastic Beanstalk creates.
f. Choose Apply.
g. Read the warning, and then choose Confirm.
• To add a security group using a configuration file (p. 683), use the securitygroup-
addexisting.config example file.
300
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
Next, use environment properties to pass the connection information to your environment. The sample
application uses a default set of properties that match the ones that Elastic Beanstalk configures when
you provision a database within your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Environment properties section, define the variables that your application reads to construct
a connection string. For compatibility with environments that have an integrated RDS DB instance,
use the following names and values. You can find all values, except for your password, in the RDS
console.
301
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
6. Choose Apply.
Finally, configure your environment's Auto Scaling group with a higher minimum instance count. Run at
least two instances at all times to prevent the web servers in your environment from being a single point
of failure, and to allow you to deploy changes without taking your site out of service.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, set Min instances to 2.
6. Choose Apply.
302
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
The site collects user comments and uses a MySQL database to store the data. To add a comment,
choose Share Your Thought, enter a comment, and then choose Submit Your Thought. The web app
writes the comment to the database so that any instance in the environment can read it, and it won't be
lost if instances go out of service.
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
303
AWS Elastic Beanstalk Developer Guide
Tutorial - HA production
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
In addition, you can terminate database resources that you created outside of your Elastic Beanstalk
environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the
data to another instance later.
Next steps
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
The sample application uses configuration files to configure PHP settings and create a table in the
database if it doesn't already exist. You can also use a configuration file to configure the security group
settings of your instances during environment creation to avoid time-consuming configuration updates.
See Advanced environment customization with configuration files (.ebextensions) (p. 683) for more
information.
For development and testing, you might want to use the Elastic Beanstalk functionality for adding a
managed DB instance directly to your environment. For instructions on setting up a database inside your
environment, see Adding a database to your Elastic Beanstalk environment (p. 577).
If you need a high-performance database, consider using Amazon Aurora. Amazon Aurora is a MySQL-
compatible database engine that offers commercial database features at low cost. To connect your
application to a different database, repeat the security group configuration (p. 297) steps and update
the RDS-related environment properties (p. 300).
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
304
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
Running a DB instance external to Elastic Beanstalk decouples the database from the lifecycle of your
environment. This lets you connect to the same database from multiple environments, swap out one
database for another, or perform a blue/green deployment (p. 449) without affecting your database.
This tutorial was developed with WordPress version 4.9.5 and PHP 7.0.
Note
For current information about the compatibility of PHP releases with WordPress versions, see
PHP Compatibility and WordPress Versions on the WordPress website. You should refer to this
information before you upgrade to a new release of PHP for your WordPress implementations.
Topics
• Prerequisites (p. 305)
• Launch a DB instance in Amazon RDS (p. 306)
• Download WordPress (p. 308)
• Launch an Elastic Beanstalk environment (p. 309)
• Configure security groups and environment properties (p. 310)
• Configure and deploy your application (p. 312)
• Install WordPress (p. 313)
• Update keys and salts (p. 313)
• Remove access restrictions (p. 314)
• Configure your Auto Scaling group (p. 315)
• Upgrade WordPress (p. 315)
• Clean up (p. 315)
• Next steps (p. 316)
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Default VPC
305
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
The Amazon Relational Database Service (Amazon RDS) procedures in this tutorial assume that you are
launching resources in a default Amazon Virtual Private Cloud (Amazon VPC). All new accounts include
a default VPC in each AWS Region. If you don't have a default VPC, the procedures will vary. See Using
Elastic Beanstalk with Amazon RDS (p. 923) for instructions for EC2-Classic and custom VPC platforms.
AWS Regions
The sample application uses Amazon EFS, which only works in AWS Regions that support Amazon EFS.
To learn about supported AWS Regions, see Amazon Elastic File System Endpoints and Quotas in the
AWS General Reference.
In the following steps you'll use the Amazon RDS console to:
• DB instance class – Choose an instance size that has an appropriate amount of memory and CPU
power for your workload.
• Multi-AZ deployment – For high availability, set this to Create an Aurora Replica/Reader node in
a different AZ.
• Master username and Master password – The database username and password. Make a note of
these settings because you will use them later.
7. Verify the default settings for the remaining options, and then choose Create database.
After your DB instance is created, modify the security group attached to it in order to allow inbound
traffic on the appropriate port..
Note
This is the same security group that you'll attach to your Elastic Beanstalk environment later, so
the rule that you add now will grant ingress permission to other resources in the same security
group.
To modify the inbound rules on the security group that's attached to your RDS instance
306
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
2. Choose Databases.
3. Choose the name of your DB instance to view its details.
4. In the Connectivity section, make a note of the Subnets, Security groups, and Endpoint that are
displayed on this page. This is so you can use this information later.
5. Under Security, you can see the security group that's associated with the DB instance. Open the link
to view the security group in the Amazon EC2 console.
307
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
Creating a DB instance takes about 10 minutes. In the meantime, download WordPress and create your
Elastic Beanstalk environment.
Download WordPress
To prepare to deploy WordPress using AWS Elastic Beanstalk, you must copy the WordPress files to your
computer and provide the correct configuration information.
~$ wget https://github.com/aws-samples/eb-php-wordpress/releases/download/v1.1/eb-php-
wordpress-v1.zip
308
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
In the following steps, you'll use the Elastic Beanstalk console to:
Environment creation takes about five minutes and creates the following resources.
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
309
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Because the Amazon RDS instance that you launched is outside of your environment, you are responsible
for managing its lifecycle.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Environments, and then choose the name of your
environment from the list.
Note
If you have many environments, use the search bar to filter the environment list.
c. In the navigation pane, choose Configuration.
d. In the Instances configuration category, choose Edit.
e. Under EC2 security groups, choose the security group to attach to the instances, in
addition to the instance security group that Elastic Beanstalk creates.
f. Choose Apply.
g. Read the warning, and then choose Confirm.
• To add a security group using a configuration file (p. 683), use the securitygroup-
addexisting.config example file.
Next, use environment properties to pass the connection information to your environment.
The WordPress application uses a default set of properties that match the ones that Elastic Beanstalk
configures when you provision a database within your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Environment properties section, define the variables that your application reads to construct
a connection string. For compatibility with environments that have an integrated RDS DB instance,
310
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
use the following names and values. You can find all values, except for your password, in the RDS
console.
311
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
6. Choose Apply.
The customized wp-config.php file from the project repo uses the environment variables that you
defined in the previous step to configure the database connection. The .ebextensions folder contains
configuration files that create additional resources within your Elastic Beanstalk environment.
The configuration files require modification to work with your account. Replace the placeholder values in
the files with the appropriate IDs and create a source bundle.
312
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
Upload the source bundle to Elastic Beanstalk to deploy WordPress to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Install WordPress
To complete your WordPress installation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose the environment URL to open your site in a browser. You are redirected to a WordPress
installation wizard because you haven't configured the site yet.
4. Perform a standard installation. The wp-config.php file is already present in the source code and
configured to read the database connection information from the environment. You shouldn't be
prompted to configure the connection.
The hash salt can be any value that meets the environment property requirements (p. 592), but you
should not store it in source control. Use the Elastic Beanstalk console to set these properties directly on
the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the navigation pane, choose Configuration.
4. Under Software, choose Edit.
5. For Environment properties, modify the following properties:
313
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
Note
Setting the properties on the environment directly overrides the values in wordpress.config.
Now that you've installed WordPress, remove the configuration file to open the site to the world.
~/wordpress-beanstalk$ rm .ebextensions/loadbalancer-sg.config
Upload the source bundle to Elastic Beanstalk to deploy WordPress to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
314
AWS Elastic Beanstalk Developer Guide
Tutorial - HA WordPress
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, set Min instances to 2.
6. Choose Apply.
To support content uploads across multiple instances, the sample project uses Amazon EFS to create
a shared file system. Create a post on the site and upload content to store it on the shared file system.
View the post and refresh the page multiple times to hit both instances and verify that the shared file
system is working.
Upgrade WordPress
To upgrade to a new version of WordPress, back up your site and deploy it to a new environment.
Important
Do not use the update functionality within WordPress or update your source files to use a new
version. Both of these actions can result in your post URLs returning 404 errors even though
they are still in the database and file system.
To upgrade WordPress
1. In the WordPress admin console, use the export tool to export your posts to an XML file.
2. Deploy and install the new version of WordPress to Elastic Beanstalk with the same steps that you
used to install the previous version. To avoid downtime, you can create an environment with the new
version.
3. On the new version, install the WordPress Importer tool in the admin console and use it to import
the XML file containing your posts. If the posts were created by the admin user on the old version,
assign them to the admin user on the new site instead of trying to import the admin user.
4. If you deployed the new version to a separate environment, do a CNAME swap (p. 449) to redirect
users from the old site to the new site.
Clean up
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
315
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
In addition, you can terminate database resources that you created outside of your Elastic Beanstalk
environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the
data to another instance later.
Next steps
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
The sample application uses configuration files to configure PHP settings and create a table in the
database, if it doesn't already exist. You can also use a configuration file to configure the security group
settings of your instances during environment creation to avoid time-consuming configuration updates.
See Advanced environment customization with configuration files (.ebextensions) (p. 683) for more
information.
For development and testing, you might want to use the Elastic Beanstalk functionality for adding a
managed DB instance directly to your environment. For instructions on setting up a database inside your
environment, see Adding a database to your Elastic Beanstalk environment (p. 577).
If you need a high-performance database, consider using Amazon Aurora. Amazon Aurora is a MySQL-
compatible database engine that offers commercial database features at low cost. To connect your
application to a different database, repeat the security group configuration (p. 297) steps and update
the RDS-related environment properties (p. 300).
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
316
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
website to connect to it. The website uses Amazon Elastic File System (Amazon EFS) as shared storage
for uploaded files. Running a DB instance external to Elastic Beanstalk decouples the database from the
lifecycle of your environment, and lets you connect to the same database from multiple environments,
swap out one database for another, or perform a blue/green deployment without affecting your
database.
Sections
• Prerequisites (p. 317)
• Launch a DB instance in Amazon RDS (p. 317)
• Launch an Elastic Beanstalk environment (p. 320)
• Configure security settings and environment properties (p. 321)
• Configure and deploy your application (p. 323)
• Install Drupal (p. 325)
• Update Drupal configuration and remove access restrictions (p. 326)
• Configure your Auto Scaling group (p. 328)
• Cleanup (p. 328)
• Next steps (p. 329)
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
The procedures in this tutorial for Amazon Relational Database Service (Amazon RDS) tasks assume that
you are launching resources in a default Amazon Virtual Private Cloud (Amazon VPC). All new accounts
include a default VPC in each region. If you don't have a default VPC, the procedures will vary. See Using
Elastic Beanstalk with Amazon RDS (p. 923) for instructions for EC2-Classic and custom VPC platforms.
The sample application uses Amazon EFS. It only works in AWS Regions that support Amazon EFS. To
learn about supporting AWS Regions, see Amazon Elastic File System Endpoints and Quotas in the AWS
General Reference.
If the platform of your Elastic Beanstalk environment uses PHP 7.4 or earlier, we recommend that you
use Drupal version 8.9.13 for this tutorial. For platforms installed with PHP 8.0 or later, we recommend
that you use Drupal 9.1.5.
For more information about Drupal releases and the PHP versions that they support, see PHP
requirements on the Drupal website. The core versions that Drupal recommends are listed on the website
https://www.drupal.org/project/drupal.
317
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Elastic Beanstalk and your Elastic Beanstalk environments, and will not be terminated or monitored by
Elastic Beanstalk.
Use the Amazon RDS console to launch a Multi-AZ MySQL DB instance. Choosing a Multi-AZ deployment
ensures that your database will failover and continue to be available if the source DB instance goes out
of service.
• DB instance class – Choose an instance size that has an appropriate amount of memory and CPU
power for your workload.
• Multi-AZ deployment – For high availability, set this to Create an Aurora Replica/Reader node in
a different AZ.
• Master username and Master password – The database username and password. Make a note of
these settings because you will use them later.
7. Verify the default settings for the remaining options, and then choose Create database.
Next, modify the security group attached to your DB instance to allow inbound traffic on the appropriate
port. This is the same security group that you will attach to your Elastic Beanstalk environment later, so
the rule that you add will grant ingress permission to other resources in the same security group.
To modify the inbound rules on the security group that's attached to your RDS instance
318
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Creating a DB instance takes about 10 minutes. In the meantime, launch your Elastic Beanstalk
environment.
319
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains. The RDS DB instance that you launched is outside
of your environment, so you are responsible for managing its lifecycle.
320
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Environments, and then choose the name of your
environment from the list.
Note
If you have many environments, use the search bar to filter the environment list.
c. In the navigation pane, choose Configuration.
d. In the Instances configuration category, choose Edit.
e. Under EC2 security groups, choose the security group to attach to the instances, in
addition to the instance security group that Elastic Beanstalk creates.
f. Choose Apply.
g. Read the warning, and then choose Confirm.
• To add a security group using a configuration file (p. 683), use the securitygroup-
addexisting.config example file.
Next, use environment properties to pass the connection information to your environment. The sample
application uses a default set of properties that match the ones that Elastic Beanstalk configures when
you provision a database within your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Environment properties section, define the variables that your application reads to construct
a connection string. For compatibility with environments that have an integrated RDS DB instance,
use the following names and values. You can find all values, except for your password, in the RDS
console.
321
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
6. Choose Apply.
After installing Drupal, you need to connect to the instance with SSH to retrieve some configuration
details. Assign an SSH key to your environment's instances.
322
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
To configure SSH
1. If you haven't previously created a key pair, open the key pairs page of the Amazon EC2 console and
follow the instructions to create one.
2. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
3. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
4. In the navigation pane, choose Configuration.
5. Under Security, choose Edit.
6. For EC2 key pair, choose your key pair.
7. Choose Apply.
1. Run the follwing command to download Drupal from www.drupal.org/download. To learn more
about downloads, see the the Drupal website.
If the platform of your Elastic Beanstalk environment uses PHP 7.4 or earlier, we recommend
that you download Drupal version 8.9.13 for this tutorial. You can run the following command to
download it.
If your platform uses PHP 8.0 or later, we recommend that you download Drupal 9.1.5. You can use
this command to download it.
For more information about Drupal releases and the PHP versions that they support, see PHP
requirements in the official Drupal documentation. The core versions that Drupal recommends are
listed on the Drupal website.
2. Use the following command to download the configuration files from the sample repository:
~$ wget https://github.com/aws-samples/eb-php-drupal/releases/download/v1.1/eb-php-
drupal-v1.zip
323
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
The beanstalk-settings.php file from the project repo uses the environment variables that you
defined in the previous step to configure the database connection. The .ebextensions folder contains
configuration files that create additional resources within your Elastic Beanstalk environment.
The configuration files require modification to work with your account. Replace the placeholder values in
the files with the appropriate IDs and create a source bundle.
324
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Upload the source bundle to Elastic Beanstalk to deploy Drupal to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Install Drupal
To complete your Drupal installation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose the environment URL to open your site in a browser. You are redirected to a Drupal
installation wizard because the site has not been configured yet.
4. Perform a standard installation with the following settings for the database:
325
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
Get the sync directory id from the last line of the settings file.
The file also contains the sites current hash key, but you can ignore the current value and use your own.
Assign the sync directory path and hash key to environment properties. The customized settings file
from the project repo reads these properties to configure the site during deployment, in addition to the
database connection properties that you set earlier.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. Under Environment properties, enter key-value pairs.
326
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
6. Choose Apply.
Finally, the sample project includes a configuration file (loadbalancer-sg.config) that creates a
security group and assigns it to the environment's load balancer, using the IP address that you configured
in dev.config to restrict HTTP access on port 80 to connections from your network. Otherwise, an
outside party could potentially connect to your site before you have installed Drupal and configured your
admin account.
~/drupal-beanstalk$ rm .ebextensions/loadbalancer-sg.config
Upload the source bundle to Elastic Beanstalk to deploy Drupal to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
327
AWS Elastic Beanstalk Developer Guide
Tutorial - HA Drupal
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, set Min instances to 2.
6. Choose Apply.
To support content uploads across multiple instances, the sample project uses Amazon Elastic File
System to create a shared file system. Create a post on the site and upload content to store it on the
shared file system. View the post and refresh the page multiple times to hit both instances and verify
that the shared file system is working.
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
In addition, you can terminate database resources that you created outside of your Elastic Beanstalk
environment. When you terminate an Amazon RDS DB instance, you can take a snapshot and restore the
data to another instance later.
328
AWS Elastic Beanstalk Developer Guide
Adding a database
2. Choose Databases.
3. Choose your DB instance.
4. Choose Actions, and then choose Delete.
5. Choose whether to create a snapshot, and then choose Delete.
Next steps
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
The sample application uses configuration files to configure PHP settings and create a table in the
database if it doesn't already exist. You can also use a configuration file to configure your instances'
security group settings during environment creation to avoid time-consuming configuration updates.
See Advanced environment customization with configuration files (.ebextensions) (p. 683) for more
information.
For development and testing, you might want to use the Elastic Beanstalk functionality for adding a
managed DB instance directly to your environment. For instructions on setting up a database inside your
environment, see Adding a database to your Elastic Beanstalk environment (p. 577).
If you need a high-performance database, consider using Amazon Aurora. Amazon Aurora is a MySQL-
compatible database engine that offers commercial database features at low cost. To connect your
application to a different database, repeat the security group configuration (p. 297) steps and update
the RDS-related environment properties (p. 300).
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
If you are using Amazon RDS for the first time, add a DB instance (p. 330) to a test environment with
the Elastic Beanstalk console and verify that your application can connect to it.
To connect to a database, add the driver (p. 330) to your application, load the driver class in your code,
and create a connection object (p. 331) with the environment properties provided by Elastic Beanstalk.
The configuration and connection code vary depending on the database engine and framework that you
use.
Sections
• Adding a DB instance to your environment (p. 330)
• Downloading a driver (p. 330)
• Connecting to a database with a PDO or MySQLi (p. 331)
• Connecting to a database with Symfony (p. 331)
329
AWS Elastic Beanstalk Developer Guide
Adding a database
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577).
Downloading a driver
To use PHP Data Objects (PDO) to connect to the database, install the driver that matches the database
engine that you chose.
• MySQL – PDO_MYSQL
• PostgreSQL – PDO_PGSQL
• Oracle – PDO_OCI
• SQL Server – PDO_SQLSRV
330
AWS Elastic Beanstalk Developer Guide
Adding a database
For a PDO, create a Data Source Name (DSN) from the host, port, and name. Pass the DSN to the
constructor for the PDO with the database user name and password.
<?php
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
For other drivers, replace mysql with the name of your driver – pgsql, oci, or sqlsrv.
For MySQLi, pass the hostname, user name, password, database name, and port to the mysqli
constructor.
Example app/config/parameters.yml
parameters:
database_driver: pdo_mysql
database_host: '%env(RDS_HOSTNAME)%'
database_port: '%env(RDS_PORT)%'
database_name: '%env(RDS_DB_NAME)%'
database_user: '%env(RDS_USERNAME)%'
database_password: '%env(RDS_PASSWORD)%'
For earlier versions of Symfony, environment variables are only accessible if they start with SYMFONY__.
This means that the Elastic Beanstalk-defined environment properties are not accessible, and you must
define your own environment properties to pass the connection information to Symfony.
To connect to a database with Symfony 2, create an environment property (p. 278) for each
parameter. Then, use %property.name% to access the Symfony-transformed variable in a configuration
file. For example, an environment property named SYMFONY__DATABASE__USER is accessible as
database.user.
331
AWS Elastic Beanstalk Developer Guide
Working with Python
database_user: "%database.user%"
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
Topics
• Setting up your Python development environment (p. 332)
• Using the Elastic Beanstalk Python platform (p. 334)
• Deploying a Flask application to Elastic Beanstalk (p. 339)
• Deploying a Django application to Elastic Beanstalk (p. 345)
• Adding an Amazon RDS DB instance to your Python application environment (p. 355)
• Python tools and resources (p. 356)
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
For common setup steps and tools that apply to all languages, see Configuring your development
machine (p. 953).
Sections
• Prerequisites (p. 332)
• Using a virtual environment (p. 333)
• Configuring a Python project for Elastic Beanstalk (p. 334)
Prerequisites
For all Python applications that you'll deploy with Elastic Beanstalk, these prerequisites are common:
1. A Python version matching the Elastic Beanstalk Python platform version your application will use.
332
AWS Elastic Beanstalk Developer Guide
Development environment
2. The pip utility, matching your Python version. This is used to install and list dependencies for your
project, so that Elastic Beanstalk knows how to set up your application's environment.
3. The AWS Elastic Beanstalk Command Line Interface (EB CLI). This is used to initialize your application
with the files necessary for deploying with Elastic Beanstalk.
4. A working ssh installation. This is used to connect with your running instances when you need to
examine or debug a deployment.
5. The virtualenv package. This is used to create an environment used to develop and test your
application, so that the environment can be replicated by Elastic Beanstalk without installing extra
packages that aren't needed by your application. Install this package with the following command:
For instructions on installing Python, pip, and the EB CLI, see Install the EB CLI (p. 957).
$ virtualenv /tmp/eb_python_app
Replace eb_python_app with a name that makes sense for your application (using your
application's name is a good idea). The virtualenv command creates a virtual environment for you
in the specified directory and prints the results of its actions:
2. Once your virtual environment is ready, start it by running the activate script located in the
environment's bin directory. For example, to start the eb_python_app environment created in the
previous step, you would type:
$ source /tmp/eb_python_app/bin/activate
The virtual environment prints its name (for example: (eb_python_app)) at the beginning of each
command prompt, reminding you that you're in a virtual Python environment.
3. To stop using your virtual environment and go back to the system’s default Python interpreter with
all its installed libraries, run the deactivate command.
(eb_python_app) $ deactivate
Note
Once created, you can restart the virtual environment at any time by running its activate
script again.
333
AWS Elastic Beanstalk Developer Guide
The Python platform
1. From within your virtual environment (p. 333), return to the top of your project's directory tree
(python_eb_app), and type:
This command copies the names and versions of the packages that are installed in your virtual
environment to requirements.txt, For example, if the PyYAML package, version 3.11 is installed in
your virtual environment, the file will contain the line:
PyYAML==3.11
This allows Elastic Beanstalk to replicate your application's Python environment using the same
packages and same versions that you used to develop and test your application.
2. Configure the EB CLI repository with the eb init command. Follow the prompts to choose a region,
platform and other options. For detailed instructions, see Managing Elastic Beanstalk environments
with the EB CLI (p. 968).
By default, Elastic Beanstalk looks for a file called application.py to start your application. If
this doesn't exist in the Python project that you've created, some adjustment of your application's
environment is necessary. You will also need to set environment variables so that your application's
modules can be loaded. See Using the Elastic Beanstalk Python platform (p. 334) for more information.
Starting with Amazon Linux 2 platform branches, Elastic Beanstalk provides Gunicorn as the default
WSGI server.
You can add a Procfile to your source bundle to specify and configure the WSGI server for your
application. For details, see the section called “Procfile” (p. 337).
You can use the Pipfile and Pipfile.lock files created by Pipenv to specify Python package
dependencies and other requirements. For details about specifying dependencies, see the section called
“Specifying dependencies” (p. 338).
Elastic Beanstalk provides configuration options (p. 613) that you can use to customize the software
that runs on the EC2 instances in your Elastic Beanstalk environment. You can configure environment
variables needed by your application, enable log rotation to Amazon S3, and map folders in your
application source that contain static files to paths served by the proxy server.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
334
AWS Elastic Beanstalk Developer Guide
The Python platform
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
For Python packages available from pip, you can include a requirements file in the root of your
application source code. Elastic Beanstalk installs any dependency packages specified in a requirements
file during deployment. For details, see the section called “Specifying dependencies” (p. 338).
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
Use the Elastic Beanstalk console to configure Python process settings, enable AWS X-Ray, enable log
rotation to Amazon S3, and configure variables that your application can read from the environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Python settings
• Proxy server – The proxy server to use on your environment instances. By default, nginx is used.
• WSGI Path – The name of or path to your main application file. For example, application.py, or
django/wsgi.py.
• NumProcesses – The number of processes to run on each application instance.
• NumThreads – The number of threads to run in each process.
Log options
The Log Options section has two settings:
335
AWS Elastic Beanstalk Developer Guide
The Python platform
• Instance profile– Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
By default, the proxy server in a Python environment serves any files in a folder named static at the
/static path. For example, if your application source contains a file named logo.png in a folder
named static, the proxy server serves it to users at subdomain.elasticbeanstalk.com/static/
logo.png. You can configure additional mappings as explained in this section.
Environment properties
You can use environment properties to provide information to your application and configure
environment variables. For example, you can create an environment property named
CONNECTION_STRING that specifies a connection string that your application can use to connect to a
database.
Inside the Python environment running in Elastic Beanstalk, these values are accessible using Python's
os.environ dictionary. For more information, go to http://docs.python.org/library/os.html.
You can use code that looks similar to the following to access the keys and parameters:
import os
endpoint = os.environ['API_ENDPOINT']
Environment properties can also provide information to a framework. For example, you can create a
property named DJANGO_SETTINGS_MODULE to configure Django to use a specific settings module.
Depending on the environment, the value could be development.settings, production.settings,
etc.
See Environment properties and other software settings (p. 590) for more information.
The following example configuration file specifies configuration option settings to create an
environment property named DJANGO_SETTINGS_MODULE, choose the Apache proxy server,
specify two static files options that map a directory named statichtml to the path /html and
a directory named staticimages to the path /images, and specify additional settings in the
aws:elasticbeanstalk:container:python (p. 680) namespace. This namespace contains
336
AWS Elastic Beanstalk Developer Guide
The Python platform
options that let you specify the location of the WSGI script in your source code, and the number of
threads and processes to run in WSGI.
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: production.settings
aws:elasticbeanstalk:environment:proxy:
ProxyServer: apache
aws:elasticbeanstalk:environment:proxy:staticfiles:
/html: statichtml
/images: staticimages
aws:elasticbeanstalk:container:python:
WSGIPath: ebdjango.wsgi:application
NumProcesses: 3
NumThreads: 20
Notes
• If you're using an Amazon Linux AMI Python platform version (preceding Amazon Linux 2),
replace the value for WSGIPath with ebdjango/wsgi.py. The value in the example works
with the Gunicorn WSGI server, which isn't supported on Amazon Linux AMI platform versions.
• In addition, these older platform versions use a different namespace for configuring static files
—aws:elasticbeanstalk:container:python:staticfiles. It has the same option
names and semantics as the standard static file namespace.
Configuration files also support several keys to further modify the software on your environment's
instances (p. 685). This example uses the packages (p. 686) key to install Memcached with yum and
container commands (p. 694) to run commands that configure the server during deployment:
packages:
yum:
libmemcached-devel: '0.31'
container_commands:
collectstatic:
command: "django-admin.py collectstatic --noinput"
01syncdb:
command: "django-admin.py syncdb --noinput"
leader_only: true
02migrate:
command: "django-admin.py migrate"
leader_only: true
03wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
99customize:
command: "scripts/customize.sh"
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
Example Procfile
337
AWS Elastic Beanstalk Developer Guide
The Python platform
The following example uses a Procfile to configure Gunicorn, the default WSGI server.
Example Procfile
Notes
• If you configure any WSGI server other than Gunicorn, be sure to also specify it as a
dependency of your application, so that it is installed on your environment instances.
For details about dependency specification, see the section called “Specifying
dependencies” (p. 338).
• The default port for the WSGI server is 8000. If you specify a different port number in your
Procfile command, set the PORT environment property (p. 590) to this port number too.
For details about Procfile usage, expand the Buildfile and Procfile section in the section called
“Extending Linux platforms” (p. 31).
Create a file named requirements.txt and place it in the top-level directory of your source bundle.
The following is an example requirements.txt file for Django.
Django==2.2
mysqlclient==2.0.3
In your development environment, you can use the pip freeze command to generate your
requirements file.
To ensure that your requirements file only contains packages that are actually used by your application,
use a virtual environment (p. 333) that only has those packages installed. Outside of a virtual
environment, the output of pip freeze will include all pip packages installed on your development
machine, including those that came with your operating system.
Note
On Amazon Linux AMI Python platform versions, Elastic Beanstalk doesn't natively support
Pipenv or Pipfiles. If you use Pipenv to manage your application's dependencies, run the
following command to generate a requirements.txt file.
338
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
Amazon Linux 2 Python platform versions support Pipenv-based requirements files. Create them on your
development environment and include them with the source bundle that you deploy to Elastic Beanstalk.
Note
Amazon Linux AMI Python platform versions (preceding Amazon Linux 2) don't support Pipenv
and Pipfile.
The following example uses Pipenv to install Django and the Django REST framework.
These commands create the files Pipfile and Pipfile.lock. Place Pipfile in the top-level directory
of your source bundle to get latest versions of dependency packages installed on your environment
instances. Alternatively, include Pipfile.lock to get a constant set of package versions reflecting your
development environment at the time of the file's creation.
If you include more than one of the requirements files described here, Elastic Beanstalk uses just one of
them. The following list shows the precedence, in descending order.
1. requirements.txt
2. Pipfile.lock
3. Pipfile
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
339
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Flask requires Python 3.7 or later. In this tutorial we use Python 3.7 and the corresponding Elastic
Beanstalk platform version. Install Python by following the instructions at Setting up your Python
development environment (p. 332).
This tutorial also uses the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing and
configuring the EB CLI, see Install the EB CLI (p. 957) and Configure the EB CLI (p. 964).
~$ mkdir eb-flask
~$ cd eb-flask
You will see (virt) prepended to your command prompt, indicating that you're in a virtual
environment. Use the virtual environment for the rest of this tutorial.
3. Install Flask with pip install:
This command lists all of the packages installed in your virtual environment. Because you are in a
virtual environment, globally installed packages like the EB CLI are not shown.
5. Save the output from pip freeze to a file named requirements.txt.
340
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
This file tells Elastic Beanstalk to install the libraries during deployment. For more information, see
Specifying dependencies using a requirements file (p. 338).
Create a new text file in this directory named application.py with the following contents:
Example ~/eb-flask/application.py
# add a rule when the page is accessed with a name appended to the site
# URL.
application.add_url_rule('/<username>', 'hello', (lambda username:
header_text + say_hello(username) + home_link + footer_text))
This example prints a customized greeting that varies based on the path used to access the service.
Note
By adding application.debug = True before running the application, debug output is
enabled in case something goes wrong. It's a good practice for development, but you should
remove debug statements in production code, since debug output can reveal internal aspects of
your application.
Using application.py as the filename and providing a callable application object (the Flask object,
in this case) allows Elastic Beanstalk to easily find your application's code.
341
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
Open http://127.0.0.1:5000/ in your web browser. You should see the application running,
showing the index page:
Check the server log to see the output from your request. You can stop the web server and return to your
virtual environment by typing Ctrl+C.
If you got debug output instead, fix the errors and make sure the application is running locally before
configuring it for Elastic Beanstalk.
~/eb-flask/
|-- virt
|-- application.py
`-- requirements.txt
The virt folder, however, is not required for the application to run on Elastic Beanstalk. When you
deploy, Elastic Beanstalk creates a new virtual environment on the server instances and installs the
libraries listed in requirements.txt. To minimize the size of the source bundle that you upload during
deployment, add an .ebignore (p. 966) file that tells the EB CLI to leave out the virt folder.
Example ~/Eb-flask/.ebignore
virt
Next, you'll create your application environment and deploy your configured application with Elastic
Beanstalk.
342
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
This command creates a new application named flask-tutorial and configures your local
repository to create environments with the latest Python 3.7 platform version.
2. (optional) Run eb init again to configure a default keypair so that you can connect to the EC2
instance running your application with SSH:
~/eb-flask$ eb init
Do you want to set up SSH for your instances?
(y/n): y
Select a keypair.
1) my-keypair
2) [ Create new KeyPair ]
Select a key pair if you have one already, or follow the prompts to create a new one. If you don't see
the prompt or need to change your settings later, run eb init -i.
3. Create an environment and deploy your application to it with eb create:
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
343
AWS Elastic Beanstalk Developer Guide
Tutorial - flask
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
When the environment creation process completes, open your web site with eb open:
~/eb-flask$ eb open
This will open a browser window using the domain name created for your application. You should see the
same Flask website that you created and tested locally.
If you don't see your application running, or get an error message, see Troubleshooting
Deployments (p. 1061) for help with how to determine the cause of the error.
If you do see your application running, then congratulations, you've deployed your first Flask application
with Elastic Beanstalk!
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
344
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
For more information about Flask, visit flask.pocoo.org.
If you'd like to try out another Python web framework, check out Deploying a Django application to
Elastic Beanstalk (p. 345).
Prerequisites
To use any AWS service, including Elastic Beanstalk, you need to have an AWS account and credentials.
To learn more and to sign up, visit https://aws.amazon.com/.
To follow this tutorial, you should have all of the Common Prerequisites (p. 332) for Python installed,
including the following packages:
345
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
The following steps demonstrate the commands you must enter for Unix-based systems and Windows,
shown on separate tabs.
Unix-based systems
~$ virtualenv ~/eb-virt
Windows
Unix-based systems
~$ source ~/eb-virt/bin/activate
(eb-virt) ~$
Windows
C:\>%HOMEPATH%\eb-virt\Scripts\activate
(eb-virt) C:\>
You'll see (eb-virt) prepended to your command prompt, indicating that you're in a virtual
environment.
Note
The rest of these instructions show the Linux command prompt in your home directory ~$.
On Windows this is C:\Users\USERNAME>, where USERNAME is your Windows login name.
3. Use pip to install Django.
Note
The Django version you install must be compatible with the Python version on the Elastic
Beanstalk Python configuration that you choose for deploying your application. For
information about deployment, see ??? (p. 349) in this topic.
For more information about current Python platform versions, see Python in the AWS
Elastic Beanstalk Platforms document.
For Django version compatibility with Python, see What Python version can I use with
Django?
4. To verify that Django is installed, enter the following.
346
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
...
This command lists all of the packages installed in your virtual environment. Later, you use the
output of this command to configure your project for use with Elastic Beanstalk.
Unix-based systems
~$ source ~/eb-virt/bin/activate
(eb-virt) ~$
Windows
C:\>%HOMEPATH%\eb-virt\Scripts\activate
(eb-virt) C:\>
You'll see the (eb-virt) prefix prepended to your command prompt, indicating that you're in a
virtual environment.
Note
The rest of these instructions show the Linux command prompt ~$ in your home directory
and the Linux home directory ~/. On Windows these are C:\Users\USERNAME>, where
USERNAME is your Windows login name.
2. Use the django-admin startproject command to create a Django project named ebdjango.
This command creates a standard Django site named ebdjango with the following directory
structure.
~/ebdjango
|-- ebdjango
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| `-- wsgi.py
`-- manage.py
(eb-virt) ~$ cd ebdjango
347
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
By default, Elastic Beanstalk looks for a file named application.py to start your application. Because
this doesn't exist in the Django project that you've created, you need to make some adjustments to your
application's environment. You also must set environment variables so that your application's modules
can be loaded.
Unix-based systems
Windows
C:\Users\USERNAME\ebdjango>%HOMEPATH%\eb-virt\Scripts\activate
2. Run pip freeze, and then save the output to a file named requirements.txt.
Elastic Beanstalk uses requirements.txt to determine which package to install on the EC2
instances that run your application.
3. Create a directory named .ebextensions.
4. In the .ebextensions directory, add a configuration file (p. 683) named django.config with
the following text.
Example ~/ebdjango/.ebextensions/django.config
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: ebdjango.wsgi:application
348
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
This setting, WSGIPath, specifies the location of the WSGI script that Elastic Beanstalk uses to start
your application.
Note
If you're using an Amazon Linux AMI Python platform version (preceding Amazon Linux
2), replace the value for WSGIPath with ebdjango/wsgi.py. The value in the example
works with the Gunicorn WSGI server, which isn't supported on Amazon Linux AMI platform
versions.
5. Deactivate your virtual environment with the deactivate command.
Reactivate your virtual environment whenever you need to add packages to your application or run
your application locally.
~/ebdjango/
|-- .ebextensions
| `-- django.config
|-- ebdjango
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| `-- wsgi.py
|-- db.sqlite3
|-- manage.py
`-- requirements.txt
Next, you'll create your application environment and deploy your configured application with Elastic
Beanstalk.
Immediately after deployment, you'll edit Django's configuration to add the domain name that
Elastic Beanstalk assigned to your application to Django's ALLOWED_HOSTS. Then you'll redeploy your
application. This is a Django security requirement, designed to prevent HTTP Host header attacks. For
more information, see Host header validation.
This command creates an application named django-tutorial. It also configures your local
repository to create environments with the latest Python 3.7 platform version.
2. (Optional) Run eb init again to configure a default key pair so that you can use SSH to connect to
the EC2 instance running your application.
349
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
~/ebdjango$ eb init
Do you want to set up SSH for your instances?
(y/n): y
Select a keypair.
1) my-keypair
2) [ Create new KeyPair ]
Select a key pair if you have one already, or follow the prompts to create one. If you don't see the
prompt or need to change your settings later, run eb init -i.
3. Create an environment and deploy your application to it with eb create.
Note
If you see a "service role required" error message, run eb create interactively (without
specifying an environment name) and the EB CLI creates the role for you.
This command creates a load-balanced Elastic Beanstalk environment named django-env. Creating
an environment takes about 5 minutes. As Elastic Beanstalk creates the resources needed to run your
application, it outputs informational messages that the EB CLI relays to your terminal.
4. When the environment creation process completes, find the domain name of your new environment
by running eb status.
~/ebdjango$ eb status
Environment details for: django-env
Application name: django-tutorial
...
CNAME: eb-django-app-dev.elasticbeanstalk.com
...
...
ALLOWED_HOSTS = ['eb-django-app-dev.elasticbeanstalk.com']
6. Save the file, and then deploy your application by running eb deploy. When you run eb deploy, the
EB CLI bundles up the contents of your project directory and deploys it to your environment.
~/ebdjango$ eb deploy
Note
If you are using Git with your project, see Using the EB CLI with Git (p. 974).
7. When the environment update process completes, open your website with eb open.
~/ebdjango$ eb open
This opens a browser window using the domain name created for your application. You should see
the same Django website that you created and tested locally.
350
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
If you don't see your application running, or get an error message, see Troubleshooting
deployments (p. 1061) for help with how to determine the cause of the error.
If you do see your application running, then congratulations, you've deployed your first Django
application with Elastic Beanstalk!
For this example, we'll enable Django's admin console and configure a few other settings.
Example ~/ebdjango/ebdjango/settings.py
...
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'US/Pacific'
USE_I18N = True
USE_L10N = True
USE_TZ = True
~/ebdjango/$ eb deploy
351
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
Example ~/ebdjango/ebdjango/settings.py
4. Run manage.py collectstatic to populate the static directory with static assets (JavaScript,
CSS, and images) for the admin site.
~/ebdjango$ eb deploy
6. View the admin console by opening the site in your browser, appending /admin/ to the site URL,
such as the following.
http://djang-env.p33kq46sfh.us-west-2.elasticbeanstalk.com/admin/
352
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
7. Log in with the username and password that you configured in step 2.
You can use a similar procedure of local updating/testing followed by eb deploy. Elastic Beanstalk does
the work of updating your live servers, so you can focus on application development instead of server
administration!
353
AWS Elastic Beanstalk Developer Guide
Tutorial - Django
1. Create a configuration file (p. 683) named db-migrate.config with the following content.
Example ~/ebdjango/.ebextensions/db-migrate.config
container_commands:
01_migrate:
command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate"
leader_only: true
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: ebdjango.settings
This configuration file activates the server's virtual environment and runs the manage.py
migrate command during the deployment process, before starting your application. Because
it runs before the application starts, you must also configure the DJANGO_SETTINGS_MODULE
environment variable explicitly (usually wsgi.py takes care of this for you during startup).
Specifying leader_only: true in the command ensures that it is run only once when you're
deploying to multiple instances.
2. Deploy your application.
~/ebdjango$ eb deploy
Clean up
To save instance hours and other AWS resources between development sessions, terminate your Elastic
Beanstalk environment with eb terminate.
This command terminates the environment and all of the AWS resources that run within it. It
doesn't delete the application, however, so you can always create more environments with the same
configuration by running eb create again. For more information on EB CLI commands, see Managing
Elastic Beanstalk environments with the EB CLI (p. 968).
If you're done with the sample application, you can also remove the project folder and virtual
environment.
~$ rm -rf ~/eb-virt
~$ rm -rf ~/ebdjango
Next steps
For more information about Django, including an in-depth tutorial, see the official documentation.
If you want to try out another Python web framework, check out Deploying a Flask application to Elastic
Beanstalk (p. 339).
354
AWS Elastic Beanstalk Developer Guide
Adding a database
If you are using Amazon RDS for the first time, add a DB instance (p. 355) to a test environment with
the Elastic Beanstalk Management Console and verify that your application can connect to it.
To connect to a database, add the driver (p. 356) to your application, load the driver in your code, and
create a connection object (p. 356) with the environment properties provided by Elastic Beanstalk. The
configuration and connection code vary depending on the database engine and framework that you use.
Sections
• Adding a DB instance to your environment (p. 355)
• Downloading a driver (p. 356)
• Connecting to a database (p. 356)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
355
AWS Elastic Beanstalk Developer Guide
Resources
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577).
Downloading a driver
Add the database driver to your project's requirements file (p. 338).
Django==2.2
mysqlclient==2.0.3
• MySQL – mysqlclient
• PostgreSQL – psycopg2
• Oracle – cx_Oracle
• SQL Server – adodbapi
For more information see Python DatabaseInterfaces and Django 2.2 - supported databases.
Connecting to a database
Elastic Beanstalk provides connection information for attached DB instances in environment properties.
Use os.environ['VARIABLE'] to read the properties and configure a database connection.
import os
if 'RDS_HOSTNAME' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['RDS_DB_NAME'],
'USER': os.environ['RDS_USERNAME'],
'PASSWORD': os.environ['RDS_PASSWORD'],
'HOST': os.environ['RDS_HOSTNAME'],
'PORT': os.environ['RDS_PORT'],
}
}
356
AWS Elastic Beanstalk Developer Guide
Working with Ruby
Resource Description
Boto (the AWS SDK for Python) Install Boto using GitHub.
Python Developer Center One-stop shop for sample code, documentation, tools, and
additional resources.
AWS Elastic Beanstalk for Ruby makes it easy to deploy, manage, and scale your Ruby web applications
using Amazon Web Services. Elastic Beanstalk is available to anyone developing or hosting a web
application using Ruby. This section provides step-by-step instructions for deploying a sample
application to Elastic Beanstalk using the Elastic Beanstalk command line interface (EB CLI), and then
updating the application to use the Rails and Sinatra web application frameworks.
The topics in this chapter assume that you have some some knowledge of Elastic Beanstalk
environments. If you haven't used Elastic Beanstalk before, try the getting started tutorial (p. 3) to learn
the basics.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
For common setup steps and tools that apply to all languages, see Configuring your development
machine for use with Elastic Beanstalk (p. 953)
Sections
• Installing Ruby (p. 358)
• Installing the AWS SDK for Ruby (p. 359)
357
AWS Elastic Beanstalk Developer Guide
Development environment
Installing Ruby
Install GCC if you don't have a C compiler. On Ubuntu, use apt.
Install RVM to manage Ruby language installations on your machine. Use the commands at rvm.io to get
the project keys and run the installation script.
This script installs RVM in a folder named .rvm in your user directory, and modifies your shell profile to
load a setup script whenever you open a new terminal. Load the script manually to get started.
~$ source ~/.rvm/scripts/rvm
Check Ruby in the AWS Elastic Beanstalk Platforms document to find the latest version of Ruby available
on an Elastic Beanstalk platform. Install that version.
~$ ruby --version
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
358
AWS Elastic Beanstalk Developer Guide
The Ruby platform
Install the SDK for Ruby and its dependencies with the gem command.
Visit the AWS SDK for Ruby homepage for more information and installation instructions.
• Install Aptana
• RubyMine
Note
An IDE might add files to your project folder that you might not want to commit to source
control. To prevent committing these files to source control, use .gitignore or your source
control tool's equivalent.
If you just want to begin coding and don't need all of the features of an IDE, consider installing Sublime
Text.
If you use RubyGems, you can include a Gemfile file (p. 362) in your source bundle to install packages
during deployment.
Your application might run under a different application server, for example Passenger. You can use a
Procfile to start a different application server, and a Gemfile to install it. For details, see the section
called “Procfile” (p. 362).
Note
If you are using an Amazon Linux AMI Ruby platform branch (preceding Amazon Linux 2),
be aware that Elastic Beanstalk provides two flavors of these branches - with Puma and
with Passenger. If your application needs the Passenger application server, you can use the
appropriate Passenger platform branch, and you don't need to do any additional configuration.
Elastic Beanstalk provides configuration options (p. 613) that you can use to customize the software
that runs on the Amazon Elastic Compute Cloud (Amazon EC2) instances in your Elastic Beanstalk
environment. You can configure environment variables needed by your application, enable log rotation
to Amazon S3, and map folders in your application source that contain static files to paths served by the
proxy server. The platform also predefines some common environment variables related to Rails and
Rack for ease of discovery and use.
Configuration options are available in the Elastic Beanstalk console for modifying the configuration of
a running environment (p. 624). To avoid losing your environment's configuration when you terminate
359
AWS Elastic Beanstalk Developer Guide
The Ruby platform
it, you can use saved configurations (p. 721) to save your settings and later apply them to another
environment.
To save settings in your source code, you can include configuration files (p. 683). Settings in
configuration files are applied every time you create an environment or deploy your application. You can
also use configuration files to install packages, run scripts, and perform other instance customization
operations during deployments.
Settings applied in the Elastic Beanstalk console override the same settings in configuration files, if they
exist. This lets you have default settings in configuration files, and override them with environment-
specific settings in the console. For more information about precedence, and other methods of changing
settings, see Configuration options (p. 613).
For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see the
section called “Extending Linux platforms” (p. 31).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
Log options
The Log options section has two settings:
• Instance profile– Specifies the instance profile that has permission to access the Amazon S3 bucket
associated with your application.
• Enable log file rotation to Amazon S3 – Specifies whether log files for your application's Amazon EC2
instances should be copied to the Amazon S3 bucket associated with your application.
Static files
To improve performance, the Static files section lets you configure the proxy server to serve static files
(for example, HTML or images) from a set of directories inside your web application. For each directory,
you set the virtual path to directory mapping. When the proxy server receives a request for a file under
the specified path, it serves the file directly instead of routing the request to your application.
For details about configuring static files using configuration files or the Elastic Beanstalk console, see the
section called “Static files” (p. 732).
By default, the proxy server in a Ruby environment is configured to serve static files as follows:
• Files in the public folder are served from the /public path and the domain root (/ path).
• Files in the public/assets subfolder are served from the /assets path.
360
AWS Elastic Beanstalk Developer Guide
The Ruby platform
• If your application source contains a file named logo.png in a folder named public, the proxy
server serves it to users from subdomain.elasticbeanstalk.com/public/logo.png and
subdomain.elasticbeanstalk.com/logo.png.
• If your application source contains a file named logo.png in a folder named assets inside the
public folder, the proxy server serves it from subdomain.elasticbeanstalk.com/assets/
logo.png.
You can configure additional mappings for static files. For more information, see Ruby configuration
namespaces (p. 361) later in this topic.
Note
For platform versions prior to Ruby 2.7 AL2 version 3.3.7, the default Elastic Beanstalk
nginx proxy server configuration doesn't support serving static files from the domain root
(subdomain.elasticbeanstalk.com/). This platform version was released on October 21,
2021. For more information see New platform versions - Ruby in the AWS Elastic Beanstalk
Release Notes.
Environment properties
The Environment Properties section lets you specify environment configuration settings on the Amazon
EC2 instances that are running your application. Environment properties are passed in as key-value pairs
to the application.
The Ruby platform defines the following properties for environment configuration:
Inside the Ruby environment running in Elastic Beanstalk, environment variables are accessible using
the ENV object. For example, you could read a property named API_ENDPOINT to a variable with the
following code:
endpoint = ENV['API_ENDPOINT']
See Environment properties and other software settings (p. 590) for more information.
361
AWS Elastic Beanstalk Developer Guide
The Ruby platform
The Ruby platform doesn't define any platform-specific namespaces. Instead, it defines environment
properties for common Rails and Rack options.
The following configuration file specifies a static files option that maps a directory named
staticimages to the path /images, sets each of the platform defined environment properties, and
sets an additional environment property named LOGGING.
Example .ebextensions/ruby-settings.config
option_settings:
aws:elasticbeanstalk:environment:proxy:staticfiles:
/images: staticimages
aws:elasticbeanstalk:application:environment:
BUNDLE_WITHOUT: test
BUNDLER_DEPLOYMENT_MODE: true
RACK_ENV: development
RAILS_SKIP_ASSET_COMPILATION: true
RAILS_SKIP_MIGRATIONS: true
LOGGING: debug
Note
The BUNDLER_DEPLOYMENT_MODE environment property and the
aws:elasticbeanstalk:environment:proxy:staticfiles namespace aren't defined on
Amazon Linux AMI Ruby platform branches (preceding Amazon Linux 2).
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
Example Gemfile
source "https://rubygems.org"
gem 'sinatra'
gem 'json'
gem 'rack-parser'
When a Gemfile file is present, Elastic Beanstalk runs bundle install to install dependencies.
For details about writing and using a Procfile, expand the Buildfile and Procfile section in the section
called “Extending Linux platforms” (p. 31).
When you don't provide a Procfile, Elastic Beanstalk generates the following default file, which
assumes you're using the pre-installed Puma application server.
362
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
If you want to use your own provided Puma server, you can install it using a Gemfile (p. 362). The
following example Procfile shows how to start it.
Example Procfile
If you want to use the Passenger application server, use the following example files to configure your
Ruby environment to install and use Passenger.
Example Gemfile
source 'https://rubygems.org'
gem 'passenger'
Example Procfile
Note
You don't have to change anything in the configuration of the nginx proxy server to
use Passenger. To use other application servers, you might need to customize the nginx
configuration to properly forward requests to your application.
Sections
• Prerequisites (p. 363)
• Launch an Elastic Beanstalk environment (p. 364)
• Install rails and generate a website (p. 365)
• Configure rails settings (p. 367)
• Deploy your application (p. 368)
• Cleanup (p. 368)
• Next steps (p. 369)
Prerequisites
Basic Elastic Beanstalk knowledge
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
363
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
Command line
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Rails dependencies
The Rails framework 6.1.4.1 has the following dependencies. Be sure you have all of them installed.
• Ruby 2.5.0 or newer – For installation instructions, see Setting up your Ruby development
environment (p. 357).
In this tutorial we use Ruby 3.0.2 and the corresponding Elastic Beanstalk platform version.
• Node.js – For installation instructions, see Installing Node.js via package manager.
• Yarn – For installation instructions, see Installation on the Yarn website.
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
364
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
~$ rails --version
Rails 6.1.4.1
Use rails new with the name of the application to create a new Rails project.
Rails creates a directory with the name specified, generates all of the files needed to run a sample
project locally, and then runs bundler to install all of the dependencies (Gems) defined in the project's
Gemfile.
~$ cd eb-rails
~/eb-rails$ rails server
=> Booting Puma
=> Rails 6.1.4.1 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.5.2 (ruby 3.0.2-p107) ("Zawgyi")
365
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
* Min threads: 5
* Max threads: 5
* Environment: development
* PID: 77857
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
...
This page is only visible in development mode. Add some content to the front page of the application to
support production deployment to Elastic Beanstalk. Use rails generate to create a controller, route,
and view for your welcome page.
366
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
invoke assets
invoke coffee
create app/assets/javascripts/welcome_page.coffee
invoke scss
create app/assets/stylesheets/welcome_page.scss.
This gives you all you need to access the page at /welcome_page/welcome. Before you publish the
changes, however, change the content in the view and add a route to make this page appear at the top
level of the site.
Example app/views/welcome_page/welcome.html.erb
<h1>Welcome!</h1>
<p>This is the front page of my first Rails application on Elastic Beanstalk.</p>
Example config/routes.rb
Rails.application.routes.draw do
get 'welcome_page/welcome'
root 'welcome_page#welcome'
This tells Rails to route requests to the root of the website to the welcome page controller's welcome
method, which renders the content in the welcome view (welcome.html.erb).
In order for Elastic Beanstalk to successfully deploy the application on the Ruby platform, we need to
update Gemfile.lock. Some dependencies of Gemfile.lock might be platform specific. Therefore,
we need to add platform ruby to Gemfile.lock so that all required dependencies are installed with
the deployment.
Example
Rails uses this property to create keys. Therefore you should keep it a secret and not store it in source
control in plain text. Instead, you provide it to Rails code on your environment through an environment
property.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
367
AWS Elastic Beanstalk Developer Guide
Tutorial - rails
6. Choose Apply.
Upload the source bundle to Elastic Beanstalk to deploy Rails to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
368
AWS Elastic Beanstalk Developer Guide
Tutorial - sinatra
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
For more information about Rails, visit rubyonrails.org.
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
Prerequisites
This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic
Beanstalk console. If you haven't already, follow the instructions in Getting started using Elastic
Beanstalk (p. 3) to launch your first Elastic Beanstalk environment.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate.
On Linux and macOS, you can use your preferred shell and package manager. On Windows 10, you can
install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
Sinatra 2.1.0 requires Ruby 2.3.0 or newer. In this tutorial we use Ruby 3.0.2 and the corresponding
Elastic Beanstalk platform version. Install Ruby by following the instructions at Setting up your Ruby
development environment (p. 357).
369
AWS Elastic Beanstalk Developer Guide
Tutorial - sinatra
Environment creation takes about 5 minutes and creates the following resources:
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic
Beanstalk terminates all the resources that it contains.
Note
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not
deleted during environment termination. For more information, see Using Elastic Beanstalk with
Amazon S3 (p. 935).
370
AWS Elastic Beanstalk Developer Guide
Tutorial - sinatra
Example config.ru
require './helloworld'
run Sinatra::Application
2. Create a Ruby code file named helloworld.rb with the following contents.
Example helloworld.rb
require 'sinatra'
get '/' do
"Hello World!"
end
Example Gemfile
source 'https://rubygems.org'
gem 'sinatra'
gem 'puma'
Example
5. In order for Elastic Beanstalk to successfully deploy the application on the Ruby platform, we need
to update Gemfile.lock. Some dependencies of Gemfile.lock might be platform specific.
Therefore, we need to add platform ruby to Gemfile.lock so that all required dependencies
are installed with the deployment.
Example
Example Procfile
371
AWS Elastic Beanstalk Developer Guide
Tutorial - sinatra
Upload the source bundle to Elastic Beanstalk to deploy Sinatra to your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Cleanup
When you finish working with Elastic Beanstalk, you can terminate your environment. Elastic
Beanstalk terminates all AWS resources associated with your environment, such as Amazon EC2
instances (p. 497), database instances (p. 577), load balancers (p. 526), security groups, and
alarms (p. ).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
With Elastic Beanstalk, you can easily create a new environment for your application at any time.
Next steps
For more information about Sinatra, visit sinatrarb.com.
As you continue to develop your application, you'll probably want a way to manage environments
and deploy your application without manually creating a .zip file and uploading it to the Elastic
Beanstalk console. The Elastic Beanstalk Command Line Interface (p. 956) (EB CLI) provides easy-to-use
commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from
the command line.
372
AWS Elastic Beanstalk Developer Guide
Adding a database
Finally, if you plan on using your application in a production environment, you will want to configure
a custom domain name (p. 612) for your environment and enable HTTPS (p. 734) for secure
connections.
If you are using Amazon RDS for the first time, add a DB instance (p. 373) to a test environment with
the Elastic Beanstalk Management Console and verify that your application can connect to it.
To connect to a database, add the adapter (p. 374) to your application and configure a
connection (p. 374) with the environment properties provided by Elastic Beanstalk. The configuration
and connection code vary depending on the database engine and framework that you use.
Sections
• Adding a DB instance to your environment (p. 373)
• Downloading an adapter (p. 374)
• Connecting to a database (p. 374)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB
instance's hostname and other connection information are available to your application through the
following environment properties:
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
373
AWS Elastic Beanstalk Developer Guide
Adding a database
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
For more information about configuring an internal DB instance, see Adding a database to your Elastic
Beanstalk environment (p. 577).
Downloading an adapter
Add the database adapter to your project's gem file (p. 362).
source 'https://rubygems.org'
gem 'puma'
gem 'rails', '~> 6.1.4', '>= 6.1.4.1'
gem 'mysql2'
• MySQL – mysql2
• PostgreSQL – pg
• Oracle – activerecord-oracle_enhanced-adapter
• SQL Server – activerecord-sqlserver-adapter
Connecting to a database
Elastic Beanstalk provides connection information for attached DB instances in environment properties.
Use ENV['VARIABLE'] to read the properties and configure a database connection.
production:
adapter: mysql2
encoding: utf8
database: <%= ENV['RDS_DB_NAME'] %>
username: <%= ENV['RDS_USERNAME'] %>
password: <%= ENV['RDS_PASSWORD'] %>
host: <%= ENV['RDS_HOSTNAME'] %>
port: <%= ENV['RDS_PORT'] %>
374
AWS Elastic Beanstalk Developer Guide
These tutorials are targeted at intermediate users and may not contain instructions for basic steps such
as signing up for AWS. If this is your first time using AWS or Elastic Beanstalk, check out the Getting
Started walkthrough (p. 3) to get your first Elastic Beanstalk environment up and running.
You can download the sample applications used by Elastic Beanstalk when you create an environment
without providing a source bundle with the following links:
• Docker – docker.zip
• Multicontainer Docker – docker-multicontainer-v2.zip
• Preconfigured Docker (Glassfish) – docker-glassfish-v1.zip
• Go – go.zip
• Corretto – corretto.zip
• Tomcat – tomcat.zip
• .NET Core on Linux – dotnet-core-linux.zip
• .NET – dotnet-asp-v1.zip
• Node.js – nodejs.zip
• PHP – php.zip
• Python – python.zip
• Ruby – ruby.zip
375
AWS Elastic Beanstalk Developer Guide
More involved sample applications that show the use of additional web frameworks, libraries and tools
are available as open source projects on GitHub:
• Load-balanced WordPress (tutorial (p. 305)) – Configuration files for installing WordPress securely and
running it in a load-balanced Elastic Beanstalk environment.
• Load-balanced Drupal (tutorial (p. 316)) – Configuration files and instructions for installing Drupal
securely and running it in a load-balanced Elastic Beanstalk environment.
• Scorekeep - RESTful web API that uses the Spring framework and the AWS SDK for Java to provide an
interface for creating and managing users, sessions, and games. The API is bundled with an Angular
1.5 web app that consumes the API over HTTP. Includes branches that show integration with Amazon
Cognito, AWS X-Ray, and Amazon Relational Database Service.
The application uses features of the Java SE platform to download dependencies and build on-
instance, minimizing the size of the souce bundle. The application also includes nginx configuration
files that override the default configuration to serve the frontend web app statically on port 80
through the proxy, and route requests to paths under /api to the API running on localhost:5000.
• Does it Have Snakes? - Tomcat application that shows the use of RDS in a Java EE web application in
Elastic Beanstalk. The project shows the use of Servlets, JSPs, Simple Tag Support, Tag Files, JDBC,
SQL, Log4J, Bootstrap, Jackson, and Elastic Beanstalk configuration files.
• Locust Load Generator - This project shows the use of Java SE platform features to install and run
Locust, a load generating tool written in Python. The project includes configuration files that install
and configure Locust, a build script that configures a DynamoDB table, and a Procfile that runs Locust.
• Share Your Thoughts (tutorial (p. 296)) - PHP application that shows the use of MySQL on Amazon
RDS, Composer, and configuration files.
• A New Startup (tutorial (p. 262)) - Node.js sample application that shows the use of DynamoDB, the
AWS SDK for JavaScript in Node.js, npm package management, and configuration files.
376
AWS Elastic Beanstalk Developer Guide
To create an application
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose Create a new application.
3. Use the on-screen form to provide an application name.
4. Optionally, provide a description, and add tag keys and values.
5. Choose Create.
377
AWS Elastic Beanstalk Developer Guide
After creating the application, the console prompts you to create an environment for it. For detailed
information about all of the options available, see Creating an Elastic Beanstalk environment (p. 407).
To delete an application
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
378
AWS Elastic Beanstalk Developer Guide
Application management console
2. In the navigation pane, choose Applications, and then select your application on the list.
3. Choose Actions, and then choose Delete application.
Topics
• Elastic Beanstalk application management console (p. 379)
• Managing application versions (p. 380)
• Create an application source bundle (p. 385)
• Tagging Elastic Beanstalk application resources (p. 392)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
The application overview page shows a list with an overview of all environments associated with the
application.
a. Choose the Actions drop-down menu, and then choose one of the application management
actions. To launch an environment in this application, you can directly choose Create a new
environment. For details, see the section called “Creating environments” (p. 407).
b. Choose an environment name to go to the environment management console (p. 396) for that
environment, where you can configure, monitor, or manage the environment.
c. Choose Application versions following the application name in the navigation pane to view and
manage the application versions for your application.
An application version is an uploaded version of your application code. You can upload new
versions, deploy an existing version to any of the application's environments, or delete old
versions. For more information, see Managing application versions (p. 380).
379
AWS Elastic Beanstalk Developer Guide
Managing application versions
d. Choose Saved configurations following the application name in the navigation pane to view
and manage configurations saved from running environments.
A saved configuration is a collection of settings that you can use to restore an environment's
settings to a previous state, or to create an environment with the same settings. For more
information see Using Elastic Beanstalk saved configurations (p. 721).
You can also upload a source bundle without deploying it from the application management
console (p. 379) or with the EB CLI command eb appversion (p. 990). Elastic Beanstalk stores source
bundles in Amazon Simple Storage Service (Amazon S3) and doesn't automatically delete them.
You can apply tags to an application version when you create it, and edit tags of existing application
versions. For details, see Tagging application versions (p. 383).
You can also create a new application version using the EB CLI. For more information, see eb
appversion (p. 990) in the EB CLI commands chapter.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Application versions.
4. Choose Upload. Use the on-screen form to upload your application's source bundle (p. 385).
Note
The source bundle's file size limit is 512 MB.
5. Optionally, provide a brief description, and add tag keys and values.
6. Choose Upload.
The file you specified is associated with your application. You can deploy the application version to a new
or existing environment.
Over time, your application can accumulate many application versions. To save storage space and avoid
hitting the application version quota, it's a good idea to delete application versions that you no longer
need.
Note
Deleting an application version doesn't affect environments currently running that version.
You can also delete an application version using the EB CLI. For more information, see eb
appversion (p. 990) in the EB CLI commands chapter.
380
AWS Elastic Beanstalk Developer Guide
Managing application versions
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Application versions.
4. Select one or more application versions that you want to delete.
7. Choose Delete.
You can also configure Elastic Beanstalk to delete old versions automatically by configuring application
version lifecycle settings. If you configure these lifecycle settings, they're applied when you create
new application versions. For example, if you configure a maximum of 25 application versions, Elastic
Beanstalk deletes the oldest version when you upload a 26th version. If you set a maximum age of 90
days, any versions older than 90 days are deleted when you upload a new version. For details, see the
section called “Version lifecycle” (p. 382).
If you don't choose to delete the source bundle from Amazon S3, Elastic Beanstalk still deletes
the version from its records. However, the source bundle is left in your Elastic Beanstalk storage
bucket (p. 935). The application version quota applies only to versions Elastic Beanstalk tracks.
Therefore, you can delete versions to stay within the quota, but retain all source bundles in Amazon S3.
381
AWS Elastic Beanstalk Developer Guide
Version lifecycle
Note
The application version quota doesn't apply to source bundles, but you might still incur Amazon
S3 charges, and retain personal information beyond the time you need it. Elastic Beanstalk
never deletes source bundles automatically. You should delete source bundles when you no
longer need them.
You can avoid hitting the quota by applying an application version lifecycle policy to your applications. A
lifecycle policy tells Elastic Beanstalk to delete application versions that are old, or to delete application
versions when the total number of versions for an application exceeds a specified number.
Elastic Beanstalk applies an application's lifecycle policy each time you create a new application version,
and deletes up to 100 versions each time the lifecycle policy is applied. Elastic Beanstalk deletes old
versions after creating the new version, and does not count the new version towards the maximum
number of versions defined in the policy.
Elastic Beanstalk does not delete application versions that are currently being used by an environment,
or application versions deployed to environments that were terminated less than ten weeks before the
policy was triggered.
The application version quota applies across all applications in a region. If you have several applications,
configure each application with a lifecycle policy appropriate to avoid reaching the quota. For example,
if you have 10 applications in a region and the quota is 1,000 application versions, consider setting a
lifecycle policy with a quota of 99 application versions for all applications, or set other values in each
application as long as the total is less than 1,000 application versions. Elastic Beanstalk only applies the
policy if the application version creation succeeds, so if you have already reached the quota, you must
delete some versions manually prior to creating a new version.
By default, Elastic Beanstalk leaves the application version's source bundle (p. 385) in Amazon S3 to
prevent loss of data. You can delete the source bundle to save space.
You can set the lifecycle settings through the Elastic Beanstalk CLI and APIs. See eb
appversion (p. 990), CreateApplication (using the ResourceLifecycleConfig parameter), and
UpdateApplicationResourceLifecycle for details.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Application versions.
4. Choose Settings.
5. Use the on-screen form to configure application lifecycle settings.
6. Choose Save.
382
AWS Elastic Beanstalk Developer Guide
Tagging application versions
• Configure lifecycle settings based on the total count of application versions or the age of application
versions.
• Specify whether to delete the source bundle from S3 when the application version is deleted.
• Specify the service role under which the application version is deleted. To include all permissions
required for version deletion, choose the default Elastic Beanstalk service role, named aws-
elasticbeanstalk-service-role, or another service role using the Elastic Beanstalk managed
service policies. For more information, see Managing Elastic Beanstalk service roles (p. 860).
383
AWS Elastic Beanstalk Developer Guide
Tagging application versions
You can specify tags when you create an application version. In an existing application version, you
can add or remove tags, and update the values of existing tags. You can add up to 50 tags to each
application version.
You can also use the Elastic Beanstalk console to upload an application version (p. 380) without
immediately using it in an environment. You can specify tag keys and values when you upload an
application version.
With the AWS CLI or other API-based clients, add tags by using the --tags parameter on the create-
application-version command.
When you use the EB CLI to create or update an environment, an application version is created from the
code that you deploy. There isn't a direct way to tag an application version during its creation through
the EB CLI. See the following section to learn about adding tags to an existing application version.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Application versions.
4. Select the application version you want to manage.
5. Choose Actions, and then choose Manage tags.
6. Use the on-screen form to add, update, or delete tags.
7. Choose Apply.
If you use the EB CLI to update your application version, use eb tags (p. 1040) to add, update, delete, or
list tags.
For example, the following command lists the tags in an application version.
The following command updates the tag mytag1 and deletes the tag mytag2.
384
AWS Elastic Beanstalk Developer Guide
Create a source bundle
--resource "arn:aws:elasticbeanstalk:us-east-2:my-account-id:applicationversion/my-
app/my-version"
For a complete list of options and more examples, see eb tags (p. 1040).
With the AWS CLI or other API-based clients, use the list-tags-for-resource command to list the tags of
an application version.
Use the update-tags-for-resource command to add, update, or delete tags in an application version.
Specify both tags to add and tags to update in the --tags-to-add parameter of update-tags-for-
resource. A nonexisting tag is added, and an existing tag's value is updated.
Note
To use some of the EB CLI and AWS CLI commands with an Elastic Beanstalk application version,
you need the application version's ARN. You can retrieve the ARN by using the following
command.
• Consist of a single ZIP file or WAR file (you can include multiple WAR files inside your ZIP file)
• Not exceed 512 MB
• Not include a parent folder or top-level directory (subdirectories are fine)
If you want to deploy a worker application that processes periodic background tasks, your application
source bundle must also include a cron.yaml file. For more information, see Periodic tasks (p. 485).
If you are deploying your application with the Elastic Beanstalk Command Line Interface (EB CLI), the
AWS Toolkit for Eclipse, or the AWS Toolkit for Visual Studio, the ZIP or WAR file will automatically be
structured correctly. For more information, see Using the Elastic Beanstalk command line interface (EB
CLI) (p. 956), Creating and deploying Java applications on Elastic Beanstalk (p. 108), and The AWS
Toolkit for Visual Studio (p. 212).
Sections
• Creating a source bundle from the command line (p. 386)
• Creating a source bundle with Git (p. 386)
• Zipping files in Mac OS X Finder or Windows explorer (p. 386)
385
AWS Elastic Beanstalk Developer Guide
Creating a source bundle from the command line
This ensures that Elastic Beanstalk configuration files (p. 683) and other files and folders that start with
a period are included in the archive.
The above commands include hidden files that may increase your source bundle size unnecessarily. For
more control, use a more detailed file pattern, or create your source bundle with Git (p. 386).
git archive only includes files that are stored in git, and excludes ignored files and git files. This helps
keep your source bundle as small as possible. For more information, go to the git-archive manual page.
Example
Suppose you have a Python project folder labeled myapp, which includes the following files and
subfolders:
386
AWS Elastic Beanstalk Developer Guide
Zipping files in Mac OS X Finder or Windows explorer
myapplication.py
README.md
static/
static/css
static/css/styles.css
static/img
static/img/favicon.ico
static/img/logo.png
templates/
templates/base.html
templates/index.html
As noted in the list of requirements above, your source bundle must be compressed without a parent
folder, so that its decompressed structure does not include an extra top-level directory. In this example,
no myapp folder should be created when the files are decompressed (or, at the command line, no myapp
segment should be added to the file paths).
This sample file structure is used throughout this topic to illustrate how to zip files.
1. Open your top-level project folder and select all the files and subfolders within it. Do not select the
top-level folder itself.
2. Right-click the selected files, and then choose Compress X items, where X is the number of files and
subfolders you've selected.
387
AWS Elastic Beanstalk Developer Guide
Zipping files in Mac OS X Finder or Windows explorer
1. Open your top-level project folder and select all the files and subfolders within it. Do not select the
top-level folder itself.
388
AWS Elastic Beanstalk Developer Guide
Zipping files in Mac OS X Finder or Windows explorer
2. Right-click the selected files, choose Send to, and then choose Compressed (zipped) folder.
389
AWS Elastic Beanstalk Developer Guide
Creating a source bundle for a .NET application
If you need to manually create a source bundle for your .NET application, you cannot simply create a
ZIP file that contains the project directory. You must create a web deployment package for your project
that is suitable for deployment to Elastic Beanstalk. There are several methods you can use to create a
deployment package:
• Create the deployment package using the Publish Web wizard in Visual Studio. For more information,
go to How to: Create a Web Deployment Package in Visual Studio.
Important
When creating the web deployment package, you must start the Site name with Default
Web Site.
• It you have a .NET project, you can create the deployment package using the msbuild command as
shown in the following example.
390
AWS Elastic Beanstalk Developer Guide
Testing your source bundle
Important
The DeployIisAppPath parameter must begin with Default Web Site.
• If you have a website project, you can use the IIS Web Deploy tool to create the deployment package.
For more information, go to Packaging and Restoring a Web site.
Important
The apphostconfig parameter must begin with Default Web Site.
If you are deploying multiple applications or an ASP.NET Core application, put your .ebextensions
folder in the root of the source bundle, side by side with the application bundles and manifest file:
~/workspace/source-bundle/
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- AspNetCore101HelloWorld.zip
|-- AspNetCoreHelloWorld.zip
|-- aws-windows-deployment-manifest.json
`-- VS2015AspNetWebApiApp.zip
1. Open a terminal window (Mac OS X) or connect to the Linux server. Navigate to the directory that
contains your source bundle.
2. Using the unzip or tar xf command, decompress the archive.
3. Ensure that the decompressed files appear in the same folder as the archive itself, rather than in a
new top-level folder or directory.
Note
If you use Mac OS X Finder to decompress the archive, a new top-level folder will be
created, no matter how you structured the archive itself. For best results, use the command
line.
1. Download or install a program that allows you to extract compressed files via the command line. For
example, you can download the free unzip.exe program from http://stahlforce.com/dev/index.php?
tool=zipunzip.
2. If necessary, copy the executable file to the directory that contains your source bundle. If you've
installed a system-wide tool, you can skip this step.
3. Using the appropriate command, decompress the archive. If you downloaded unzip.exe using the
link in step 1, the command is unzip <archive-name>.
4. Ensure that the decompressed files appear in the same folder as the archive itself, rather than in a
new top-level folder or directory.
391
AWS Elastic Beanstalk Developer Guide
Tagging resources
Here are some ways to use tagging with Elastic Beanstalk resources:
• Deployment stages – Identify resources associated with different stages of your application, such as
development, beta, and production.
• Cost allocation – Use cost allocation reports to track your usage of AWS resources associated with
various expense accounts. The reports include both tagged and untagged resources, and they
aggregate costs according to tags. For information about how cost allocation reports use tags, see Use
Cost Allocation Tags for Custom Billing Reports in the AWS Billing and Cost Management User Guide.
• Access control – Use tags to manage permissions to requests and resources. For example, a user who
can only create and manage beta environments should only have access to beta stage resources. For
details, see Using tags to control access to Elastic Beanstalk resources (p. 910).
You can add up to 50 tags to each resource. Environments are slightly different: Elastic Beanstalk adds
three default system tags to environments, and you can't edit or delete these tags. In addition to the
default tags, you can add up to 47 additional tags to each environment.
• Keys and values can contain letters, numbers, white space, and the following symbols: _ . : / = +
- @
• Keys can contain up to 127 characters. Values can contain up to 255 characters.
Note
These length limits are for Unicode characters in UTF-8. For other multibyte encodings, the
limits might be lower.
• Keys are case sensitive.
• Keys cannot begin with aws: or elasticbeanstalk:.
Tagging applications
You can apply tags to your AWS Elastic Beanstalk applications. Tags are key-value pairs associated with
AWS resources. For information about Elastic Beanstalk resource tagging, use cases, tag key and value
constraints, and supported resource types, see Tagging Elastic Beanstalk application resources (p. 392).
392
AWS Elastic Beanstalk Developer Guide
Tagging applications
You can specify tags when you create an application. In an existing application, you can add or remove
tags, and update the values of existing tags. You can add up to 50 tags to each application.
If you use the EB CLI to create an application, use the --tags option with eb init (p. 1017) to add tags.
393
AWS Elastic Beanstalk Developer Guide
Tagging applications
With the AWS CLI or other API-based clients, add tags by using the --tags parameter on the create-
application command.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. Choose Actions, and then choose Manage tags.
4. Use the on-screen form to add, update, or delete tags.
5. Choose Apply.
If you use the EB CLI to update your application, use eb tags (p. 1040) to add, update, delete, or list
tags.
The following command updates the tag mytag1 and deletes the tag mytag2.
For a complete list of options and more examples, see eb tags (p. 1040).
With the AWS CLI or other API-based clients, use the list-tags-for-resource command to list the tags of
an application.
Specify both tags to add and tags to update in the --tags-to-add parameter of update-tags-for-
resource. A nonexisting tag is added, and an existing tag's value is updated.
Note
To use some of the EB CLI and AWS CLI commands with an Elastic Beanstalk application, you
need the application's ARN. You can retrieve the ARN by using the following command.
394
AWS Elastic Beanstalk Developer Guide
Tagging applications
395
AWS Elastic Beanstalk Developer Guide
Environment management console
Managing environments
AWS Elastic Beanstalk makes it easy to create new environments for your application. You can create
and manage separate environments for development, testing, and production use, and you can deploy
any version (p. 441) of your application to any environment. Environments can be long-running or
temporary. When you terminate an environment, you can save its configuration to recreate it later.
As you develop your application, you will deploy it often, possibly to several different environments for
different purposes. Elastic Beanstalk lets you configure how deployments are performed (p. 444). You
can deploy to all of the instances in your environment simultaneously, or split a deployment into batches
with rolling deployments.
Configuration changes (p. 452) are processed separately from deployments, and have their own
scope. For example, if you change the type of the EC2 instances running your application, all of the
instances must be replaced. On the other hand, if you modify the configuration of the environment's
load balancer, that change can be made in-place without interrupting service or lowering capacity. You
can also apply configuration changes that modify the instances in your environment in batches with
rolling configuration updates (p. 453).
Note
Modify the resources in your environment only by using Elastic Beanstalk. If you modify
resources using another service's console, CLI commands, or SDKs, Elastic Beanstalk won't
be able to accurately monitor the state of those resources, and you won't be able to save the
configuration or reliably recreate the environment. Out-of band-changes can also cause issues
when updating or terminating an environment.
When you launch an environment, you choose a platform version. We update platforms periodically with
new platform versions to provide performance improvements and new features. You can update your
environment to the latest platform version (p. 459) at any time.
As your application grows in complexity, you can split it into multiple components, each running in a
separate environment. For long-running workloads, you can launch worker environments (p. 482) that
process jobs from an Amazon Simple Queue Service (Amazon SQS) queue.
Topics
• Using the Elastic Beanstalk environment management console (p. 396)
• Creating an Elastic Beanstalk environment (p. 407)
• Deploying applications to Elastic Beanstalk environments (p. 441)
• Configuration changes (p. 452)
• Updating your Elastic Beanstalk environment's platform version (p. 459)
• Canceling environment configuration updates and application deployments (p. 477)
• Rebuilding Elastic Beanstalk environments (p. 478)
• Environment types (p. 480)
• Elastic Beanstalk worker environments (p. 482)
• Creating links between Elastic Beanstalk environments (p. 489)
396
AWS Elastic Beanstalk Developer Guide
Environment management console
perform common actions. These actions include restarting the web servers running in your environment,
cloning your environment, or rebuilding your environment from scratch.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
You see the environment overview page. The console's navigation pane shows the name of the
application where the environment belongs, with related application management pages, and the
environment name, with environment management pages.
397
AWS Elastic Beanstalk Developer Guide
Environment overview
Topics
• Environment overview (p. 398)
• Environment actions (p. 399)
• Configuration (p. 401)
• Logs (p. 403)
• Health (p. 403)
• Monitoring (p. 404)
• Alarms (p. 404)
• Managed updates (p. 405)
• Events (p. 405)
• Tags (p. 406)
Environment overview
To view the environment overview page, choose the environment name on the navigation pane, if it's the
current environment. Alternatively, navigate to the environment from the application page or from the
main environment list on the Environments page.
The top pane on the environment overview page shows top-level information about your environment.
This includes its name, URL, and current health status, as well as the name of the currently deployed
application version, and the platform version that the application is running on. You can see the five
most recent environment events below the overview pane.
Choose Refresh to update the information shown. The overview page contains the following information
and options.
URL
The environment's URL is located at the top of the overview and below the environment name. This is
the URL of the web application that the environment is running.
Health
The overall health of the environment. With Enhanced health reporting and monitoring (p. 776)
enabled, the environment status is shown with a Causes button that you can choose to view more
information about the environment's current status.
For Basic health reporting (p. 773) environments, a link to the Monitoring Console (p. 770) is shown.
Running version
The name of the application version that is deployed and running on your environment. Choose Upload
and deploy to upload a source bundle (p. 385) and deploy it to your environment. This option creates a
new application version.
Platform
The name of the platform version running on your environment. Typically, this comprises the
architecture, operating system (OS), language, and application server (collectively known as the platform
branch), with a specific platform version number. Choose Change to select a different platform version.
This option is available only if another version of the platform branch is available.
Updating the platform version using this option replaces instances running in your environment with
new instances.
398
AWS Elastic Beanstalk Developer Guide
Environment actions
Note
When you first use Elastic Beanstalk, only the latest (recommended) version of each platform
branch is available for use. Change first becomes available when a new platform version is
released for the branch. After upgrading to the latest platform branch version, you have the
option to go back to a previous version.
Recent events
The Recent Events section of the environment overview page shows the most recent events emitted by
your environment. This list is updated in real time at the same time that your environment is updated.
Environment actions
The environment overview page contains an Actions menu that you can use to perform common
operations on your environment. This menu is shown on the right side of the environment header next to
the Create a new environment option.
Note
Some actions are only available under certain conditions, remaining disabled until the right
conditions are met.
399
AWS Elastic Beanstalk Developer Guide
Environment actions
Load configuration
Load a previously saved configuration. Configurations are saved to your application and can be loaded by
any associated environment. If you've made changes to your environment's configuration, you can load
a saved configuration to undo those changes. You can also load a configuration that you saved from a
different environment running the same application to propagate configuration changes between them.
Save configuration
Save the current configuration of your environment to your application. Before you make changes
to your environment's configuration, save the current configuration so that you can roll back later, if
needed. You can also apply a saved configuration when you launch a new environment.
Clone environment
Launch a new environment with the same configuration as your currently running environment.
Rebuild environment
Terminate all resources in the running environment and build a new environment with the same
settings. This operation takes several minutes, similar to the amount of time needed for deploying a new
environment from scratch. Any Amazon RDS instances that are running in your environment's data tier
are deleted during a rebuild. If you need the data, create a snapshot. You can create a snapshot manually
in the RDS console or configure your data tier's Deletion Policy to create a snapshot automatically before
deleting the instance. This is the default setting when you create a data tier.
Terminate environment
Terminate all resources in the running environment and remove the environment from the application.
If you have an RDS instance that is running in a data tier and you need to retain its data, make sure
400
AWS Elastic Beanstalk Developer Guide
Configuration
the database deletion policy is set to either Snapshot or Retain. For more information, see Database
lifecycle (p. 578) in the Configuring environments chapter of this guide.
Restore environment
If the environment has been terminated in the last hour, you can restore it from this page. After an hour,
you can restore it from the application overview page (p. 479).
Configuration
The Configuration overview page shows the current configuration of your environment and its
resources, including Amazon EC2 instances, a load balancer, notifications, and health monitoring
settings. Use the settings on this page to customize the behavior of your environment during
deployments, enable additional features, and modify the instance type and other settings that you chose
during environment creation.
401
AWS Elastic Beanstalk Developer Guide
Configuration
For more information, see Configuring Elastic Beanstalk environments (p. 491).
402
AWS Elastic Beanstalk Developer Guide
Logs
Logs
The Logs page lets you retrieve logs from the EC2 instances in your environment. When you request logs,
Elastic Beanstalk sends a command to the instances, which then upload logs to your Elastic Beanstalk
storage bucket in Amazon S3. When you request logs on this page, Elastic Beanstalk automatically
deletes them from Amazon S3 after 15 minutes.
You can also configure your environment's instances to upload logs to Amazon S3 for permanent storage
after they have been rotated locally.
For more information, see Viewing logs from Amazon EC2 instances in your Elastic Beanstalk
environment (p. 820).
Health
If enhanced health monitoring is enabled, the Enhanced health overview page shows live health
information about every instance in your environment. Enhanced health monitoring enables Elastic
Beanstalk to closely monitor the resources in your environment so that it can assess the health of your
application more accurately.
When enhanced health monitoring is enabled, this page shows information about the requests served by
the instances in your environment and metrics from the operating system, including latency, load, and
CPU utilization.
For more information, see Enhanced health reporting and monitoring (p. 776).
403
AWS Elastic Beanstalk Developer Guide
Monitoring
Monitoring
The Monitoring page shows an overview of health information for your environment. This includes
the default set of metrics provided by Elastic Load Balancing and Amazon EC2, and graphs that show
how the environment's health has changed over time. You can use the options on this page to configure
additional graphs for resource-specific metrics, and add alarms for any metric supported by the in-use
health reporting system.
For more information, see Monitoring environment health in the AWS management console (p. 770).
Alarms
The Existing alarms page shows information about any alarms that you have configured for your
environment. You can use the options on this page to modify or delete alarms.
404
AWS Elastic Beanstalk Developer Guide
Managed updates
Managed updates
The Managed updates overview page shows information about upcoming and completed managed
platform updates and instance replacement. These features let you configure your environment to
update to the latest platform version automatically during a weekly maintenance window that you
choose.
In between platform releases, you can choose to have your environment replace all of its Amazon EC2
instances during the maintenance window. This can alleviate issues that occur when your application
runs for extended periods of time.
Events
The Events page shows the event stream for your environment. Elastic Beanstalk outputs event
messages whenever you interact with the environment, and when any of your environment's resources
are created or modified as a result.
405
AWS Elastic Beanstalk Developer Guide
Tags
For more information, see Viewing an Elastic Beanstalk environment's event stream (p. 816).
Tags
The Tags page shows the tags that Elastic Beanstalk applied to the environment when you created it,
and any tags that you added. You can add, edit, and delete custom tags. You can't edit or delete the tags
that Elastic Beanstalk applied.
Environment tags are applied to every resource that Elastic Beanstalk creates to support your
application.
406
AWS Elastic Beanstalk Developer Guide
Creating environments
For more information, see Tagging resources in your Elastic Beanstalk environments (p. 587).
The following procedure launches a new environment running the default application. These steps are
simplified to get your environment up and running quickly, using default option values. For detailed
instructions with descriptions of the many options you can use to configure the resources that Elastic
Beanstalk deploys on your behalf, see The create new environment wizard (p. 409).
Notes
• For instructions on creating and managing environments with the EB CLI, see Managing
Elastic Beanstalk environments with the EB CLI (p. 968).
• Creating an environment requires the permissions in the Elastic Beanstalk full access managed
policy. See Elastic Beanstalk user policy (p. 23) for details.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose an existing application's name in the
list or create one (p. 377).
3. On the application overview page, choose Create a new environment.
407
AWS Elastic Beanstalk Developer Guide
Creating environments
4. Next, for environment tier, choose the Web server environment or Worker environment
environment tier (p. 13). You can't change an environment's tier after creation.
Note
The .NET on Windows Server platform (p. 182) doesn't support the worker environment tier.
5. For Platform, select the platform and platform branch that match the language your application
uses.
Note
Elastic Beanstalk supports multiple versions (p. 29) for most of the platforms that are listed.
By default, the console selects the recommended version for the platform and platform
branch you choose. If your application requires a different version, you can select it here, or
choose Configure more options, as described in step 7. For information about supported
platform versions, see the section called “Supported platforms” (p. 29).
6. For Application code, choose Sample application.
408
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
7. To further customize your environment, choose Configure more options. You can set the following
options only during environment creation:
• Environment name
• Domain name
• Platform version
• Processor
• VPC
• Tier
You can change the following settings after environment creation, but they require new instances or
other resources to be provisioned and can take a long time to apply:
• Instance type, root volume, key pair, and AWS Identity and Access Management (IAM) role
• Internal Amazon RDS database
• Load balancer
For details on all available settings, see The create new environment wizard (p. 409).
8. Choose Create environment.
While Elastic Beanstalk creates your environment, you are redirected to the Elastic Beanstalk
console (p. 396). When the environment health turns green, choose the URL next to the environment
name to view the running application. This URL is generally accessible from the internet unless you
configure your environment to use a custom VPC with an internal load balancer (p. 424).
Topics
• The create new environment wizard (p. 409)
• Clone an Elastic Beanstalk environment (p. 428)
• Terminate an Elastic Beanstalk environment (p. 430)
• Creating Elastic Beanstalk environments with the AWS CLI (p. 431)
• Creating Elastic Beanstalk environments with the API (p. 432)
• Constructing a Launch Now URL (p. 435)
• Creating and updating groups of Elastic Beanstalk environments (p. 439)
This topic describes the Create new environment wizard and all the ways you can use it to configure the
environment you want to create.
409
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
• Name – Enter a name for the environment. The form provides a generated name.
• Domain – (web server environments) Enter a unique domain name for your environment. The default
name is the environment's name. You can enter a different domain name. Elastic Beanstalk uses this
name to create a unique CNAME for the environment. To check whether the domain name you want is
available, choose Check Availability.
• Description – Enter a description for this environment.
• Managed platform
• Custom platform
Managed platform
In most cases you use an Elastic Beanstalk managed platform for your new environment. When the new
environment wizard starts, it selects the Managed platform option by default.
410
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Select a platform, a platform branch within that platform, and a specific platform version in the branch.
When you select a platform branch, the recommended version within the branch is selected by default.
In addition, you can select any platform version you've used before.
Note
For a production environment, we recommend that you choose a platform version in a
supported platform branch. For details about platform branch states, see the Platform Branch
definition in the the section called “Platforms glossary” (p. 24).
Custom platform
If an off-the-shelf platform doesn't meet your needs, you can create a new environment from a custom
platform. To specify a custom platform, choose the Custom platform option, and then select one of the
available custom platforms. If there are no custom platforms available, this option is dimmed.
411
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
• You can use the sample application that Elastic Beanstalk provides for each platform.
• You can use code that you already deployed to Elastic Beanstalk. Choose Existing version and your
application in the Application code section.
• You can upload new code. Choose Upload your code, and then choose Upload. You can upload new
application code from a local file, or you can specify the URL for the Amazon S3 bucket that contains
your application code.
Note
Depending on the platform version you selected, you can upload your application in a ZIP
source bundle (p. 385), a WAR file (p. 115), or a plaintext Docker configuration (p. 50). The file
size limit is 512 MB.
When you choose to upload new code, you can also provide tags to associate with your new code. For
more information about tagging an application version, see the section called “Tagging application
versions” (p. 383).
412
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
413
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
For quick environment creation using default configuration options, you can now choose Create
environment. Choose Configure more options to make additional configuration changes, as described in
the following sections.
The High availability presets include a load balancer, and are recommended for production
environments. Choose them if you want an environment that can run multiple instances for high
availability and scale in response to load. The Single instance presets are primarily recommended for
development. Two of the presets enable Spot Instance requests. For details about Elastic Beanstalk
capacity configuration, see Auto Scaling group (p. 511).
The last preset, Custom configuration, removes all recommended values except role settings and
uses the API defaults. Choose this option if you are deploying a source bundle with configuration
files (p. 683) that set configuration options. Custom configuration is also selected automatically if you
modify either the Low cost or High availability configuration presets.
414
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Configuration Categories
• Software settings (p. 415)
• Instances (p. 416)
• Capacity (p. 417)
• Load balancer (p. 417)
• Rolling updates and deployments (p. 418)
• Security (p. 420)
• Monitoring (p. 421)
• Managed updates (p. 422)
• Notifications (p. 423)
• Network (p. 424)
• Database (p. 425)
• Tags (p. 426)
• Worker environment (p. 427)
Software settings
Use the Modify software configuration page to configure the software on the Amazon Elastic Compute
Cloud (Amazon EC2) instances that run your application. You can configure environment properties, AWS
X-Ray debugging, instance log storing and streaming, and platform-specific settings. For details, see the
section called “Software settings” (p. 590).
415
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Instances
Use the Modify instances configuration page to configure the Amazon EC2 instances that run your
application. For details, see the section called “Amazon EC2 instances” (p. 497).
416
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Capacity
Use the Modify capacity configuration page to configure the compute capacity of your environment and
Auto Scaling group settings to optimize the number and type of instances you're using. You can also
change your environment capacity based on triggers or on a schedule.
A load-balanced environment can run multiple instances for high availability and prevent downtime
during configuration updates and deployments. In a load-balanced environment, the domain name maps
to the load balancer. In a single-instance environment, it maps to an elastic IP address on the instance.
Warning
A single-instance environment isn't production ready. If the instance becomes unstable
during deployment, or Elastic Beanstalk terminates and restarts the instance during a
configuration update, your application can be unavailable for a period of time. Use single-
instance environments for development, testing, or staging. Use load-balanced environments
for production.
For more information about environment capacity settings, see the section called “Auto Scaling
group” (p. 511) and the section called “Amazon EC2 instances” (p. 497).
Load balancer
Use the Modify load balancer configuration page to select a load balancer type and to configure
settings for it. In a load-balanced environment, your environment's load balancer is the entry point for all
traffic headed for your application. Elastic Beanstalk supports several types of load balancer. By default,
the Elastic Beanstalk console creates an Application Load Balancer and configures it to serve HTTP traffic
on port 80.
417
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Note
You can only select your environment's load balancer type during environment creation.
For more information about load balancer types and settings, see the section called “Load
balancer” (p. 526) and the section called “HTTPS” (p. 734).
Use the Modify rolling updates and deployments configuration page to configure how Elastic Beanstalk
processes application deployments and configuration updates for your environment.
418
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Application deployments happen when you upload an updated application source bundle and deploy
it to your environment. For more information about configuring deployments, see the section called
“Deployment options” (p. 444).
Configuration changes that modify the launch configuration (p. 633) or VPC settings (p. 647) require
terminating all instances in your environment and replacing them. For more information about setting
the update type and other options, see the section called “Configuration changes” (p. 452).
419
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Security
Use the Modify security configuration page to configure service and instance security settings.
For a description of Elastic Beanstalk security concepts, see Permissions (p. 20). For more information
about configuring environment security settings, see the section called “Security” (p. 585).
420
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Monitoring
Use the Modify monitoring configuration page to configure health reporting, monitoring rules, and
health event streaming. For details, see the section called “Enable enhanced health” (p. 784), the
section called “Enhanced health rules” (p. 796), and the section called “Streaming environment
health” (p. 839).
421
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Managed updates
Use the Modify managed updates configuration page to configure managed platform updates. You can
decide if you want them enabled, set the schedule, and configure other properties. For details, see the
section called “Managed updates” (p. 464).
422
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Notifications
Use the Modify notifications configuration page to specify an email address to receive email
notifications (p. 600) for important events from your environment.
423
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Network
If you have created a custom VPC (p. 605), the Modify network configuration page to configure your
environment to use it. If you don't choose a VPC, Elastic Beanstalk uses the default VPC and subnets.
424
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Database
Use the Modify database configuration page to add an Amazon Relational Database Service (Amazon
RDS) database to your environment for development and testing. Elastic Beanstalk provides connection
information to your instances by setting environment properties for the database hostname, user name,
password, table name, and port.
425
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Tags
Use the Modify tags configuration page to add tags to the resources in your environment. For
more information about environment tagging, see Tagging resources in your Elastic Beanstalk
environments (p. 587).
426
AWS Elastic Beanstalk Developer Guide
The create new environment wizard
Worker environment
If you're creating a worker tier environment, use the Modify worker configuration page to configure
the worker environment. The worker daemon on the instances in your environment pulls items from an
Amazon Simple Queue Service (Amazon SQS) queue and relays them as post messages to your worker
application. You can choose the Amazon SQS queue that the worker daemon reads from (auto-generated
or existing). You can also configure the messages that the worker daemon sends to your application.
For more information, see the section called “Worker environments” (p. 482).
427
AWS Elastic Beanstalk Developer Guide
Clone an environment
You can only clone an environment to a different platform version of the same platform branch. A
different platform branch isn't guaranteed to be compatible. To use a different platform branch, you
have to manually create a new environment, deploy your application code, and make any necessary
changes in code and options to ensure your application works correctly on the new platform branch.
Note
Elastic Beanstalk doesn't include any unmanaged changes to resources in the clone. Changes to
AWS resources that you make using tools other than the Elastic Beanstalk console, command-
line tools, or API are considered unmanaged changes.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Environment actions, and then do one of the following:
• Choose Clone environment to clone the environment without any changes to the platform
version.
• Choose Clone with latest platform to clone the environment, but with a newer version of the
original environment's platform branch.
4. On the Clone environment page, review the information in the Original Environment section to
verify that you chose the environment from which you want to create a clone.
5. In the New Environment section, you can optionally change the Environment name, Environment
URL, Description, Platform version, and Service role values that Elastic Beanstalk automatically set
based on the original environment.
Note
If the platform version used in the original environment isn't the one recommended for use
in the platform branch, you are warned that a different platform version is recommended.
Choose Platform version, and you can see the recommended platform version on the list—
for example, 3.3.2 (Recommended).
428
AWS Elastic Beanstalk Developer Guide
Clone an environment
429
AWS Elastic Beanstalk Developer Guide
Terminate an environment
You can specify the name of the source environment in the clone command, or leave it out to clone the
default environment for the current project folder. The EB CLI prompts you to enter a name and DNS
prefix for the new environment.
By default, eb clone creates the new environment with the latest available version of the source
environment's platform. To force the EB CLI to use the same version, even if there is a newer version
available, use the --exact option.
For more information about this command, see eb clone (p. 994).
Elastic Beanstalk might fail to terminate your environment. One common reason is that the security
group of another environment has a dependency on the security group of the environment that you
want to terminate. For instructions on how to avoid this problem, see Security groups (p. 503) on the
EC2 Instances page of this guide.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
430
AWS Elastic Beanstalk Developer Guide
With the AWS CLI
Note
When you terminate your environment, the CNAME that's associated with the terminated
environment is freed up to be used by anyone.
It takes a few minutes for Elastic Beanstalk to terminate the AWS resources that are running in the
environment.
AWS CLI
To terminate an environment
API
To terminate an environment
EnvironmentName = SampleAppEnv
https://elasticbeanstalk.us-west-2.amazon.com/?EnvironmentName=SampleAppEnv
&Operation=TerminateEnvironment
&AuthParams
If you don't have an application version for your source yet, create it. For example, the following
command creates an application version from a source bundle in Amazon Simple Storage Service
(Amazon S3).
431
AWS Elastic Beanstalk Developer Guide
With the API
4. Create environment.
[
{
"Namespace": "aws:autoscaling:launchconfiguration",
"OptionName": "IamInstanceProfile",
"Value": "aws-elasticbeanstalk-ec2-role"
}
]
The above option setting defines the IAM instance profile. You can specify the ARN or the profile
name.
5. Determine if the new environment is Green and Ready.
If the new environment does not come up Green and Ready, you should decide if you want to retry
the operation or leave the environment in its current state for investigation. Make sure to terminate
the environment after you are finished, and clean up any unused resources.
Note
You can adjust the timeout period if the environment doesn't launch in a reasonable time.
• CNAMEPrefix = SampleApp
Example
https://elasticbeanstalk.us-east-2.amazonaws.com/?CNAMEPrefix=sampleapplication
&Operation=CheckDNSAvailability
&AuthParams
• ApplicationName = SampleApp
• VersionLabel = Version2
Example
https://elasticbeanstalk.us-east-2.amazonaws.com/?ApplicationName=SampleApp
432
AWS Elastic Beanstalk Developer Guide
With the API
&VersionLabel=Version2
&Operation=DescribeApplicationVersions
&AuthParams
• ApplicationName = SampleApp
• TemplateName = MyConfigTemplate
• SolutionStackName = 64bit%20Amazon%20Linux%202015.03%20v2.0.0%20running
%20Ruby%202.2%20(Passenger%20Standalone)
Example
https://elasticbeanstalk.us-east-2.amazonaws.com/?ApplicationName=SampleApp
&TemplateName=MyConfigTemplate
&Operation=CreateConfigurationTemplate
&SolutionStackName=64bit%20Amazon%20Linux%202015.03%20v2.0.0%20running%20Ruby
%202.2%20(Passenger%20Standalone)
&AuthParams
• EnvironmentName = SampleAppEnv2
• VersionLabel = Version2
• Description = description
• TemplateName = MyConfigTemplate
• ApplicationName = SampleApp
• CNAMEPrefix = sampleapplication
• OptionSettings.member.1.Namespace = aws:autoscaling:launchconfiguration
• OptionSettings.member.1.OptionName = IamInstanceProfile
• OptionSettings.member.1.Value = aws-elasticbeanstalk-ec2-role
Example
https://elasticbeanstalk.us-east-2.amazonaws.com/?ApplicationName=SampleApp
&VersionLabel=Version2
&EnvironmentName=SampleAppEnv2
&TemplateName=MyConfigTemplate
&CNAMEPrefix=sampleapplication
&Description=description
&Operation=CreateEnvironment
&OptionSettings.member.1.Namespace=aws%3Aautoscaling%3Alaunchconfiguration
&OptionSettings.member.1.OptionName=IamInstanceProfile
&OptionSettings.member.1.Value=aws-elasticbeanstalk-ec2-role
&AuthParams
• EnvironmentName = SampleAppEnv2
• VersionLabel = Version2
• Description = description
• TemplateName = MyConfigTemplate
• ApplicationName = SampleApp
433
AWS Elastic Beanstalk Developer Guide
With the API
• Tier = Worker
• OptionSettings.member.1.Namespace = aws:autoscaling:launchconfiguration
• OptionSettings.member.1.OptionName = IamInstanceProfile
• OptionSettings.member.1.Value = aws-elasticbeanstalk-ec2-role
• OptionSettings.member.2.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.2.OptionName = WorkerQueueURL
• OptionSettings.member.2.Value = sqsd.elasticbeanstalk.us-
east-2.amazonaws.com
• OptionSettings.member.3.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.3.OptionName = HttpPath
• OptionSettings.member.3.Value = /
• OptionSettings.member.4.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.4.OptionName = MimeType
• OptionSettings.member.4.Value = application/json
• OptionSettings.member.5.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.5.OptionName = HttpConnections
• OptionSettings.member.5.Value = 75
• OptionSettings.member.6.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.6.OptionName = ConnectTimeout
• OptionSettings.member.6.Value = 10
• OptionSettings.member.7.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.7.OptionName = InactivityTimeout
• OptionSettings.member.7.Value = 10
• OptionSettings.member.8.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.8.OptionName = VisibilityTimeout
• OptionSettings.member.8.Value = 60
• OptionSettings.member.9.Namespace = aws:elasticbeanstalk:sqsd
• OptionSettings.member.9.OptionName = RetentionPeriod
• OptionSettings.member.9.Value = 345600
Example
https://elasticbeanstalk.us-east-2.amazonaws.com/?ApplicationName=SampleApp
&VersionLabel=Version2
&EnvironmentName=SampleAppEnv2
&TemplateName=MyConfigTemplate
&Description=description
&Tier=Worker
&Operation=CreateEnvironment
&OptionSettings.member.1.Namespace=aws%3Aautoscaling%3Alaunchconfiguration
&OptionSettings.member.1.OptionName=IamInstanceProfile
&OptionSettings.member.1.Value=aws-elasticbeanstalk-ec2-role
&OptionSettings.member.2.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.2.OptionName=WorkerQueueURL
&OptionSettings.member.2.Value=sqsd.elasticbeanstalk.us-east-2.amazonaws.com
&OptionSettings.member.3.Namespace=aws%3elasticbeanstalk%3sqsd
&OptionSettings.member.3.OptionName=HttpPath
&OptionSettings.member.3.Value=%2F
&OptionSettings.member.4.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.4.OptionName=MimeType
434
&OptionSettings.member.4.Value=application%2Fjson
AWS Elastic Beanstalk Developer Guide
Launch Now URL
&OptionSettings.member.5.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.5.OptionName=HttpConnections
&OptionSettings.member.5.Value=75
&OptionSettings.member.6.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.6.OptionName=ConnectTimeout
&OptionSettings.member.6.Value=10
&OptionSettings.member.7.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.7.OptionName=InactivityTimeout
&OptionSettings.member.7.Value=10
&OptionSettings.member.8.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.8.OptionName=VisibilityTimeout
&OptionSettings.member.8.Value=60
&OptionSettings.member.9.Namespace=aws%3Aelasticbeanstalk%3Asqsd
&OptionSettings.member.9.OptionName=RetentionPeriod
&OptionSettings.member.9.Value=345600
&AuthParams
A Launch Now URL gives Elastic Beanstalk the minimum information that's required to create an
application: the application name, solution stack, instance type, and environment type. Elastic Beanstalk
uses default values for other configuration details that aren't explicitly specified in your custom Launch
Now URL.
A Launch Now URL uses standard URL syntax. For more information, see RFC 3986 - Uniform Resource
Identifier (URI): Generic Syntax.
URL parameters
The URL must contain the following parameters, which are case sensitive:
• region – Specify an AWS Region. For a list of Regions that are supported by Elastic Beanstalk, see AWS
Elastic Beanstalk Endpoints and Quotas in the AWS General Reference.
• applicationName – Specify the name of your application. Elastic Beanstalk displays the application
name in the Elastic Beanstalk console to distinguish it from other applications. By default, the
application name also forms the basis of the environment name and environment URL.
• platform – Specify the platform version to use for the environment. Use one of the following
methods, then URL-encode your choice:
• Specify a platform ARN without a version. Elastic Beanstalk selects the latest platform version of the
corresponding platform major version. For example, to select the latest Python 3.6 platform version,
specify Python 3.6 running on 64bit Amazon Linux.
• Specify the platform name. Elastic Beanstalk selects the latest version of the platform's latest
language runtime (for example, Python).
For a description of all available platforms and their versions, see Elastic Beanstalk supported
platforms (p. 29).
435
AWS Elastic Beanstalk Developer Guide
Launch Now URL
You can use the AWS Command Line Interface (AWS CLI) to get a list of all the available platform
versions with their respective ARNs. The list-platform-versions command lists detailed
information about all the available platform versions. Use the --filters argument to scope down
the list. For example, you can scope the list to only show the platform versions of a specific language.
The following example queries all the Python platform versions, and pipes the output through a series
of commands. The result is a list of platform version ARNs (without the /version tail), in a human-
readable format, without URL encoding.
The following example adds a Perl command to the last example to URL-encode the output.
A Launch Now URL can optionally contain the following parameters. If you don't include the optional
parameters in your Launch Now URL, Elastic Beanstalk uses default values to create and run your
application. When you don't include the sourceBundleUrl parameter, Elastic Beanstalk uses the default
sample application for the specified platform.
• sourceBundleUrl – Specify the location of your web application source bundle in URL format. For
example, if you uploaded your source bundle to an Amazon S3 bucket, you might specify the value of
the sourceBundleUrl parameter as https://mybucket.s3.amazonaws.com/myobject.
Note
You can specify the value of the sourceBundleUrl parameter as an HTTP URL, but the user's
web browser will convert characters as needed by applying HTML URL encoding.
• environmentType – Specify whether the environment is load balanced and scalable or just a
single instance. For more information, see Environment types (p. 480). You can specify either
LoadBalancing or SingleInstance as the parameter value.
• tierName – Specify whether the environment supports a web application that processes web requests
or a web application that runs background jobs. For more information, see Elastic Beanstalk worker
environments (p. 482). You can specify either WebServer or Worker,
• instanceType – Specify a server with the characteristics (including memory size and CPU power) that
are most appropriate to your application. For more information about Amazon EC2 instance families
and types, see Instance types in the Amazon EC2 User Guide for Linux Instances or Instance types in
the Amazon EC2 User Guide for Windows Instances. For more information about the available instance
types across Regions, see Available instance types in the Amazon EC2 User Guide for Linux Instances or
Available instance types in the Amazon EC2 User Guide for Windows Instances.
436
AWS Elastic Beanstalk Developer Guide
Launch Now URL
• withVpc – Specify whether to create the environment in an Amazon VPC. You can specify either true
or false. For more information about using Elastic Beanstalk with Amazon VPC, see Using Elastic
Beanstalk with Amazon VPC (p. 938).
• withRds – Specify whether to create an Amazon RDS database instance with this environment. For
more information, see Using Elastic Beanstalk with Amazon RDS (p. 923). You can specify either true
or false.
• rdsDBEngine – Specify the database engine that you want to use for your Amazon EC2 instances
in this environment. You can specify mysql, oracle-sel, sqlserver-ex, sqlserver-web, or
sqlserver-se. The default value is mysql.
• rdsDBAllocatedStorage – Specify the allocated database storage size in gigabytes (GB). You can
specify the following values:
• MySQL – 5 to 1024. The default is 5.
• Oracle – 10 to 1024. The default is 10.
• Microsoft SQL Server Express Edition – 30.
• Microsoft SQL Server Web Edition – 30.
• Microsoft SQL Server Standard Edition – 200.
• rdsDBInstanceClass – Specify the database instance type. The default value is db.t2.micro
(db.m1.large is for an environment that's not running in an Amazon VPC). For a list of database
instance classes that are supported by Amazon RDS, see DB Instance Class in the Amazon Relational
Database Service User Guide.
• rdsMultiAZDatabase – Specify whether Elastic Beanstalk needs to create the database instance
across multiple Availability Zones. You can specify either true or false. For more information about
multiple Availability Zone deployments with Amazon RDS, see Regions and Availability Zones in the
Amazon Relational Database Service User Guide.
• rdsDBDeletionPolicy – Specify whether to delete or snapshot the database instance on environment
termination. You can specify either Delete or Snapshot.
Example
The following is an example Launch Now URL. After you construct your own, you can give it to your
users. For example, you can embed the URL on a webpage or in training materials. When users create an
application using the Launch Now URL, the Elastic Beanstalk Create an Application wizard requires no
additional input.
https://console.aws.amazon.com/elasticbeanstalk/home?region=us-west-2#/
newApplication?applicationName=YourCompanySampleApp&platform=PHP%207.3%20running
%20on%2064bit%20Amazon%20Linux&sourceBundleUrl=http://s3.amazonaws.com/mybucket/
myobject&environmentType=SingleInstance&tierName=WebServer&instanceType=m1.small&withVpc=true&withRds=t
When users choose a Launch Now URL, Elastic Beanstalk displays a page similar to the following.
437
AWS Elastic Beanstalk Developer Guide
Launch Now URL
438
AWS Elastic Beanstalk Developer Guide
Compose environments
Create links between Elastic Beanstalk environments to designate one environment as a dependency
of another. When you create a group of environments with the Compose Environments API, Elastic
Beanstalk creates dependent environments only after their dependencies are up and running. For more
information on environment links, see Creating links between Elastic Beanstalk environments (p. 489).
The Compose Environments API uses an environment manifest (p. 727) to store configuration
details that are shared by groups of environments. Each component application must have an env.yaml
configuration file in its application source bundle that specifies the parameters used to create its
environment.
You can use the Compose Environments API with the Elastic Beanstalk command line interface (EB
CLI), the AWS CLI, or an SDK. See Managing multiple Elastic Beanstalk environments as a group with the
EB CLI (p. 985) for EB CLI instructions.
Instead of processing the jobs directly, the front-end application adds jobs to an Amazon SQS queue. The
second environment, worker, pulls jobs from the queue and processes them. worker uses a G2 instance
type that has a high-performance GPU, while front can run on a more cost-effective generic instance
type.
You would organize the project folder, Media Library, into separate directories for each component,
with each directory containing an environment definition file (env.yaml) with the source code for each:
~/workspace/media-library
|-- front
| `-- env.yaml
`-- worker
439
AWS Elastic Beanstalk Developer Guide
Compose environments
`-- env.yaml
The following listings show the env.yaml file for each component application.
~/workspace/media-library/front/env.yaml
EnvironmentName: front+
EnvironmentLinks:
"WORKERQUEUE" : "worker+"
AWSConfigurationTemplateVersion: 1.1.0.0
EnvironmentTier:
Name: WebServer
Type: Standard
SolutionStack: 64bit Amazon Linux 2015.09 v2.0.4 running Java 8
OptionSettings:
aws:autoscaling:launchconfiguration:
InstanceType: m4.large
~/workspace/media-library/worker/env.yaml
EnvironmentName: worker+
AWSConfigurationTemplateVersion: 1.1.0.0
EnvironmentTier:
Name: Worker
Type: SQS/HTTP
SolutionStack: 64bit Amazon Linux 2015.09 v2.0.4 running Java 8
OptionSettings:
aws:autoscaling:launchconfiguration:
InstanceType: g2.2xlarge
After creating an application version (p. 380) for the front-end (front-v1) and worker (worker-v1)
application components, you call the Compose Environments API with the version names. In this
example, we use the AWS CLI to call the API.
440
AWS Elastic Beanstalk Developer Guide
Deployments
"SourceBundle": {
"S3Bucket": "DOC-EXAMPLE-BUCKET",
"S3Key": "worker-v1.zip"
}
}
}
# Create environments:
~$ aws elasticbeanstalk compose-environments --application-name media-library --group-name
dev --version-labels front-v1 worker-v1
The third call creates two environments, front-dev and worker-dev. The API creates the names of the
environments by concatenating the EnvironmentName specified in the env.yaml file with the group
name option specified in the Compose Environments call, separated by a hyphen. The total length of
these two options and the hyphen must not exceed the maximum allowed environment name length of
23 characters.
The application running in the front-dev environment can access the name of the Amazon SQS queue
attached to the worker-dev environment by reading the WORKERQUEUE variable. For more information
on environment links, see Creating links between Elastic Beanstalk environments (p. 489).
Each deployment is identified by a deployment ID. Deployment IDs start at 1 and increment by one with
each deployment and instance configuration change. If you enable enhanced health reporting (p. 776),
Elastic Beanstalk displays the deployment ID in both the health console (p. 787) and the EB
CLI (p. 979) when it reports instance health status. The deployment ID helps you determine the state of
your environment when a rolling update fails.
Elastic Beanstalk provides several deployment policies and settings. For details about configuring a
policy and additional settings, see the section called “Deployment options” (p. 444). The following
table lists the policies and the kinds of environments that support them.
† In this table, a Legacy Windows Server environment is an environment based on a Windows Server
platform configuration that uses an IIS version earlier than IIS 8.5.
441
AWS Elastic Beanstalk Developer Guide
Choosing a deployment policy
Warning
Some policies replace all instances during the deployment or update. This causes all
accumulated Amazon EC2 burst balances to be lost. It happens in the following cases:
The following list provides summary information about the different deployment policies and adds
related considerations.
• All at once – The quickest deployment method. Suitable if you can accept a short loss of service,
and if quick deployments are important to you. With this method, Elastic Beanstalk deploys the new
application version to each instance. Then, the web proxy or application server might need to restart.
As a result, your application might be unavailable to users (or have low availability) for a short time.
• Rolling – Avoids downtime and minimizes reduced availability, at a cost of a longer deployment time.
Suitable if you can't accept any period of completely lost service. With this method, your application
is deployed to your environment one batch of instances at a time. Most bandwidth is retained
throughout the deployment.
• Rolling with additional batch – Avoids any reduced availability, at a cost of an even longer
deployment time compared to the Rolling method. Suitable if you must maintain the same bandwidth
throughout the deployment. With this method, Elastic Beanstalk launches an extra batch of instances,
then performs a rolling deployment. Launching the extra batch takes time, and ensures that the same
bandwidth is retained throughout the deployment.
• Immutable – A slower deployment method, that ensures your new application version is always
deployed to new instances, instead of updating existing instances. It also has the additional advantage
of a quick and safe rollback in case the deployment fails. With this method, Elastic Beanstalk performs
an immutable update (p. 456) to deploy your application. In an immutable update, a second Auto
Scaling group is launched in your environment and the new version serves traffic alongside the old
version until the new instances pass health checks.
• Traffic splitting – A canary testing deployment method. Suitable if you want to test the health of your
new application version using a portion of incoming traffic, while keeping the rest of the traffic served
by the old application version.
Deployment methods
Method
Impact of failed deployment Deploy time Zero No Rollback
Code
downtime
DNS processdeployed
change to
442
AWS Elastic Beanstalk Developer Guide
Deploying a new application version
Method
Impact of failed deployment Deploy time Zero No Rollback
Code
downtime
DNS processdeployed
change to
Immutable
Minimal ✓ ✓ Terminate
New
Yes Yes new instances
instances
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Upload and deploy.
4. Use the on-screen form to upload the application source bundle.
5. Choose Deploy.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
443
AWS Elastic Beanstalk Developer Guide
Other ways to deploy your application
3. In the navigation pane, find your application's name and choose Application versions.
4. Select the application version to deploy.
5. Choose Actions, and then choose Deploy.
6. Select an environment, and then choose Deploy.
For deployments that depend on resource configuration changes or a new version that can't run
alongside the old version, you can launch a new environment with the new version and perform a
CNAME swap for a blue/green deployment (p. 449).
With rolling deployments, Elastic Beanstalk splits the environment's Amazon EC2 instances into batches
and deploys the new version of the application to one batch at a time. It leaves the rest of the instances
in the environment running the old version of the application. During a rolling deployment, some
instances serve requests with the old version of the application, while instances in completed batches
serve other requests with the new version. For details, see the section called “How rolling deployments
work” (p. 447).
To maintain full capacity during deployments, you can configure your environment to launch a
new batch of instances before taking any instances out of service. This option is known as a rolling
deployment with an additional batch. When the deployment completes, Elastic Beanstalk terminates the
additional batch of instances.
Immutable deployments perform an immutable update (p. 456) to launch a full set of new instances
running the new version of the application in a separate Auto Scaling group, alongside the instances
running the old version. Immutable deployments can prevent issues caused by partially completed
rolling deployments. If the new instances don't pass health checks, Elastic Beanstalk terminates them,
leaving the original instances untouched.
Traffic-splitting deployments let you perform canary testing as part of your application deployment. In
a traffic-splitting deployment, Elastic Beanstalk launches a full set of new instances just like during an
immutable deployment. It then forwards a specified percentage of incoming client traffic to the new
application version for a specified evaluation period. If the new instances stay healthy, Elastic Beanstalk
forwards all traffic to them and terminates the old ones. If the new instances don't pass health checks,
or if you choose to abort the deployment, Elastic Beanstalk moves traffic back to the old instances and
terminates the new ones. There's never any service interruption. For details, see the section called “How
traffic-splitting deployments work” (p. 448).
Warning
Some policies replace all instances during the deployment or update. This causes all
accumulated Amazon EC2 burst balances to be lost. It happens in the following cases:
444
AWS Elastic Beanstalk Developer Guide
Deployment options
• Immutable updates
• Deployments with immutable updates or traffic splitting enabled
If your application doesn't pass all health checks, but still operates correctly at a lower health status,
you can allow instances to pass health checks with a lower status, such as Warning, by modifying the
Healthy threshold option. If your deployments fail because they don't pass health checks and you need
to force an update regardless of health status, specify the Ignore health check option.
When you specify a batch size for rolling updates, Elastic Beanstalk also uses that value for rolling
application restarts. Use rolling restarts when you need to restart the proxy and application servers
running on your environment's instances without downtime.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Rolling updates and deployments configuration category, choose Edit.
5. In the Application Deployments section, choose a Deployment policy, batch settings, and health
check options.
6. Choose Apply.
The Application deployments section of the Rolling updates and deployments page has the following
options for application deployments:
For the Rolling and Rolling with additional batch deployment policies you can configure:
• Batch size – The size of the set of instances to deploy in each batch.
Choose Percentage to configure a percentage of the total number of EC2 instances in the Auto
Scaling group (up to 100 percent), or choose Fixed to configure a fixed number of instances (up to the
maximum instance count in your environment's Auto Scaling configuration).
445
AWS Elastic Beanstalk Developer Guide
Deployment options
For the Traffic splitting deployment policy you can configure the following:
• Traffic split – The initial percentage of incoming client traffic that Elastic Beanstalk shifts to
environment instances running the new application version you're deploying.
• Traffic splitting evaluation time – The time period, in minutes, that Elastic Beanstalk waits after an
initial healthy deployment before proceeding to shift all incoming client traffic to the new application
version that you're deploying.
• Ignore health check – Prevents a deployment from rolling back when a batch fails to become healthy
within the Command timeout.
• Healthy threshold – Lowers the threshold at which an instance is considered healthy during rolling
deployments, rolling updates, and immutable updates.
• Command timeout – The number of seconds to wait for an instance to become healthy before
canceling the deployment or, if Ignore health check is set, to continue to the next batch.
446
AWS Elastic Beanstalk Developer Guide
Deployment options
After reattaching the instances in a batch to the load balancer, Elastic Load Balancing waits until they
pass a minimum number of Elastic Load Balancing health checks (the Healthy check count threshold
value), and then starts routing traffic to them. If no health check URL (p. 534) is configured, this can
happen very quickly, because an instance will pass the health check as soon as it can accept a TCP
connection. If a health check URL is configured, the load balancer doesn't route traffic to the updated
instances until they return a 200 OK status code in response to an HTTP GET request to the health
check URL.
Elastic Beanstalk waits until all instances in a batch are healthy before moving on to the next batch.
With basic health reporting (p. 773), instance health depends on the Elastic Load Balancing health
check status. When all instances in the batch pass enough health checks to be considered healthy by
Elastic Load Balancing, the batch is complete. If enhanced health reporting (p. 776) is enabled, Elastic
Beanstalk considers several other factors, including the result of incoming requests. With enhanced
health reporting, all instances must pass 12 consecutive health checks with an OK status (p. 793)
within two minutes for web server environments, and 18 health checks within three minutes for worker
environments.
If a batch of instances does not become healthy within the command timeout (p. 445), the deployment
fails. After a failed deployment, check the health of the instances in your environment (p. 787) for
information about the cause of the failure. Then perform another deployment with a fixed or known
good version of your application to roll back.
If a deployment fails after one or more batches completed successfully, the completed batches run
the new version of your application while any pending batches continue to run the old version. You
can identify the version running on the instances in your environment on the health page (p. 788)
in the console. This page displays the deployment ID of the most recent deployment that executed
447
AWS Elastic Beanstalk Developer Guide
Deployment options
on each instance in your environment. If you terminate instances from the failed deployment, Elastic
Beanstalk replaces them with instances running the application version from the most recent successful
deployment.
During a traffic-splitting deployment, Elastic Beanstalk creates a new set of instances in a separate
temporary Auto Scaling group. Elastic Beanstalk then instructs the load balancer to direct a certain
percentage of your environment's incoming traffic to the new instances. Then, for a configured amount
of time, Elastic Beanstalk tracks the health of the new set of instances. If all is well, Elastic Beanstalk
shifts remaining traffic to the new instances and attaches them to the environment's original Auto
Scaling group, replacing the old instances. Then Elastic Beanstalk cleans up—terminates the old
instances and removes the temporary Auto Scaling group.
Note
The environment's capacity doesn't change during a traffic-splitting deployment. Elastic
Beanstalk launches the same number of instances in the temporary Auto Scaling group as there
are in the original Auto Scaling group at the time the deployment starts. It then maintains a
constant number of instances in both Auto Scaling groups for the deployment duration. Take
this fact into account when configuring the environment's traffic splitting evaluation time.
Rolling back the deployment to the previous application version is quick and doesn't impact service to
client traffic. If the new instances don't pass health checks, or if you choose to abort the deployment,
Elastic Beanstalk moves traffic back to the old instances and terminates the new ones. You can abort
any deployment by using the environment overview page in the Elastic Beanstalk console, and choosing
Abort current operation in Environment actions. You can also call the AbortEnvironmentUpdate API or
the equivalent AWS CLI command.
Traffic-splitting deployments require an Application Load Balancer. Elastic Beanstalk uses this load
balancer type by default when you create your environment using the Elastic Beanstalk console or the EB
CLI.
Use the DeploymentPolicy option to set the deployment type. The following values are supported:
• AllAtOnce – Disables rolling deployments and always deploys to all instances simultaneously.
• Rolling – Enables standard rolling deployments.
• RollingWithAdditionalBatch – Launches an extra batch of instances, before starting the
deployment, to maintain full capacity.
• Immutable – Performs an immutable update (p. 456) for every deployment.
• TrafficSplitting – Performs traffic-splitting deployments to canary-test your application
deployments.
When you enable rolling deployments, set the BatchSize and BatchSizeType options to configure
the size of each batch. For example, to deploy 25 percent of all instances in each batch, specify the
following options and values.
448
AWS Elastic Beanstalk Developer Guide
Blue/Green deployments
Example .ebextensions/rolling-updates.config
option_settings:
aws:elasticbeanstalk:command:
DeploymentPolicy: Rolling
BatchSizeType: Percentage
BatchSize: 25
To deploy to five instances in each batch, regardless of the number of instances running, and to bring
up an extra batch of five instances running the new version before pulling any instances out of service,
specify the following options and values.
Example .ebextensions/rolling-additionalbatch.config
option_settings:
aws:elasticbeanstalk:command:
DeploymentPolicy: RollingWithAdditionalBatch
BatchSizeType: Fixed
BatchSize: 5
To perform an immutable update for each deployment with a health check threshold of Warning, and
proceed with the deployment even if instances in a batch don't pass health checks within a timeout of 15
minutes, specify the following options and values.
Example .ebextensions/immutable-ignorehealth.config
option_settings:
aws:elasticbeanstalk:command:
DeploymentPolicy: Immutable
HealthCheckSuccessThreshold: Warning
IgnoreHealthCheck: true
Timeout: "900"
To perform traffic-splitting deployments, forwarding 15 percent of client traffic to the new application
version and evaluating health for 10 minutes, specify the following options and values.
Example .ebextensions/traffic-splitting.config
option_settings:
aws:elasticbeanstalk:command:
DeploymentPolicy: TrafficSplitting
aws:elasticbeanstalk:trafficsplitting:
NewVersionPercent: "15"
EvaluationTime: "10"
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
449
AWS Elastic Beanstalk Developer Guide
Blue/Green deployments
Blue/green deployments require that your environment runs independently of your production database,
if your application uses one. If your environment includes a database that Elastic Beanstalk created on
your behalf, the database and connection of the environment isn't preserved unless you take specific
actions. If you have a database that you want to retain, use one of the Elastic Beanstalk database
lifecycle options. You can choose the Retain option to keep the database and environment operational
after decoupling the database. For more information see Database lifecycle (p. 578) in the Configuring
environments chapter of this guide.
For instructions on how to configure your application to connect to an Amazon RDS instance that's not
managed by Elastic Beanstalk, see Using Elastic Beanstalk with Amazon RDS (p. 923).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. Clone your current environment (p. 428), or launch a new environment to run the platform version
you want.
3. Deploy the new application version (p. 443) to the new environment.
4. Test the new version on the new environment.
5. On the environment overview page, choose Environment actions, and then choose Swap
environment URLs.
6. For Environment name, select the current environment.
450
AWS Elastic Beanstalk Developer Guide
Blue/Green deployments
7. Choose Swap.
Elastic Beanstalk swaps the CNAME records of the old and new environments, redirecting traffic from the
old version to the new version.
After Elastic Beanstalk completes the swap operation, verify that the new environment responds when
you try to connect to the old environment URL. However, do not terminate your old environment until
451
AWS Elastic Beanstalk Developer Guide
Configuration changes
the DNS changes are propagated and your old DNS records expire. DNS servers don't always clear old
records from their cache based on the time to live (TTL) that you set on your DNS records.
Configuration changes
When you modify configuration option settings in the Configuration section of the environment
management console (p. 396), AWS Elastic Beanstalk propagates the change to all affected resources.
These resources include the load balancer that distributes traffic to the Amazon EC2 instances
running your application, the Auto Scaling group that manages those instances, and the EC2 instances
themselves.
Many configuration changes can be applied to a running environment without replacing existing
instances. For example, setting a health check URL (p. 534) triggers an environment update to
modify the load balancer settings, but doesn't cause any downtime because the instances running your
application continue serving requests while the update is propagated.
Configuration changes that modify the launch configuration (p. 633) or VPC settings (p. 647) require
terminating all instances in your environment and replacing them. For example, when you change
the instance type or SSH key setting for your environment, the EC2 instances must be terminated and
replaced. Elastic Beanstalk provides several policies that determine how this replacement is done.
• Rolling updates – Elastic Beanstalk applies your configuration changes in batches, keeping a minimum
number of instances running and serving traffic at all times. This approach prevents downtime during
the update process. For details, see Rolling updates (p. 453).
• Immutable updates – Elastic Beanstalk launches a temporary Auto Scaling group outside of your
environment with a separate set of instances running with the new configuration. Then Elastic
Beanstalk places these instances behind your environment's load balancer. Old and new instances both
serve traffic until the new instances pass health checks. At that time, Elastic Beanstalk moves the new
instances into your environment's Auto Scaling group and terminates the temporary group and old
instances. For details, see Immutable updates (p. 456).
• Disabled – Elastic Beanstalk makes no attempt to avoid downtime. It terminates your environment's
existing instances and replaces them with new instances running with the new configuration.
Warning
Some policies replace all instances during the deployment or update. This causes all
accumulated Amazon EC2 burst balances to be lost. It happens in the following cases:
452
AWS Elastic Beanstalk Developer Guide
Rolling updates
† For the purpose of this table, a Legacy Windows Server Environment is an environment based on a
Windows Server platform configuration that use an IIS version earlier than IIS 8.5.
Topics
• Elastic Beanstalk rolling environment configuration updates (p. 453)
• Immutable environment updates (p. 456)
Rolling configuration update batches can be processed periodically (time-based), with a delay between
each batch, or based on health. For time-based rolling updates, you can configure the amount of time
that Elastic Beanstalk waits after completing the launch of a batch of instances before moving on to the
next batch. This pause time allows your application to bootstrap and start serving requests.
With health-based rolling updates, Elastic Beanstalk waits until instances in a batch pass health checks
before moving on to the next batch. The health of an instance is determined by the health reporting
system, which can be basic or enhanced. With basic health (p. 773), a batch is considered healthy as
soon as all instances in it pass Elastic Load Balancing (ELB) health checks.
With enhanced health reporting (p. 776), all of the instances in a batch must pass multiple consecutive
health checks before Elastic Beanstalk will move on to the next batch. In addition to ELB health
checks, which check only your instances, enhanced health monitors application logs and the state of
your environment's other resources. In a web server environment with enhanced health, all instances
must pass 12 health checks over the course of two minutes (18 checks over three minutes for worker
environments). If any instance fails one health check, the count resets.
If a batch doesn't become healthy within the rolling update timeout (default is 30 minutes),
the update is canceled. Rolling update timeout is a configuration option (p. 613) that
is available in the aws:autoscaling:updatepolicy:rollingupdate (p. 456)
namespace. If your application doesn't pass health checks with Ok status but is stable
at a different level, you can set the HealthCheckSuccessThreshold option in the
aws:elasticbeanstalk:healthreporting:system (p. 656) namespace to change the level at
which Elastic Beanstalk considers an instance to be healthy.
If the rolling update process fails, Elastic Beanstalk starts another rolling update to roll back to the
previous configuration. A rolling update can fail due to failed health checks or if launching new
instances causes you to exceed the quotas on your account. If you hit a quota on the number of Amazon
EC2 instances, for example, the rolling update can fail when it attempts to provision a batch of new
instances. In this case, the rollback fails as well.
A failed rollback ends the update process and leaves your environment in an unhealthy state.
Unprocessed batches are still running instances with the old configuration, while any batches that
completed successfully have the new configuration. To fix an environment after a failed rollback, first
resolve the underlying issue that caused the update to fail, and then initiate another environment
update.
An alternative method is to deploy the new version of your application to a different environment and
then perform a CNAME swap to redirect traffic with zero downtime. See Blue/Green deployments with
Elastic Beanstalk (p. 449) for more information.
453
AWS Elastic Beanstalk Developer Guide
Rolling updates
Rolling deployments (p. 444) occur whenever you deploy your application and can typically be
performed without replacing instances in your environment. Elastic Beanstalk takes each batch out of
service, deploys the new application version, and then places it back in service.
The exception to this is if you change settings that require instance replacement at the same time you
deploy a new application version. For example, if you change the key name (p. 633) settings in a
configuration file (p. 683) in your source bundle and deploy it to your environment, you trigger a rolling
update. Instead of deploying your new application version to each batch of existing instances, a new
batch of instances is provisioned with the new configuration. In this case, a separate deployment doesn't
occur because the new instances are brought up with the new application version.
Anytime new instances are provisioned as part of an environment update, there is a deployment phase
where your application's source code is deployed to the new instances and any configuration settings
that modify the operating system or software on the instances are applied. Deployment health check
settings (p. 445) (Ignore health check, Healthy threshold, and Command timeout) also apply to
health-based rolling updates and immutable updates during the deployment phase.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Rolling updates and deployments configuration category, choose Edit.
5. In the Configuration updates section, for Rolling update type, select one of the Rolling options.
454
AWS Elastic Beanstalk Developer Guide
Rolling updates
The Configuration updates section of the Rolling updates and deployments page has the following
options for rolling updates:
• Rolling update type – Elastic Beanstalk waits after it finishes updating a batch of instances before
moving on to the next batch, to allow those instances to finish bootstrapping and start serving traffic.
Choose from the following options:
• Rolling based on Health – Wait until instances in the current batch are healthy before placing
instances in service and starting the next batch.
• Rolling based on Time – Specify an amount of time to wait between launching new instances and
placing them in service before starting the next batch.
• Immutable – Apply the configuration change to a fresh group of instances by performing an
immutable update (p. 456).
• Batch size – The number of instances to replace in each batch, between 1 and 10000. By default, this
value is one-third of the minimum size of the Auto Scaling group, rounded up to a whole number.
• Minimum capacity – The minimum number of instances to keep running while other instances are
updated, between 0 and 9999. The default value is either the minimum size of the Auto Scaling group
or one less than the maximum size of the Auto Scaling group, whichever number is lower.
• Pause time (time-based only) – The amount of time to wait after a batch is updated before moving on
to the next batch, to allow your application to start receiving traffic. Between 0 seconds and one hour.
455
AWS Elastic Beanstalk Developer Guide
Immutable updates
• Health – Wait until instances in the current batch are healthy before placing instances in service and
starting the next batch.
• Time – Specify an amount of time to wait between launching new instances and placing them in
service before starting the next batch.
• Immutable – Apply the configuration change to a fresh group of instances by performing an
immutable update (p. 456).
When you enable rolling updates, set the MaxBatchSize and MinInstancesInService options
to configure the size of each batch. For time-based and health-based rolling updates, you can also
configure a PauseTime and Timeout, respectively.
For example, to launch up to five instances at a time, while maintaining at least two instances in service,
and wait five minutes and 30 seconds between batches, specify the following options and values.
Example .ebextensions/timebased.config
option_settings:
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateEnabled: true
MaxBatchSize: 5
MinInstancesInService: 2
RollingUpdateType: Time
PauseTime: PT5M30S
To enable health-based rolling updates, with a 45-minute timeout for each batch, specify the following
options and values.
Example .ebextensions/healthbased.config
option_settings:
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateEnabled: true
MaxBatchSize: 5
MinInstancesInService: 2
RollingUpdateType: Health
Timeout: PT45M
Timeout and PauseTime values must be specified in ISO8601 duration: PT#H#M#S, where each # is the
number of hours, minutes, or seconds, respectively.
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
456
AWS Elastic Beanstalk Developer Guide
Immutable updates
safely. If an immutable environment update fails, the rollback process requires only terminating an
Auto Scaling group. A failed rolling update, on the other hand, requires performing an additional rolling
update to roll back the changes.
To perform an immutable environment update, Elastic Beanstalk creates a second, temporary Auto
Scaling group behind your environment's load balancer to contain the new instances. First, Elastic
Beanstalk launches a single instance with the new configuration in the new group. This instance serves
traffic alongside all of the instances in the original Auto Scaling group that are running the previous
configuration.
When the first instance passes health checks, Elastic Beanstalk launches additional instances with the
new configuration, matching the number of instances running in the original Auto Scaling group. When
all of the new instances pass health checks, Elastic Beanstalk transfers them to the original Auto Scaling
group, and terminates the temporary Auto Scaling group and old instances.
Note
During an immutable environment update, the capacity of your environment doubles for a short
time when the instances in the new Auto Scaling group start serving requests and before the
original Auto Scaling group's instances are terminated. If your environment has many instances,
or you have a low on-demand instance quota, ensure that you have enough capacity to perform
an immutable environment update. If you are near the quota, consider using rolling updates
instead.
Immutable updates require enhanced health reporting (p. 776) to evaluate your environment's health
during the update. Enhanced health reporting combines standard load balancer health checks with
instance monitoring to ensure that the instances running the new configuration are serving requests
successfully (p. 779).
You can also use immutable updates to deploy new versions of your application, as an alternative to
rolling deployments. When you configure Elastic Beanstalk to use immutable updates for application
deployments (p. 444), it replaces all instances in your environment every time you deploy a new version
of your application. If an immutable application deployment fails, Elastic Beanstalk reverts the changes
immediately by terminating the new Auto Scaling group. This can prevent partial fleet deployments,
which can occur when a rolling deployment fails after some batches have already completed.
Warning
Some policies replace all instances during the deployment or update. This causes all
accumulated Amazon EC2 burst balances to be lost. It happens in the following cases:
If an immutable update fails, the new instances upload bundle logs (p. 820) to Amazon S3 before
Elastic Beanstalk terminates them. Elastic Beanstalk leaves logs from a failed immutable update in
Amazon S3 for one hour before deleting them, instead of the standard 15 minutes for bundle and tail
logs.
Note
If you use immutable updates for application version deployments, but not for configuration,
you might encounter an error if you attempt to deploy an application version that contains
configuration changes that would normally trigger a rolling update (for example, configurations
that change instance type). To avoid this, make the configuration change in a separate update,
or configure immutable updates for both deployments and configuration changes.
You can't perform an immutable update in concert with resource configuration changes. For example,
you can't change settings that require instance replacement (p. 452) while also updating other settings,
or perform an immutable deployment with configuration files that change configuration settings or
457
AWS Elastic Beanstalk Developer Guide
Immutable updates
additional resources in your source code. If you attempt to change resource settings (for example, load
balancer settings) and concurrently perform an immutable update, Elastic Beanstalk returns an error.
If your resource configuration changes aren't dependent on your source code change or on
instance configuration, perform them in two updates. If they are dependent, perform a blue/green
deployment (p. 449) instead.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Rolling updates and deployments configuration category, choose Edit.
5. In the Configuration Updates section, set Rolling update type to Immutable.
6. Choose Apply.
458
AWS Elastic Beanstalk Developer Guide
Platform updates
Example .ebextensions/immutable-updates.config
option_settings:
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateType: Immutable
The following example enables immutable updates for both configuration changes and deployments.
Example .ebextensions/immutable-all.config
option_settings:
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateType: Immutable
aws:elasticbeanstalk:command:
DeploymentPolicy: Immutable
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
You can use the Elastic Beanstalk console or the EB CLI to update your environment's platform version.
Depending on the platform version you'd like to update to, Elastic Beanstalk recommends one of two
methods for performing platform updates.
• Method 1 – Update your environment's platform version (p. 462). We recommend this method when
you're updating to the latest platform version within a platform branch—with the same runtime, web
server, application server, and operating system, and without a change in the major platform version.
This is the most common and routine platform update.
• Method 2 – Perform a Blue/Green deployment (p. 463). We recommend this method when you're
updating to a platform version in a different platform branch—with a different runtime, web server,
application server, or operating system, or to a different major platform version. This is a good
approach when you want to take advantage of new runtime capabilities or the latest Elastic Beanstalk
functionality, or when you want to move off of a deprecated or retired platform branch.
Migrating from a legacy platform version (p. 469) requires a blue/green deployment, because these
platform versions are incompatible with currently supported versions.
Migrating a Linux application to Amazon Linux 2 (p. 470) requires a blue/green deployment, because
Amazon Linux 2 platform versions are incompatible with previous Amazon Linux AMI platform
versions.
459
AWS Elastic Beanstalk Developer Guide
Platform updates
For more help with choosing the best platform update method, expand the section for your
environment's platform.
Docker
Use Method 1 (p. 462) to perform platform updates.
Multicontainer Docker
Use Method 1 (p. 462) to perform platform updates.
Preconfigured Docker
Consider the following cases:
• If you're migrating your application to another platform, for example from Go 1.4 (Docker) to Go 1.11
or from Python 3.4 (Docker) to Python 3.6, use Method 2 (p. 463).
• If you're migrating your application to a different Docker container version, for example from Glassfish
4.1 (Docker) to Glassfish 5.0 (Docker), use Method 2 (p. 463).
• If you're updating to a latest platform version with no change in container version or major version,
use Method 1 (p. 462).
Go
Use Method 1 (p. 462) to perform platform updates.
Java SE
Consider the following cases:
• If you're migrating your application to a different Java runtime version, for example from Java 7 to
Java 8, use Method 2 (p. 463).
• If you're updating to a latest platform version with no change in runtime version, use Method
1 (p. 462).
• If you're migrating your application to a different Java runtime version or Tomcat application server
version, for example from Java 7 with Tomcat 7 to Java 8 with Tomcat 8.5, use Method 2 (p. 463).
• If you're migrating your application across major Java with Tomcat platform versions (v1.x.x, v2.x.x,
and v3.x.x), use Method 2 (p. 463).
• If you're updating to a latest platform version with no change in runtime version, application server
version, or major version, use Method 1 (p. 462).
• If you're migrating your application to a different Windows operating system version, for example from
Windows Server 2008 R2 to Windows Server 2016, use Method 2 (p. 463).
460
AWS Elastic Beanstalk Developer Guide
Platform updates
• If you're migrating your application across major Windows Server platform versions, see Migrating
from earlier major versions of the Windows server platform (p. 189), and use Method 2 (p. 463).
• If your application is currently running on a Windows Server platform V2.x.x and you're updating to a
latest platform version, use Method 1 (p. 462).
Note
Windows Server platform versions earlier than v2 aren't semantically versioned. You can only
launch the latest version of each of these Windows Server major platform versions and can't roll
back after an upgrade.
Node.js
Use Method 2 (p. 463) to perform platform updates.
PHP
Consider the following cases:
• If you're migrating your application to a different PHP runtime version, for example from PHP 5.6 to
PHP 7.2, use Method 2 (p. 463).
• If you're migrating your application across major PHP platform versions (v1.x.x and v2.x.x), use Method
2 (p. 463).
• If you're updating to a latest platform version with no change in runtime version or major version, use
Method 1 (p. 462).
Python
Consider the following cases:
• If you're migrating your application to a different Python runtime version, for example from Python
2.7 to Python 3.6, use Method 2 (p. 463).
• If you're migrating your application across major Python platform versions (v1.x.x and v2.x.x), use
Method 2 (p. 463).
• If you're updating to a latest platform version with no change in runtime version or major version, use
Method 1 (p. 462).
Ruby
Consider the following cases:
• If you're migrating your application to a different Ruby runtime version or application server version,
for example from Ruby 2.3 with Puma to Ruby 2.6 with Puma, use Method 2 (p. 463).
• If you're migrating your application across major Ruby platform versions (v1.x.x and v2.x.x), use
Method 2 (p. 463).
• If you're updating to a latest platform version with no change in runtime version, application server
version, or major version, use Method 1 (p. 462).
461
AWS Elastic Beanstalk Developer Guide
Method 1 – Update your environment's platform version
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, under Platform, choose Change.
4. On the Update platform version dialog, select a platform version. The newest (recommended)
platform version in the branch is selected automatically. You can update to any version that you've
used in the past.
462
AWS Elastic Beanstalk Developer Guide
Method 2 – Perform a Blue/Green deployment
5. Choose Save.
To further simplify platform updates, Elastic Beanstalk can manage them for you. You can configure
your environment to apply minor and patch version updates automatically during a configurable weekly
maintenance window. Elastic Beanstalk applies managed updates with no downtime or reduction in
capacity, and cancels the update immediately if instances running your application on the new version
fail health checks. For details, see Managed platform updates (p. 464).
When you migrate across major platform versions or to platform versions with major component
updates, there's a greater likelihood that your application, or some aspects of it, might not function as
expected on the new platform version, and might require changes.
Before performing the migration, update your local development machine to the newer runtime versions
and other components of the platform you plan on migrating to. Verify that your application still works
463
AWS Elastic Beanstalk Developer Guide
Managed updates
as expected, and make any necessary code fixes and changes. Then use the following best practice
procedure to safely migrate your environment to the new platform version.
1. Create a new environment (p. 407), using the new target platform version, and deploy your
application code to it. The new environment should be in the Elastic Beanstalk application that
contains the environment you're migrating. Don't terminate the existing environment yet.
2. Use the new environment to migrate your application. In particular:
• Find and fix any application compatibility issues that you couldn't discover during the
development phase.
• Ensure that any customizations that your application makes using configuration files (p. 683)
work correctly in the new environment. These might include option settings, additional installed
packages, custom security policies, and script or configuration files installed on environment
instances.
• If your application uses a custom Amazon Machine Image (AMI), create a new custom AMI based
on the AMI of the new platform version. To learn more, see Using a custom Amazon machine
image (AMI) (p. 729). Specifically, this is required if your application uses the Windows Server
platform with a custom AMI, and you're migrating to a Windows Server V2 platform version. In
this case, see also Migrating from earlier major versions of the Windows server platform (p. 189).
Iterate on testing and deploying your fixes until you're satisfied with the application on the new
environment.
3. Turn the new environment into your production environment by swapping its CNAME with the
existing production environment's CNAME. For details, see Blue/Green deployments with Elastic
Beanstalk (p. 449).
4. When you're satisfied with the state of your new environment in production, terminate the old
environment. For details, see Terminate an Elastic Beanstalk environment (p. 430).
You can configure your environment to automatically apply patch version updates (p. 467), or both
patch and minor version updates. Managed platform updates don't support updates across platform
branches (updates to different major versions of platform components such as operating system,
runtime, or Elastic Beanstalk components), because these can introduce changes that are backward
incompatible.
You can also configure Elastic Beanstalk to replace all instances in your environment during the
maintenance window, even if a platform update isn't available. Replacing all instances in your
environment is helpful if your application encounters bugs or memory issues when running for a long
period.
On environments created on November 25, 2019 or later using the Elastic Beanstalk console, managed
updates are enabled by default whenever possible. Managed updates require enhanced health (p. 776)
464
AWS Elastic Beanstalk Developer Guide
Managed updates
to be enabled. Enhanced health is enabled by default when you select one of the configuration
presets (p. 414), and disabled when you select Custom configuration. The console can't enable
managed updates for older platform versions that don't support enhanced health, or when enhanced
health is disabled. When the console enables managed updates for a new environment, the Weekly
update window is set to a random day of the week at a random time. Update level is set to Minor and
patch, and Instance replacement is disabled. You can disable or reconfigure managed updates before
the final environment creation step.
For an existing environment, use the Elastic Beanstalk console anytime to configure managed platform
updates.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Managed updates category, choose Edit.
5. Disable or enable Managed updates.
6. If managed updates are enabled, select a maintenance window, and then select an Update level.
7. (Optional) Select Instance replacement to enable weekly instance replacement.
465
AWS Elastic Beanstalk Developer Guide
Managed updates
8. Choose Apply.
Managed platform updates depend on enhanced health reporting (p. 776) to determine that your
application is healthy enough to consider the platform update successful. See Enabling Elastic Beanstalk
enhanced health reporting (p. 784) for instructions.
Sections
• Permissions required to perform managed platform updates (p. 467)
• Managed update maintenance window (p. 467)
• Minor and patch version updates (p. 467)
• Immutable environment updates (p. 467)
• Managing managed updates (p. 468)
• Managed action option namespaces (p. 469)
466
AWS Elastic Beanstalk Developer Guide
Managed updates
For details about other ways to set the managed-updates service role, see the section called “Service
roles” (p. 860).
Note
If you use configuration files (p. 683) to extend your environment to include additional
resources, you might need to add permissions to your environment's managed-updates service
role. Typically you need to add permissions when you reference these resources by name in
other sections or files.
If an update fails, you can find the reason for the failure on the Managed updates (p. 468) page.
In a platform version number, the second number is the minor update version, and the third number is
the patch version. For example, a version 2.0.7 platform version has a minor version of 0 and a patch
version of 7.
In an immutable update, Elastic Beanstalk deploys as many instances as are currently running with the
new platform version. The new instances begin to take requests alongside those running the old version.
If the new set of instances passes all health checks, Elastic Beanstalk terminates the old set of instances,
leaving only instances with the new version.
467
AWS Elastic Beanstalk Developer Guide
Managed updates
Managed platform updates always perform immutable updates, even when you apply them outside of
the maintenance window. If you change the platform version from the Dashboard, Elastic Beanstalk
applies the update policy that you've chosen for configuration updates.
Warning
Some policies replace all instances during the deployment or update. This causes all
accumulated Amazon EC2 burst balances to be lost. It happens in the following cases:
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Managed updates.
The Managed updates overview section provides information about scheduled and pending managed
updates. The History section lists successful updates and failed attempts.
You can choose to apply a scheduled update immediately, instead of waiting until the maintenance
window.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Managed updates.
4. Choose Apply now.
5. Verify the update details, and then choose Apply.
When you apply a managed platform update outside of the maintenance window, Elastic Beanstalk
performs an immutable update. If you update the environment's platform from the Dashboard (p. 398),
or by using a different client, Elastic Beanstalk uses the update type that you selected for configuration
changes (p. 452).
If you don't have a managed update scheduled, your environment might already be running the latest
version. Other reasons for not having an update scheduled include:
• A minor version (p. 467) update is available, but your environment is configured to automatically
apply only patch version updates.
468
AWS Elastic Beanstalk Developer Guide
Upgrade a legacy environment
• Your environment hasn't been scanned since the update was released. Elastic Beanstalk typically
checks for updates every hour.
• An update is pending or already in progress.
When your maintenance window starts or when you choose Apply now, scheduled updates go into
pending status before execution.
The ManagedActionsEnabled option turns on managed platform updates. Set this option to true to
enable managed platform updates, and use the other options to configure update behavior.
Set UpdateLevel to minor or patch to apply both minor and patch version updates, or just patch
version updates, respectively.
When managed platform updates are enabled, you can enable instance replacement by setting the
InstanceRefreshEnabled option to true. When this setting is enabled, Elastic Beanstalk runs an
immutable update on your environment every week, regardless of whether there is a new platform
version available.
The following example configuration file (p. 683) enables managed platform updates for patch version
updates with a maintenance window starting at 9:00 AM UTC each Tuesday.
Example .ebextensions/managed-platform-update.config
option_settings:
aws:elasticbeanstalk:managedactions:
ManagedActionsEnabled: true
PreferredStartTime: "Tue:09:00"
aws:elasticbeanstalk:managedactions:platformupdate:
UpdateLevel: patch
InstanceRefreshEnabled: true
• Configuration files, as described in the Advanced environment customization with configuration files
(.ebextensions) (p. 683) topic
• ELB health checks, as described in the Basic health reporting (p. 773) topic
469
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
• Instance Profiles, as described in the Managing Elastic Beanstalk instance profiles (p. 855) topic
• VPCs, as described in the Using Elastic Beanstalk with Amazon VPC (p. 938) topic
• Data Tiers, as described in the Adding a database to your Elastic Beanstalk environment (p. 577) topic
• Worker Tiers, as described in the Worker environments (p. 15) topic
• Single Instance Environments, as described in the Environment types (p. 480) topic
• Tags, as described in the Tagging resources in your Elastic Beanstalk environments (p. 587) topic
• Rolling Updates, as described in the Elastic Beanstalk rolling environment configuration
updates (p. 453) topic
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, view the Platform name.
Your application is using a legacy platform version if you see (legacy) next to the platform's name.
1. Deploy your application to a new environment. For instructions, go to Creating an Elastic Beanstalk
environment (p. 407).
2. If you have an Amazon RDS DB Instance, update your database security group to allow access to
your EC2 security group for your new environment. For instructions on how to find the name of your
EC2 security group using the AWS Management Console, see Security groups (p. 503). For more
information about configuring your EC2 security group, go to the "Authorizing Network Access to an
Amazon EC2 Security Group" section of Working with DB Security Groups in the Amazon Relational
Database Service User Guide.
3. Swap your environment URL. For instructions, go to Blue/Green deployments with Elastic
Beanstalk (p. 449).
4. Terminate your old environment. For instructions, go to Terminate an Elastic Beanstalk
environment (p. 430).
Note
If you use AWS Identity and Access Management (IAM) then you will need to update your
policies to include AWS CloudFormation and Amazon RDS (if applicable). For more information,
see Using Elastic Beanstalk with AWS Identity and Access Management (p. 854).
470
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
If your Elastic Beanstalk application is based on an Amazon Linux AMI platform branch, use this page to
learn how to migrate your application's environments to Amazon Linux 2. The two platform generations
aren't guaranteed to be backward compatible with your existing application. Furthermore, even if your
application code successfully deploys to the new platform version, it might behave or perform differently
due to operating system and run time differences. Although Amazon Linux AMI and Amazon Linux 2
share the same Linux kernel, they differ in their initialization system, libc versions, the compiler tool
chain, and various packages. We've also updated platform specific versions of runtime, build tools, and
other dependencies. Therefore we recommend that you take your time, test your application thoroughly
in a development environment, and make any necessary adjustments.
Configuration On Amazon Linux 2 platforms, you can use configuration files (p. 683) as before, and
Files all sections work the same way. However, specific settings might not work the same as
they did on previous Amazon Linux AMI platforms. For example:
• Some software packages that you install using a configuration file might not be
available on Amazon Linux 2, or their names might have changed.
• Some platform specific configuration options have moved from their platform
specific namespaces to different, platform agnostic namespaces.
• Proxy configuration files provided in the .ebextensions/nginx directory should
move to the .platform/nginx platform hooks directory. For details, expand
the Reverse Proxy Configuration section in the section called “Extending Linux
platforms” (p. 31).
You still need to use .ebextensions configuration files for any script that needs a
reference to an AWS CloudFormation resource.
Platform Amazon Linux 2 platforms introduce a new way to extend your environment's platform
hooks by adding executable files to hook directories on the environment's instances.
With previous Linux platform versions, you might have used custom platform
hooks (p. 1071). These hooks weren't designed for managed platforms and weren't
supported, but could work in useful ways in some cases. With Amazon Linux 2 platform
471
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
Supported Amazon Linux 2 platform versions support the same reverse proxy servers as each
proxy platform supported in its Amazon Linux AMI platform versions. All Amazon Linux 2
servers platform versions use nginx as their default reverse proxy server. The Tomcat, Node.js,
PHP, and Python platform also support Apache HTTPD as an alternative. All platforms
enable proxy server configuration in a uniform way, as described in this section.
However, configuring the proxy server is slightly different than it was on Amazon Linux
AMI. These are the differences for all platforms:
• Default is nginx – The default proxy server on all Amazon Linux 2 platform versions
is nginx. On Amazon Linux AMI platform versions of Tomcat, PHP, and Python, the
default proxy server was Apache HTTPD.
• Consistent namespace – All Amazon Linux 2 platform versions use the
aws:elasticbeanstalk:environment:proxy namespace to configure the proxy
server. On Amazon Linux AMI platform versions this was a per-platform decision, and
Node.js used a different namespace.
• Configuration file location – You should place proxy configuration files in the
.platform/nginx and .platform/httpd directories on all Amazon Linux 2
platform versions. On Amazon Linux AMI platform versions these locations were
.ebextensions/nginx and .ebextensions/httpd, respectively.
For platform-specific proxy configuration changes, see the section called “Platform
specific considerations” (p. 472). For information about proxy configuration on
Amazon Linux 2 platforms, expand the Reverse Proxy Configuration section in the
section called “Extending Linux platforms” (p. 31).
Enhanced Amazon Linux 2 platform versions enable enhanced health by default. This is a
health change if you don't use the Elastic Beanstalk console to create your environments.
The console enables enhanced health by default whenever possible, regardless of
platform version. For details, see the section called “Enhanced health reporting and
monitoring” (p. 776).
Custom AMI If your environment uses a custom AMI (p. 729), create a new AMI based on Amazon
Linux 2 for your new environment using an Elastic Beanstalk Amazon Linux 2 platform.
Custom The managed AMIs of Amazon Linux 2 platform versions don't support custom
platforms platforms (p. 1066).
Docker
The following table lists migration information for the Amazon Linux 2 platform versions in the Docker
platform (p. 48).
472
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
Storage Elastic Beanstalk configures Docker to use storage drivers to store Docker images
and container data. On Amazon Linux AMI, Elastic Beanstalk used the Device Mapper
storage driver. To improve performance, Elastic Beanstalk provisioned an extra Amazon
EBS volume. On Amazon Linux 2 Docker platform versions, Elastic Beanstalk uses the
OverlayFS storage driver, and achieves even better performance while not requiring a
separate volume anymore.
With Amazon Linux AMI, if you used the BlockDeviceMappings option of the
aws:autoscaling:launchconfiguration namespace to add custom storage
volumes to a Docker environment, we advised you to also add the /dev/xvdcz
Amazon EBS volume that Elastic Beanstalk provisions. Elastic Beanstalk doesn't
provision this volume anymore, so you should remove it from your configuration
files. For details, see the section called “Docker configuration on Amazon Linux AMI
(preceding Amazon Linux 2)” (p. 96).
Proxy server Amazon Linux 2 Docker platform versions don't support standalone containers that
don't run behind a proxy server. On Amazon Linux AMI Docker platform versions,
this used to be possible through the none value of the ProxyServer option in the
aws:elasticbeanstalk:environment:proxy namespace.
Go
The following table lists migration information for the Amazon Linux 2 platform versions in the Go
platform (p. 101).
Port passing On Amazon Linux 2 platforms, Elastic Beanstalk doesn't pass a port value to your
application process through the PORT environment variable. You can simulate this
behavior for your process by configuring a PORT environment property yourself.
However, if you have multiple processes, and you're counting on Elastic Beanstalk
passing incremental port values to your processes (5000, 5100, 5200 etc.), you should
modify your implementation. For details, expand the Reverse proxy configuration section
in the section called “Extending Linux platforms” (p. 31).
Amazon Corretto
The following table lists migration information for the Corretto platform branches in the Java SE
platform (p. 126).
Corretto vs. To implement the Java Platform, Standard Edition (Java SE), Amazon Linux 2 platform
OpenJDK branches use Amazon Corretto, an AWS distribution of the Open Java Development
Kit (OpenJDK). Prior Elastic Beanstalk Java SE platform branches use the OpenJDK
packages included with Amazon Linux AMI.
473
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
Build tools Amazon Linux 2 platforms have newer versions of the build tools: gradle, maven, and
ant.
JAR file On Amazon Linux 2 platforms, if your source bundle (ZIP file) contains a single
handling JAR file and no other files, Elastic Beanstalk no longer renames the JAR file to
application.jar. Renaming occurs only if you submit a JAR file on its own, not
within a ZIP file.
Port passing On Amazon Linux 2 platforms, Elastic Beanstalk doesn't pass a port value to your
application process through the PORT environment variable. You can simulate this
behavior for your process by configuring a PORT environment property yourself.
However, if you have multiple processes, and you're counting on Elastic Beanstalk
passing incremental port values to your processes (5000, 5100, 5200 etc.), you should
modify your implementation. For details, expand the Reverse proxy configuration section
in the section called “Extending Linux platforms” (p. 31).
Java 7 Elastic Beanstalk doesn't support an Amazon Linux 2 Java 7 platform branch. If you
have a Java 7 application, migrate it to Corretto 8 or Corretto 11.
Tomcat
The following table lists migration information for the Amazon Linux 2 platform versions in the Tomcat
platform (p. 115).
Amazon Linux 2 Tomcat platform versions support both the nginx and
ProxyServer
the Apache HTTPD version 2.4 proxy servers. However, Apache version
2.2 isn't supported.
On Amazon Linux AMI platform versions, the default proxy was Apache
2.4. If you used the default proxy setting and added custom proxy
configuration files, your proxy configuration should still work on Amazon
Linux 2. However, if you used the apache/2.2 option value, you now
have to migrate your proxy configuration to Apache version 2.4.
474
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
Application On Amazon Linux 2 platforms, the path to the application's directory on Amazon EC2
path instances of your environment is /var/app/current. It was /var/lib/tomcat8/
webapps on Amazon Linux AMI platforms.
Node.js
The following table lists migration information for the Amazon Linux 2 platform versions in the Node.js
platform (p. 241).
Installed On Amazon Linux 2 platforms, Elastic Beanstalk maintains several Node.js platform
Node.js branches, and only installs the latest version of the Node.js major version corresponding
versions with the platform branch on each platform version. For example, each platform version
in the Node.js 12 platform branch only has Node.js 12.x.y installed by default. On
Amazon Linux AMI platform versions, we installed the multiple versions of multiple
Node.js versions on each platform version, and only maintained a single platform
branch.
Choose the Node.js platform branch that corresponds with the Node.js major version
that your application needs.
Apache On Amazon Linux 2 platforms, if you use the Apache HTTPD proxy server, the HTTPD
HTTPD log log file names are access_log and error_log, which is consistent with all other
file names platforms that support Apache HTTPD. On Amazon Linux AMI platform versions, these
log files were named access.log and error.log, respectively.
For details about log file names and locations for all platforms, see the section called
“How Elastic Beanstalk sets up CloudWatch Logs” (p. 834).
Configuration On Amazon Linux 2 platforms, Elastic Beanstalk doesn't support the configuration
options options in the aws:elasticbeanstalk:container:nodejs namespace. Some of
the options have alternatives. Here's the migration information for each option.
475
AWS Elastic Beanstalk Developer Guide
Upgrade to Amazon Linux 2
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:%s', port);
});
PHP
The following table lists migration information for the Amazon Linux 2 platform versions in the PHP
platform (p. 276).
PHP file On Amazon Linux 2 platforms, PHP files are processed using PHP-FPM (a CGI process
processing manager). On Amazon Linux AMI platforms we used mod_php (an Apache module).
Proxy server Amazon Linux 2 PHP platform versions support both the nginx and the Apache HTTPD
proxy servers. The default is nginx.
Amazon Linux AMI PHP platform versions supported only Apache HTTPD. If you
added custom Apache configuration files, you can set the ProxyServer option in the
aws:elasticbeanstalk:environment:proxy namespace to apache.
Python
The following table lists migration information for the Amazon Linux 2 platform versions in the Python
platform (p. 334).
WSGI server On Amazon Linux 2 platforms, Gunicorn is the default WSGI server. By default, Gunicorn
listens on port 8000. The port might be different than what your application used
on the Amazon Linux AMI platform. If you're setting the WSGIPath option of the
aws:elasticbeanstalk:container:python (p. 680) namespace, replace the
value with Gunicorn's syntax. For details, see the section called “Python configuration
namespaces” (p. 336).
Alternatively, you can use a Procfile to specify and configure the WSGI server. For
details, see the section called “Procfile” (p. 337).
Application On Amazon Linux 2 platforms, the path to the application's directory on Amazon
path EC2 instances of your environment is /var/app/current. It was /opt/python/
current/app on Amazon Linux AMI platforms.
Proxy server Amazon Linux 2 Python platform versions support both the nginx and the Apache
HTTPD proxy servers. The default is nginx.
476
AWS Elastic Beanstalk Developer Guide
Cancel an update
Ruby
The following table lists migration information for the Amazon Linux 2 platform versions in the Ruby
platform (p. 359).
Installed On Amazon Linux 2 platforms, Elastic Beanstalk only installs the latest version of a
Ruby single Ruby version, corresponding with the platform branch, on each platform version.
versions For example, each platform version in the Ruby 2.6 platform branch only has Ruby 2.6.x
installed. On Amazon Linux AMI platform versions, we installed the latest versions of
multiple Ruby versions, for example, 2.4.x, 2.5.x, and 2.6.x.
If your application uses a Ruby version that doesn't correspond to the platform branch
you're using, we recommend that you switch to a platform branch that has the correct
Ruby version for your application.
Application On Amazon Linux 2 platforms, Elastic Beanstalk only installs the Puma application
server server on all Ruby platform versions. You can use a Procfile to start a different
application server, and a Gemfile to install it.
On the Amazon Linux AMI platform, we supported two flavors of platform branches
for each Ruby version—one with the Puma application server and the other with the
Passenger application server. If your application uses Passenger, you can configure your
Ruby environment to install and use Passenger.
For more information and examples, see the section called “The Ruby
platform” (p. 359).
Elastic Beanstalk performs the rollback the same way that it performed the last successful update. For
example, if you have time-based rolling updates enabled in your environment, then Elastic Beanstalk
477
AWS Elastic Beanstalk Developer Guide
Rebuild an environment
will wait the specified pause time between rolling back changes on one batch of instances before rolling
back changes on the next batch. Or, if you recently turned on rolling updates, but the last time you
successfully updated your environment configuration settings was without rolling updates, Elastic
Beanstalk will perform the rollback on all instances simultaneously.
You cannot stop Elastic Beanstalk from rolling back to the previous environment configuration once
it begins to cancel the update. The rollback process continues until all instances in the environment
have the previous environment configuration or until the rollback process fails. For application version
deployments, canceling the deployment simply stops the deployment; some instances will have the new
application version and others will continue to run the existing application version. You can deploy the
same or another application version later.
For more information about rolling updates, see Elastic Beanstalk rolling environment configuration
updates (p. 453). For more information about batched application version deployments, see
Deployment policies and settings (p. 444).
To cancel an update
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Environment actions, and then choose Abort current
operation.
You can also rebuild terminated environments within six weeks (42 days) of their termination. When
you rebuild, Elastic Beanstalk attempts to create a new environment with the same name, ID, and
configuration.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Rebuild environment.
4. Choose Rebuild.
478
AWS Elastic Beanstalk Developer Guide
Rebuilding a terminated environment
Rebuilding a running environment creates new resources that have the same configuration as the old
resources; however, the resource IDs are different, and any data on the old resources is not restored. For
example, rebuilding an environment with an Amazon RDS database instance creates a new database with
the same configuration, but does not apply a snapshot to the new database.
To rebuild a running environment with the Elastic Beanstalk API, use the RebuildEnvironment action
with the AWS CLI or the AWS SDK.
Recently terminated environments appear in the application overview for up to an hour. During this time,
you can view events for the environment in its dashboard (p. 396), and use the Restore environment
action (p. 399) to rebuild it.
To rebuild an environment that is no longer visible, use the Restore terminated environment option
from the application page.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. Choose Actions, and then choose Restore terminated environment.
479
AWS Elastic Beanstalk Developer Guide
Environment types
Elastic Beanstalk attempts to create a new environment with the same name, ID, and configuration. If an
environment with the same name or URL exists when you attempt to rebuild, the rebuild fails. Deleting
the application version that was deployed to the environment will also cause the rebuild to fail.
If you use the EB CLI to manage your environment, use the eb restore command to rebuild a terminated
environment.
$ eb restore e-vdnftxubwq
To rebuild a terminated environment with the Elastic Beanstalk API, use the RebuildEnvironment
action with the AWS CLI or the AWS SDK.
Environment types
In AWS Elastic Beanstalk, you can create a load-balanced, scalable environment or a single-instance
environment. The type of environment that you require depends on the application that you deploy. For
example, you can develop and test an application in a single-instance environment to save costs and
then upgrade that environment to a load-balanced, scalable environment when the application is ready
for production.
Note
A worker environment tier for a web application that processes background tasks doesn't
include a load balancer. However, a worker environment does effectively scale out by adding
instances to the Auto Scaling group to process data from the Amazon SQS queue when the load
necessitates it.
480
AWS Elastic Beanstalk Developer Guide
Single-instance environment
Amazon EC2 Auto Scaling automatically starts additional instances to accommodate increasing load on
your application. If the load on your application decreases, Amazon EC2 Auto Scaling stops instances
but always leaves your specified minimum number of instances running. If your application requires
scalability with the option of running in multiple Availability Zones, use a load-balanced, scalable
environment. If you're not sure which environment type to select, you can pick one and, if required,
switch the environment type later.
Single-instance environment
A single-instance environment contains one Amazon EC2 instance with an Elastic IP address. A single-
instance environment doesn't have a load balancer, which can help you reduce costs compared to a load-
balanced, scalable environment. Although a single-instance environment does use the Amazon EC2 Auto
Scaling service, settings for the minimum number of instances, maximum number of instances, and
desired capacity are all set to 1. Consequently, new instances are not started to accommodate increasing
load on your application.
Use a single-instance environment if you expect your production application to have low traffic or if
you are doing remote development. If you're not sure which environment type to select, you can pick
one and, if required, you can switch the environment type later. For more information, see Changing
environment type (p. 481).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity category, choose Edit.
5. From the Environment Type list, select the type of environment that you want.
481
AWS Elastic Beanstalk Developer Guide
Worker environments
6. Choose Save.
It can take several minutes for the environment to update while Elastic Beanstalk provisions AWS
resources.
If your environment is in a VPC, select subnets to place Elastic Load Balancing and Amazon EC2 instances
in. Each Availability Zone that your application runs in must have both. See Using Elastic Beanstalk with
Amazon VPC (p. 938) for details.
A long-running task is anything that substantially increases the time it takes to complete a request, such
as processing images or videos, sending email, or generating a ZIP archive. These operations can take
only a second or two to complete, but a delay of a few seconds is a lot for a web request that would
otherwise complete in less than 500 ms.
One option is to spawn a worker process locally, return success, and process the task asynchronously.
This works if your instance can keep up with all of the tasks sent to it. Under high load, however, an
482
AWS Elastic Beanstalk Developer Guide
Worker environments
instance can become overwhelmed with background tasks and become unresponsive to higher priority
requests. If individual users can generate multiple tasks, the increase in load might not correspond to an
increase in users, making it hard to scale out your web server tier effectively.
To avoid running long-running tasks locally, you can use the AWS SDK for your programming language
to send them to an Amazon Simple Queue Service (Amazon SQS) queue, and run the process that
performs them on a separate set of instances. You then design these worker instances to take items from
the queue only when they have capacity to run them, preventing them from becoming overwhelmed.
Elastic Beanstalk worker environments simplify this process by managing the Amazon SQS queue and
running a daemon process (p. 484) on each instance that reads from the queue for you. When the
daemon pulls an item from the queue, it sends an HTTP POST request locally to http://localhost/
on port 80 with the contents of the queue message in the body. All that your application needs to do
is perform the long-running task in response to the POST. You can configure the daemon (p. 486) to
post to a different path, use a MIME type other than application/JSON, connect to an existing queue, or
customize connections (maximum concurrent requests), timeouts, and retries.
With periodic tasks (p. 485), you can also configure the worker daemon to queue messages based on a
cron schedule. Each periodic task can POST to a different path. Enable periodic tasks by including a YAML
file in your source code that defines the schedule and path for each task.
483
AWS Elastic Beanstalk Developer Guide
The worker environment SQS daemon
Note
The .NET on Windows Server platform (p. 182) doesn't support worker environments.
Sections
• The worker environment SQS daemon (p. 484)
• Dead-letter queues (p. 485)
• Periodic tasks (p. 485)
• Use Amazon CloudWatch for automatic scaling in worker environment tiers (p. 486)
• Configuring worker environments (p. 486)
When the application in the worker environment returns a 200 OK response to acknowledge that it
has received and successfully processed the request, the daemon sends a DeleteMessage call to the
Amazon SQS queue to delete the message from the queue. If the application returns any response
other than 200 OK, Elastic Beanstalk waits to put the message back in the queue after the configured
ErrorVisibilityTimeout period. If there is no response, Elastic Beanstalk waits to put the message
back in the queue after the InactivityTimeout period so that the message is available for another
attempt at processing.
Note
The properties of Amazon SQS queues (message order, at-least-once delivery, and message
sampling) can affect how you design a web application for a worker environment. For more
information, see Properties of Distributed Queues in the Amazon Simple Queue Service
Developer Guide.
Amazon SQS automatically deletes messages that have been in a queue for longer than the configured
RetentionPeriod.
HTTP headers
Name Value
User-Agent aws-sqsd
aws-sqsd/1.11
484
AWS Elastic Beanstalk Developer Guide
Dead-letter queues
HTTP headers
are added to the header. Binary attributes are
discarded and not included in the header.
Dead-letter queues
Elastic Beanstalk worker environments support Amazon Simple Queue Service (Amazon SQS) dead-letter
queues. A dead-letter queue is a queue where other (source) queues can send messages that for some
reason could not be successfully processed. A primary benefit of using a dead-letter queue is the ability
to sideline and isolate the unsuccessfully processed messages. You can then analyze any messages sent
to the dead-letter queue to try to determine why they were not successfully processed.
If you specify an autogenerated Amazon SQS queue at the time you create your worker environment tier,
a dead-letter queue is enabled by default for a worker environment. If you choose an existing SQS queue
for your worker environment, you must use SQS to configure a dead-letter queue independently. For
information about how to use SQS to configure a dead-letter queue, see Using Amazon SQS Dead Letter
Queues.
You cannot disable dead-letter queues. Messages that cannot be delivered are always eventually sent to
a dead-letter queue. You can, however, effectively disable this feature by setting the MaxRetries option
to the maximum valid value of 100.
If a dead-letter queue isn't configured for your worker environment's Amazon SQS queue, Amazon
SQS keeps messages on the queue until the retention period expires. For details about configuring the
retention period, see the section called “Configuring worker environments” (p. 486).
Note
The Elastic Beanstalk MaxRetries option is equivalent to the SQS MaxReceiveCount
option. If your worker environment doesn't use an autogenerated SQS queue, use the
MaxReceiveCount option in SQS to effectively disable your dead-letter queue. For more
information, see Using Amazon SQS Dead Letter Queues.
For more information about the lifecycle of an SQS message, go to Message Lifecycle.
Periodic tasks
You can define periodic tasks in a file named cron.yaml in your source bundle to add jobs to your
worker environment's queue automatically at a regular interval.
For example, the following cron.yaml file creates two periodic tasks. The first one runs every 12 hours
and the second one runs at 11 PM UTC every day.
Example cron.yaml
version: 1
cron:
- name: "backup-job"
url: "/backup"
schedule: "0 */12 * * *"
- name: "audit"
url: "/audit"
schedule: "0 23 * * *"
The name must be unique for each task. The URL is the path to which the POST request is sent to trigger
the job. The schedule is a CRON expression that determines when the task runs.
485
AWS Elastic Beanstalk Developer Guide
Use Amazon CloudWatch for automatic
scaling in worker environment tiers
When a task runs, the daemon posts a message to the environment's SQS queue with a header indicating
the job that needs to be performed. Any instance in the environment can pick up the message and
process the job.
Note
If you configure your worker environment with an existing SQS queue and choose an Amazon
SQS FIFO queue, periodic tasks aren't supported.
Elastic Beanstalk uses leader election to determine which instance in your worker environment queues
the periodic task. Each instance attempts to become leader by writing to an Amazon DynamoDB table.
The first instance that succeeds is the leader, and must continue to write to the table to maintain leader
status. If the leader goes out of service, another instance quickly takes its place.
For periodic tasks, the worker daemon sets the following additional headers.
HTTP headers
Name Value
You can also set other CloudWatch alarms, as needed, by using the Elastic Beanstalk console, CLI, or the
options file. For more information, see Using Elastic Beanstalk with Amazon CloudWatch (p. 830) and
Create an Auto Scaling group with Step Scaling Policies.
486
AWS Elastic Beanstalk Developer Guide
Configuring worker environments
487
AWS Elastic Beanstalk Developer Guide
Configuring worker environments
Note
You can configure the URL path for posting worker queue messages, but you can't configure
the IP port. Elastic Beanstalk always posts worker queue messages on port 80. The worker
environment application or its proxy must listen to port 80.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Worker configuration category, choose Edit.
• Worker queue – Specify the Amazon SQS queue from which the daemon reads. If you have one, you
can choose an existing queue. If you choose Autogenerated queue, Elastic Beanstalk creates a new
Amazon SQS queue and a corresponding Worker queue URL.
Note
When you choose Autogenerated queue, the queue that Elastic Beanstalk creates is a
standard Amazon SQS queue. When you choose an existing queue, you can provide either a
standard or a FIFO Amazon SQS queue. Be aware that if you provide a FIFO queue, periodic
tasks (p. 485) aren't supported.
• Worker queue URL – If you choose an existing Worker queue, this setting displays the URL associated
with that Amazon SQS queue.
• HTTP path – Specify the relative path to the application that will receive the data from the Amazon
SQS queue. The data is inserted into the message body of an HTTP POST message. The default value is
/.
• MIME type – Indicate the MIME type that the HTTP POST message uses. The default value is
application/json. However, any value is valid because you can create and then specify your own
MIME type.
• HTTP connections – Specify the maximum number of concurrent connections that the daemon can
make to any application within an Amazon EC2 instance. The default is 50. You can specify 1 to 100.
• Visibility timeout – Indicate the amount of time, in seconds, an incoming message from the Amazon
SQS queue is locked for processing. After the configured amount of time has passed, the message is
again made visible in the queue for another daemon to read. Choose a value that is longer than you
expect your application requires to process messages, up to 43200 seconds.
• Error visibility timeout – Indicate the amount of time, in seconds, that elapses before Elastic
Beanstalk returns a message to the Amazon SQS queue after an attempt to process it fails with an
explicit error. You can specify 0 to 43200 seconds.
• Max retries – Specify the maximum number of times Elastic Beanstalk attempts to send the message
to the Amazon SQS queue before moving the message to the dead-letter queue (p. 485). The default
value is 10. You can specify 1 to 100.
488
AWS Elastic Beanstalk Developer Guide
Environment links
Note
The Max retries option doesn't apply if your worker environment's Amazon SQS queues
doesn't have a configured dead-letter queue. In such a case, Amazon SQS retains messages
in the queue and processes them until the period specified by the Retention period option
expires.
• Connection timeout – Indicate the amount of time, in seconds, to wait for successful connections to
an application. The default value is 5. You can specify 1 to 60 seconds.
• Inactivity timeout – Indicate the amount of time, in seconds, to wait for a response on an existing
connection to an application. The default value is 180. You can specify 1 to 36000 seconds.
• Retention period – Indicate the amount of time, in seconds, a message is valid and is actively
processed. The default value is 345600. You can specify 60 to 1209600 seconds.
If you use an existing Amazon SQS queue, the settings that you configure when you create a worker
environment can conflict with settings you configured directly in Amazon SQS. For example, if
you configure a worker environment with a RetentionPeriod value that is higher than the
MessageRetentionPeriod value you set in Amazon SQS, Amazon SQS deletes the message when it
exceeds the MessageRetentionPeriod.
Conversely, if the RetentionPeriod value you configure in the worker environment settings is lower
than the MessageRetentionPeriod value you set in Amazon SQS, the daemon deletes the message
before Amazon SQS can. For VisibilityTimeout, the value that you configure for the daemon in
the worker environment settings overrides the Amazon SQS VisibilityTimeout setting. Ensure that
messages are deleted appropriately by comparing your Elastic Beanstalk settings to your Amazon SQS
settings.
With environment links, you can specify the connections between your application’s component
environments as named references. When you create an environment that defines a link, Elastic
Beanstalk sets an environment variable with the same name as the link. The value of the variable is the
endpoint that you can use to connect to the other component, which can be a web server or worker
environment.
For example, if your application consists of a frontend that collects email addresses and a worker that
sends a welcome email to the email addresses collected by the frontend, you can create a link to the
worker in your frontend and have the frontend automatically discover the endpoint (queue URL) for your
worker.
Define links to other environments in an environment manifest (p. 727), a YAML formatted file
named env.yaml in the root of your application source. The following manifest defines a link to an
environment named worker:
~/workspace/my-app/frontend/env.yaml
489
AWS Elastic Beanstalk Developer Guide
Environment links
AWSConfigurationTemplateVersion: 1.1.0.0
EnvironmentLinks:
"WORKERQUEUE": "worker"
When you create an environment with an application version that includes the above environment
manifest, Elastic Beanstalk looks for an environment named worker that belongs to the same
application. If that environment exists, Elastic Beanstalk creates an environment property named
WORKERQUEUE. The value of WORKERQUEUE is the Amazon SQS queue URL. The frontend application
can read this property in the same manner as an environment variable. See Environment manifest
(env.yaml) (p. 727) for details.
To use environment links, add an environment manifest to your application source and upload it with
the EB CLI, AWS CLI or an SDK. If you use the AWS CLI or an SDK, set the process flag when you call
CreateApplicationVersion:
This option tells Elastic Beanstalk to validate the environment manifest and configuration files in your
source bundle when you create the application version. The EB CLI sets this flag automatically when you
have an environment manifest in your project directory.
Create your environments normally using any client. When you need to terminate environments,
terminate the environment with the link first. If an environment is linked to by another environment,
Elastic Beanstalk will prevent the linked environment from being terminated. To override this protection,
use the ForceTerminate flag. This parameter is available in the AWS CLI as --force-terminate:
490
AWS Elastic Beanstalk Developer Guide
• EC2 instance – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run
web apps on the platform that you choose.
Each platform runs a specific set of software, configuration files, and scripts to support a specific
language version, framework, web container, or combination of these. Most platforms use either
Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves
static assets, and generates access and error logs.
• Instance security group – An Amazon EC2 security group configured to allow inbound traffic on port
80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web
app. By default, traffic isn't allowed on other ports.
• Load balancer – An Elastic Load Balancing load balancer configured to distribute requests to the
instances running your application. A load balancer also eliminates the need to expose your instances
directly to the internet.
• Load balancer security group – An Amazon EC2 security group configured to allow inbound traffic on
port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic
isn't allowed on other ports.
• Auto Scaling group – An Auto Scaling group configured to replace an instance if it is terminated or
becomes unavailable.
• Amazon S3 bucket – A storage location for your source code, logs, and other artifacts that are created
when you use Elastic Beanstalk.
• Amazon CloudWatch alarms – Two CloudWatch alarms that monitor the load on the instances in your
environment and that are triggered if the load is too high or too low. When an alarm is triggered, your
Auto Scaling group scales up or down in response.
• AWS CloudFormation stack – Elastic Beanstalk uses AWS CloudFormation to launch the resources in
your environment and propagate configuration changes. The resources are defined in a template that
you can view in the AWS CloudFormation console.
• Domain name – A domain name that routes to your web app in the form
subdomain.region.elasticbeanstalk.com.
This topic focuses on the resource configuration options available in the Elastic Beanstalk console.
The following topics show how to configure your environment in the console. They also describe the
underlying namespaces that correspond to the console options for use with configuration files or API
configuration options. To learn about advanced configuration methods, see Configuring environments
(advanced) (p. 613).
Topics
• Environment configuration using the Elastic Beanstalk console (p. 492)
• The Amazon EC2 instances for your Elastic Beanstalk environment (p. 497)
491
AWS Elastic Beanstalk Developer Guide
Configuration using the console
• Auto Scaling group for your Elastic Beanstalk environment (p. 511)
• Load balancer for your Elastic Beanstalk environment (p. 526)
• Adding a database to your Elastic Beanstalk environment (p. 577)
• Your AWS Elastic Beanstalk environment security (p. 585)
• Tagging resources in your Elastic Beanstalk environments (p. 587)
• Environment properties and other software settings (p. 590)
• Elastic Beanstalk environment notifications with Amazon SNS (p. 600)
• Configuring Amazon Virtual Private Cloud (Amazon VPC) with Elastic Beanstalk (p. 605)
• Your Elastic Beanstalk environment's Domain name (p. 612)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
You can choose two views for this page. Turn on Table View to see a list of options grouped by category.
492
AWS Elastic Beanstalk Developer Guide
Configuration overview page
You can search for an option by its name or value by entering search terms into a search box. As you
type, the list gets shorter and shows only options that match your search terms.
493
AWS Elastic Beanstalk Developer Guide
Configuration overview page
Turn off Table View to see each category in a separate frame (configuration card).
494
AWS Elastic Beanstalk Developer Guide
Configuration overview page
Choose Edit in a configuration category to get to a related configuration page, where you can see full
option values and make changes. When you're done viewing and modifying options, you can choose one
of the following actions:
• Cancel – Go back to the environment's dashboard without applying your configuration changes. When
you choose Cancel, the console loses any pending changes you made on any configuration category.
495
AWS Elastic Beanstalk Developer Guide
Review changes page
You can also cancel your configuration changes by choosing another console page, like Dashboard or
Logs. In this case, if there are any pending configuration changes, the console prompts you to confirm
that you agree to losing them.
• Review changes – Get a summary of all the pending changes you made in any of the configuration
categories. For details, see Review changes page (p. 496).
• Apply configuration – Apply the changes you made in any of the configuration categories to your
environment. In some cases you're prompted to confirm a consequence of one of your configuration
decisions.
Both tables list each option as a combination of the Namespace and Option Name with which Elastic
Beanstalk identifies it. For details, see Configuration options (p. 613).
• In the Capacity category: Change Instances (Min) from 1 to 2, and Instances (Max) from 2 to 4. This
change corresponds to two changes in the aws:autoscaling:asg namespace on the Changed
Options list.
• In the Software category:
• Enable the Rotate logs option. This change corresponds to a change in the
aws:elasticbeanstalk:hostmanager namespace on the Changed Options list.
• Remove the MY_ENV_PROPERTY environment property. This change corresponds to a single entry
for the aws:elasticbeanstalk:application:environment namespace on the Removed
Options list.
• In the Managed updates category: Enable the Managed updates option. This single configuration
change corresponds to three option changes across two namespaces—the last three items on the
Changed Options list.
The following image shows the lists of your configuration changes on the Review Changes page.
496
AWS Elastic Beanstalk Developer Guide
Amazon EC2 instances
When you're done reviewing your changes, you can choose one of the following actions:
• Continue – Go back to the Configuration overview page. You can then continue making changes or
apply pending ones.
• Apply configuration – Apply the changes you made in any of the configuration categories to your
environment. In some cases you're prompted to confirm a consequence of one of your configuration
decisions.
The instances in your environment are configured to run web apps on the platform that you choose. You
can make changes to various properties and behaviors of your environment's instances when you create
your environment or after it's already running. Or, you can already make these changes by modifying
the source code that you deploy to the environment. For for more information, see the section called
“Configuration options” (p. 613).
Note
The Auto Scaling group (p. 511) in your environment manages the Amazon EC2 instances
that run your application. When you make configuration changes that are described on this
497
AWS Elastic Beanstalk Developer Guide
Amazon EC2 instance types
page, the launch configuration also changes. The launch configuration is either an Amazon
EC2 launch template or an Auto Scaling group launch configuration resource. This change
requires replacement of all instances (p. 452). It also triggers either a rolling update (p. 453) or
immutable update (p. 456), depending on which one is configured.
Elastic Beanstalk supports several Amazon EC2 instance purchasing options: On-Demand Instances,
Reserved Instances, and Spot Instances. An On-Demand Instance is a pay-as-you-go resource—there's
no long-term commitment required when you use it. A Reserved Instance is a pre-purchased billing
discount applied automatically to matching On-Demand instances in your environment. A Spot Instance
is an unused Amazon EC2 instance that is available for less than the On-Demand price. You can enable
Spot Instances in your environment by setting a single option. You can configure Spot Instance usage,
including the mix of On-Demand and Spot Instances, using additional options. For more information, see
Auto Scaling group (p. 511).
Sections
• Amazon EC2 instance types (p. 498)
• Configuring Amazon EC2 instances for your environment (p. 499)
• Configuring AWS EC2 instances for your environment using the AWS CLI (p. 505)
• Recommendations for Graviton arm64 first wave environments (p. 507)
• The aws:autoscaling:launchconfiguration namespace (p. 509)
• Configuring the instance metadata service on your environment's instances (p. 509)
By default, Elastic Beanstalk selects the x86 processor architecture when you create a new environment.
You can choose the processor architecture (x86, arm64) for the instance types only when you’re creating
a new environment. After you create an environment, you can only change the instance types to others
within the same processor architecture of your running environment. You can't change the processor
architecture.
All of the instance types in the configuration for a given Elastic Beanstalk environment must have
the same type of processor architecture. Assume that you add a new instance type to an existing
environment that already has a t2.medium instance type, which is based on x86 architecture. You can
only add another instance type of the same architecture, such as t2.small or t4g.large.
Elastic Beanstalk regularly adds support for new compatible instance types after Amazon EC2 introduces
them. For information about instance types that are available, see Instance types in the Amazon EC2 User
Guide for Linux Instances or Instance types in the Amazon EC2 User Guide for Windows Instances.
Note
Elastic Beanstalk now offers support for Graviton on all of the latest Amazon Linux 2 platforms
across all AWS Graviton supported Regions. For more information about creating an Elastic
498
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
Beanstalk environment with arm64 based instances types, see Configuring Amazon EC2
instances for your environment (p. 499).
Create new environments that run Amazon EC2 instances on arm64 architecture and migrate
your existing applications to them with the deployment options (p. 441) in Elastic Beanstalk.
To learn more about Graviton arm64 based processors, see these AWS resources:
You can't edit your environment’s processor architecture after your environment is created. You can
choose the processor architecture (x86, arm64) for the instance types only during environment creation.
To configure Amazon EC2 instances in the Elastic Beanstalk console during environment
creation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments.
3. Choose Create a new environment (p. 409) to start creating your environment.
4. On the wizard's main page, before choosing Create environment, choose Configure more options.
5. In the Instances configuration category, choose Edit. Make changes to settings in this category, and
then choose Apply. For setting descriptions, see the section the section called “Instances category
settings” (p. 501) on this page.
6. In the Capacity configuration category, choose Edit. Make changes to settings in this category, and
then choose Continue. For setting descriptions, see the section the section called “Capacity category
settings” (p. 504) on this page.
Selecting processor architecture
Scroll down to Processor to select a processor architecture for your EC2 instances. The
console lists processor architectures that are supported by the platform that you chose
earlier in the Create environment panel.
If you don't see the processor architecture that you need, return to the configuration
category list to select a platform that supports it. From the Modify Capacity panel, choose
Cancel. Then, choose Change platform version to choose new platform settings. Next, in
the Capacity configuration category choose Edit tot see the processor architecture choices
again.
499
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
7. Choose Save, and then make any other configuration changes that your environment requires.
8. Choose Create environment.
To configure a running environment’s Amazon EC2 instances in the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Instances configuration category, choose Edit. Make changes to settings in this category, and
then choose Apply. For setting descriptions, see the section the section called “Instances category
settings” (p. 501) on this page.
5. In the Capacity configuration category, choose Edit. Make changes to settings in this category, and
then choose Continue. For setting descriptions, see the section the section called “Capacity category
settings” (p. 504) on this page.
500
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
Options
• Monitoring interval (p. 503)
• Root volume (boot device) (p. 503)
• Instance metadata service (p. 503)
• Security groups (p. 503)
501
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
502
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
Monitoring interval
By default, the instances in your environment publish basic health metrics (p. 773) to Amazon
CloudWatch at five-minute intervals at no additional cost.
For more detailed reporting, you can set the Monitoring interval to 1 minute to increase the frequency
that the resources in your environment publish basic health metrics (p. 775) to CloudWatch at.
CloudWatch service charges apply for one-minute interval metrics. For more information, see Amazon
CloudWatch.
You can modify Root volume type to use magnetic storage or provisioned IOPS SSD volume types and,
if needed, increase the volume size. For provisioned IOPS volumes, you must also select the number of
IOPS to provision. Throughput is only applicable to gp3 SSD volume types. You might enter the desired
throughput to provision. It can range between 125 and 1000 mebibytes per second (MiB/s). Select the
volume type that meets your performance and price requirements.
For more information, see Amazon EBS Volume Types in the Amazon EC2 User Guide for Linux Instances
and Amazon EBS Product Details.
Security groups
The security groups that are attached to your instances determine which traffic is allowed to reach the
instances. They also determine which traffic is allowed to leave the instances. Elastic Beanstalk creates a
security group that allows traffic from the load balancer on the standard ports for HTTP (80) and HTTPS
(443).
You can specify additional security groups that you have created to allow traffic on other ports or from
other sources. For example, you can create a security group for SSH access that allows inbound traffic
on port 22 from a restricted IP address range. Otherwise, for additional security, create one that allows
traffic from a bastion host that only you have access to.
Note
To allow traffic between environment A's instances and environment B's instances, you can add
a rule to the security group that Elastic Beanstalk attached to environment B. Then, you can
specify the security group that Elastic Beanstalk attached to environment A. This allows inbound
traffic from, or outbound traffic to, environment A's instances. However, doing so creates a
dependency between the two security groups. If you later try to terminate environment A,
Elastic Beanstalk can't delete the environment's security group, because environment B's
security group is dependent on it.
503
AWS Elastic Beanstalk Developer Guide
Configuring Amazon EC2 instances for your environment
Therefore, we recommend that you instead first create a separate security group. Then, attach it
to environment A, and specify it in a rule of environment B's security group.
For more information about Amazon EC2 security groups, see Amazon EC2 Security Groups in the
Amazon EC2 User Guide for Linux Instances.
Options
• Instance types (p. 504)
• AMI ID (p. 505)
Instance types
The Instance types setting determines the type of Amazon EC2 instance that's launched to run your
application. This configuration page shows a list of Instance types. You can select one or more instance
types. The Elastic Beanstalk console only displays the instance types based on the processor architecture
that's configured for your environment. Therefore, you can only add instance types of the same
processor architecture.
Choose an instance that's powerful enough to run your application under load, but not so powerful that
it's idle most of the time. For development purposes, the t2 family of instances provides a moderate
amount of power with the ability to burst for short periods of time. For large-scale, high-availability
applications, use a pool of instances to ensure that capacity isn't too strongly affected if any single
instance goes down. Start with an instance type that you can use to run five instances under moderate
loads during normal hours. If any instance fails, the rest of the instances can absorb the rest of the
traffic. The capacity buffer also allows time for the environment to scale up as traffic begins to rise
during peak hours.
504
AWS Elastic Beanstalk Developer Guide
Configuring AWS EC2 instances for
your environment using the AWS CLI
Note
You can't change the processor architecture for an existing environment. However, you can
migrate your applications to another environment that runs the desired processor architecture,
such as arm64. Create a new environment with the desired processor architecture. Then migrate
your applications to the new environment using one of the deployment options (p. 441) in
Elastic Beanstalk.
For more information about Amazon EC2 instance families and types, see Instance types in the Amazon
EC2 User Guide for Linux Instances or Instance types in the Amazon EC2 User Guide for Windows Instances.
To determine which instance types meet your requirements and their supported Regions, see Available
instance types in the Amazon EC2 User Guide for Linux Instances or Available instance types in the
Amazon EC2 User Guide for Windows Instances.
AMI ID
The Amazon Machine Image (AMI) is the Amazon Linux or Windows Server machine image that Elastic
Beanstalk uses to launch Amazon EC2 instances in your environment. Elastic Beanstalk provides machine
images that contain the tools and resources required to run your application.
Elastic Beanstalk selects a default AMI for your environment based on the Region, platform version and
processor architecture that you choose. If you have created a custom AMI (p. 729), replace the default
AMI ID with your own default custom one.
The first two examples creates a new environment. The command specifies an Amazon EC2 instances
type, t4g.small, that's based on arm64 processor architecture. Elastic Beanstalk defaults the Image ID
(AMI) for the EC2 instances based on the Region, platform version and instance type. The instance type
corresponds to a processor architecture. The solution-stack-name parameter applies to platform
version.
As an alternative, use an options.json file to specify the namespace options instead of including them
inline.
505
AWS Elastic Beanstalk Developer Guide
Configuring AWS EC2 instances for
your environment using the AWS CLI
Example
The next two examples update the configuration for an existing environment with the update-
environment command. In this example we're adding another instance type that's also based on arm64
processor architecture. For existing environments, all instance types that are added must have the same
processor architecture. You select the processor architecture for a new environment when you create it.
The processor architecture cannot be changed after you create the environment.
As an alternative, use an options.json file to specify the namespace options instead of including them
inline.
Example
506
AWS Elastic Beanstalk Developer Guide
Recommendations for Graviton
arm64 first wave environments
},
{
"Namespace": "aws:ec2:instances",
"OptionName": "InstanceTypes",
"Value": "t4g.small, t4g.micro"
}
]
The next two examples show more create-environment commands. These examples don't provide
values for InstanceTypes. When InstanceTypes values aren't specified, Elastic Beanstalk defaults
to x86 based processor architecture. The Image ID (AMI) for the environment's EC2 instances will default
according to the Region, platform version and defaulted instance type. The instance type corresponds to
a processor architecture.
As an alternative, use an options.json file to specify the namespace options instead of including them
inline.
Example
507
AWS Elastic Beanstalk Developer Guide
Recommendations for Graviton
arm64 first wave environments
If you created environments with the custom AMIs provided in the first wave releases, we recommend
you do the following to maintain a healthy and working environment.
Note
Elastic Beanstalk will not automatically replace the custom AMIs. You must delete the custom
AMIs in Step 1, so the next platform update in Step 2 will update them.
The procedure that follows guides you through these steps. The AWS CLI examples apply to an
environment that was created with the following information.
To update arm64 environments created under first wave of Graviton arm64 support
2. Update the environment with the most recent platform version. Choose from one of the following
options.
• Console option — Use the Elastic Beanstalk console to update the platform version. For more
information, see Update your environment's platform version (p. 462).
• AWS CLI Option— Run the AWS update-environment command, specifying the most recently
available platform version.
508
AWS Elastic Beanstalk Developer Guide
The aws:autoscaling:launchconfiguration
namespace
Note
The list-available-solution-stacks command provides a list of the platform versions
available for your account in an AWS Region.
3. Use the Elastic Beanstalk console to set up managed platform updates for your environment.
Managed platform updates automatically upgrade your environment to the latest platform version
during a scheduled maintenance window. Your application remains in service during the update
process. For more information, see managed platform updates (p. 464).
The aws:autoscaling:launchconfiguration
namespace
You can use the configuration options (p. 613) in the
aws:autoscaling:launchconfiguration (p. 633) namespace to configure the instances for your
environment, including additional options that aren't available in the console.
The following configuration file (p. 683) example uses the basic configuration options that are in this
topic. For example, it uses the DisableIMDSv1 option, which is discussed in IMDS (p. 509). It also uses
the EC2KeyName and IamInstanceProfile options that are discussed in Security (p. 585), and the
BlockDeviceMappings option, which isn't available in the console.
option_settings:
aws:autoscaling:launchconfiguration:
SecurityGroups: my-securitygroup
MonitoringInterval: "1 minute"
DisableIMDSv1: false
EC2KeyName: my-keypair
IamInstanceProfile: "aws-elasticbeanstalk-ec2-role"
BlockDeviceMappings: "/dev/sdj=:100,/dev/sdh=snap-51eef269,/dev/sdb=ephemeral0"
You can use BlockDeviceMappings to configure additional block devices for your instances. For more
information, see Block Device Mapping in the Amazon EC2 User Guide for Linux Instances.
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
Code can access instance metadata from a running instance using one of two methods: Instance
Metadata Service Version 1 (IMDSv1) or Instance Metadata Service Version 2 (IMDSv2). IMDSv2 uses
session-oriented requests and mitigates several types of vulnerabilities that could be used to try to
509
AWS Elastic Beanstalk Developer Guide
IMDS
access the IMDS. For information about these two methods, see Configuring the instance metadata
service in the Amazon EC2 User Guide for Linux Instances.
Sections
• Platform support for IMDS (p. 510)
• Choosing IMDS methods (p. 510)
• Configuring IMDS using the Elastic Beanstalk console (p. 510)
• The aws:autoscaling:launchconfiguration namespace (p. 511)
• AWS SDK – If your application uses an AWS SDK, make sure you use an the latest version of the SDK.
The AWS SDKs make IMDS calls, and newer SDK versions use IMDSv2 whenever possible. If you ever
disable IMDSv1, or if your application uses an old SDK version, IMDS calls might fail.
• Your application code – If your application makes IMDS calls, consider using the AWS SDK so that you
can make the calls instead of making direct HTTP requests. This way, you don't need to make code
changes to switch between IMDS methods. The AWS SDK uses IMDSv2 whenever possible.
• Elastic Beanstalk platform code – Our code makes IMDS calls through the AWS SDK, and therefore uses
IMDSv2 on all supporting platform versions. If your code uses an up-to-date AWS SDK and makes all
IMDS calls through the SDK, you can safely disable IMDSv1.
To configure IMDS on your Amazon EC2 instances in the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Instances configuration category, choose Edit.
510
AWS Elastic Beanstalk Developer Guide
Auto Scaling group
5. Set Disable IMDSv1 to enforce IMDSv2. Clear Disable IMDSv1 to enable both IMDSv1 and IMDSv2.
6. Choose Apply.
The following configuration file (p. 683) example disables IMDSv1 using the DisableIMDSv1 option.
option_settings:
aws:autoscaling:launchconfiguration:
DisableIMDSv1: true
The Auto Scaling group also applies the launch configuration for the instances in your environment. You
can modify the launch configuration (p. 497) to change the instance type, key pair, Amazon Elastic
Block Store (Amazon EBS) storage, and other settings that can only be configured when you launch an
instance.
The Auto Scaling group uses two Amazon CloudWatch alarms to trigger scaling operations. The
default triggers scale when the average outbound network traffic from each instance is higher than
6 MiB or lower than 2 MiB over a period of five minutes. To use Auto Scaling effectively, configure
triggers (p. 519) that are appropriate for your application, instance type, and service requirements. You
can scale based on several statistics including latency, disk I/O, CPU utilization, and request count.
To optimize your environment's use of Amazon EC2 instances through predictable periods of peak
traffic, configure your Auto Scaling group to change its instance count on a schedule (p. 522). You can
schedule changes to your group's configuration that recur daily or weekly, or schedule one-time changes
to prepare for marketing events that will drive a lot of traffic to your site.
511
AWS Elastic Beanstalk Developer Guide
Spot instance support
As an option, Elastic Beanstalk can combine On-Demand and Spot (p. 512) Instances for your
environment. You can configure Amazon EC2 Auto Scaling to monitor and automatically respond to
changes that affect the availability of your Spot Instances by enabling Capacity Rebalancing.
Auto Scaling monitors the health of each Amazon EC2 instance that it launches. If any instance
terminates unexpectedly, Auto Scaling detects the termination and launches a replacement instance. To
configure the group to use the load balancer's health check mechanism, see Auto Scaling health check
setting (p. 525).
You can configure Auto Scaling for your environment using the Elastic Beanstalk console (p. 514), the
EB CLI (p. 518), or configuration options (p. 518).
Topics
• Spot instance support (p. 512)
• Auto Scaling group configuration using the Elastic Beanstalk console (p. 514)
• Auto Scaling group configuration using the EB CLI (p. 518)
• Configuration options (p. 518)
• Auto Scaling triggers (p. 519)
• Scheduled Auto Scaling actions (p. 522)
• Auto Scaling health check setting (p. 525)
This topic describes the following methods to enable Spot Instance requests for your environment:
• The Elastic Beanstalk console – For more information, see Fleet composition in the section called “Auto
Scaling group configuration using the Elastic Beanstalk console” (p. 514).
• The EB CLI – For more information, see the section called “Auto Scaling group configuration using the
EB CLI” (p. 518).
• The aws:ec2:instances namespace configuration option – For more information, see the section
called “Configuration options” (p. 518).
Important
Demand for Spot Instances can vary significantly from moment to moment, and the availability
of Spot Instances can also vary significantly depending on how many unused Amazon EC2
instances are available. It's always possible that your Spot Instance might be interrupted.
To help minimize the impact of these interruptions to your application, you can enable the
Capacity Rebalancing option included with Amazon EC2 Auto Scaling. With this feature
enabled, EC2 automatically attempts to replace Spot Instances in an Auto Scaling group
before they are interrupted. To enable this feature use the Elastic Beanstalk console
to configure the Auto Scaling group (p. 514). Alternatively, you can set the Elastic
Beanstalk EnableCapacityRebalancing configuration option (p. 518) to true in the
aws:autoscaling:asg (p. 632) namespace.
For more information, see Capacity Rebalancing in the Amazon EC2 Auto Scaling User Guide and
Spot Instance Interruptions in the Amazon EC2 User Guide for Linux Instances.
Elastic Beanstalk provides several configuration options to support the Spot feature. They're discussed in
the following sections that explain configuration of your Auto Scaling group.
Two of these options, in the aws:ec2:instances (p. 644) namespace, deserve special attention:
512
AWS Elastic Beanstalk Developer Guide
Spot instance support
• SpotFleetOnDemandBase
• SpotFleetOnDemandAboveBasePercentage
These two options correlate with the MinSize option in the aws:autoscaling:asg (p. 632) namespace:
• Only MinSize determines your environment’s initial capacity—the number of instances you want
running at a minimum.
• SpotFleetOnDemandBase doesn't affect initial capacity. When Spot is enabled, this option only
determines how many On-Demand Instances are provisioned before any Spot Instances are considered.
• Consider when SpotFleetOnDemandBase is less than MinSize. You'll still get exactly MinSize
instances as initial capacity. At least SpotFleetOnDemandBase of them must be On-Demand
Instances.
• Consider when SpotFleetOnDemandBase is greater than MinSize. As your environment
scales out, you're guaranteed to get at least an additional amount of instances equal to the
difference between the two values. In other words, you're guaranteed to get at least an additional
(SpotFleetOnDemandBase - MinSize) instances that are On-Demand before satisfying the
SpotFleetOnDemandBase requirement.
In production environments, Spot Instances are particularly useful as part of a scalable, load-balanced
environment. We don't recommend using Spot in a single-instance environment. If Spot Instances aren't
available, you might lose the entire capacity (a single instance) of your environment. You may still wish
to use a Spot Instance in a single instance environment for development or testing. When you do, be
sure to set both SpotFleetOnDemandBase and SpotFleetOnDemandAboveBasePercentage to zero.
Any other settings result in an On-Demand Instance.
Notes
• Some older AWS accounts might provide Elastic Beanstalk with default instance types that
don't support Spot Instances (for example, t1.micro). If you enable Spot Instance requests
and you see the error None of the instance types you specified supports Spot, be sure to
configure instance types that support Spot. To choose Spot Instance types, use the Spot
Instance Advisor.
• Enabling Spot Instance requests requires using Amazon EC2 launch templates. When
you configure this feature during environment creation or updates, Elastic Beanstalk
attempts to configure your environment to use Amazon EC2 launch templates (if the
environment isn't using them already). In this case, if your user policy lacks the necessary
permissions, environment creation or updates might fail. Therefore, we recommend that
you use our managed user policy or add the required permissions to your custom policies.
For details about the required permissions, see the section called “Creating a custom user
policy” (p. 880).
The following examples demonstrate different scenarios of setting the various scaling options. All
examples assume a load-balanced environment with Spot Instance requests enabled.
Option settings
MinSize aws:autoscaling:asg 10
MaxSize aws:autoscaling:asg 24
SpotFleetOnDemandBase aws:ec2:instances 4
513
AWS Elastic Beanstalk Developer Guide
Auto Scaling group configuration
using the Elastic Beanstalk console
SpotFleetOnDemandAboveBasePercentage aws:ec2:instances 50
In this example, the environment starts with ten instances, of which seven are On-Demand (four base,
and 50% of the six above base) and three are Spot. The environment can scale out up to 24 instances.
As it scales out, the portion of On-Demand in the part of the fleet above the four base On-Demand
instances is kept at 50%, up to a maximum of 24 instances overall, of which 14 are On-Demand (four
base, and 50% of the 20 above base) and ten are Spot.
Option settings
MinSize aws:autoscaling:asg 4
MaxSize aws:autoscaling:asg 24
SpotFleetOnDemandBase aws:ec2:instances 4
SpotFleetOnDemandAboveBasePercentage aws:ec2:instances 50
In this example, the environment starts with four instances, all of which are On-Demand. The
environment can scale out up to 24 instances. As it scales out, the portion of On-Demand in the part of
the fleet above the four base On-Demand instances is kept at 50%, up to a maximum of 24 instances
overall, of which 14 are On-Demand (four base, and 50% of the 20 above base) and ten are Spot.
Option settings
MinSize aws:autoscaling:asg 3
MaxSize aws:autoscaling:asg 24
SpotFleetOnDemandBase aws:ec2:instances 4
SpotFleetOnDemandAboveBasePercentage aws:ec2:instances 50
In this example, the environment starts with three instances, all of which are On-Demand. The
environment can scale out up to 24 instances. The first additional instance above the initial three is
On-Demand, to complete the four base On-Demand instances. As it scales out further, the portion of
On-Demand in the part of the fleet above the four base On-Demand instances is kept at 50%, up to
a maximum of 24 instances overall, of which 14 are On-Demand (four base, and 50% of the 20 above
base) and ten are Spot.
514
AWS Elastic Beanstalk Developer Guide
Auto Scaling group configuration
using the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Auto Scaling group section, configure the following settings.
The following options are enabled if you select to enable Spot Instance requests:
• Maximum spot price – For recommendations about maximum price options for Spot Instances,
see Spot Instance pricing history in the Amazon EC2 User Guide for Linux Instances.
• On-Demand base – The minimum number of On-Demand Instances that your Auto Scaling
group provisions before considering Spot Instances as your environment scales out.
• On-Demand above base – The percentage of On-Demand Instances as part of any additional
capacity that your Auto Scaling group provisions beyond the On-Demand base instances.
Note
The options On-Demand base and On-Demand above base correlate to the Min and
Max Instances options listed earlier. For more information about these options and
examples, see the section called “Spot instance support” (p. 512).
• Enable Capacity Rebalancing – This option is only relevant when there is at least one
Spot Instance in your Auto Scaling group. When this feature is enabled, EC2 automatically
attempts to replace Spot Instances in the Auto Scaling group before they are interrupted,
minimizing Spot Instance interruptions to your applications. For more information, see Capacity
Rebalancing in the Amazon EC2 Auto Scaling User Guide.
• Instance type – The type of Amazon EC2 instance launched to run your application. For details,
see the section called “Instance types” (p. 504).
• AMI ID – The machine image that Elastic Beanstalk uses to launch Amazon EC2 instances in your
environment. For details, see the section called “AMI ID” (p. 505).
• Availability Zones – Choose the number of Availability Zones to spread your environment's
instances across. By default, the Auto Scaling group launches instances evenly across all usable
zones. To concentrate your instances in fewer zones, choose the number of zones to use. For
production environments, use at least two zones to ensure that your application is available in
case one Availability Zone goes out.
• Placement (optional) – Choose the Availability Zones to use. Use this setting if your instances
need to connect to resources in specific zones, or if you have purchased reserved instances, which
are zone-specific. If you al Cooldown: '720' Custom Availability Zones: 'us-west-2a,us-west-2b'
MaxSize: '4' so set the number of zones, you must choose at least that many custom zones.
515
AWS Elastic Beanstalk Developer Guide
Auto Scaling group configuration
using the Elastic Beanstalk console
If you launch your environment in a custom VPC, you cannot configure this option. In a custom
VPC, you choose Availability Zones for the subnets that you assign to your environment.
• Scaling cooldown – The amount of time, in seconds, to wait for instances to launch or terminate
after scaling, before continuing to evaluate triggers. For more information, see Scaling Cooldowns.
516
AWS Elastic Beanstalk Developer Guide
Auto Scaling group configuration
using the Elastic Beanstalk console
517
AWS Elastic Beanstalk Developer Guide
Auto Scaling group configuration using the EB CLI
6. Choose Apply.
--single
Creates the environment with one Amazon EC2 instance and no load balancer. If you don't use this
option, a load-balancer is added to the environment that's created.
--enable-spot
The following options for the eb create (p. 1003) command can only be used with --enable-spot.
--instance-types
Lists the Amazon EC2 instance types that you want your environment to use.
--spot-max-price
The maximum price per unit hour, in US dollars, that you're willing to pay for a Spot Instance.
For recommendations about maximum price options for Spot Instances, see Spot Instance
pricing history in the Amazon EC2 User Guide for Linux Instances.
--on-demand-base-capacity
The minimum number of On-Demand Instances that your Auto Scaling group provisions before
considering Spot Instances as your environment scales up.
--on-demand-above-base-capacity
The percentage of On-Demand Instances as part of additional capacity that your Auto Scaling
group provisions that's more than the number of instances that's specified by the --on-
demand-base-capacity option.
The following example creates an environment and configures the Auto Scaling group to enable Spot
Instance requests for the new environment. For this example, three possible instance types can be used.
Important
There is another similarly named option that's called --instance-type (no “s”) that the EB
CLI only recognizes when processing On-Demand Instances. Don't use --instance-type (no
"s") with the --enable-spot option. If you do, the EB CLI ignores it. Instead use --instance-
types (with "s") with the --enable-spot option.
Configuration options
Elastic Beanstalk provides configuration options (p. 613) for Auto Scaling settings in two namespaces:
aws:autoscaling:asg (p. 632) and aws:ec2:instances (p. 644).
518
AWS Elastic Beanstalk Developer Guide
Triggers
The following configuration file (p. 683) example configures the Auto Scaling group to use two to
four instances, specific availability zones, and a cooldown period of 12 minutes (720 seconds). Capacity
Rebalancing for Spot Instances is enabled. This last option only takes effect if EnableSpot is set to
true in the aws:ec2:instances (p. 644) namespace, as shown in the configuration file example
following this one.
option_settings:
aws:autoscaling:asg:
Availability Zones: Any
Cooldown: '720'
Custom Availability Zones: 'us-west-2a,us-west-2b'
MaxSize: '4'
MinSize: '2'
EnableCapacityRebalancing: true
When you update your environment configuration and remove one or more instance types from the
InstanceTypes option, Elastic Beanstalk terminates any Amazon EC2 instances running on any of
the removed instance types. Your environment's Auto Scaling group then launches new instances, as
necessary to complete the desired capacity, using your current specified instance types.
The following configuration file (p. 683) example configures the Auto Scaling group to enable Spot
Instance requests for your environment. Three possible instance types can be used. At least one On-
Demand Instance is used for baseline capacity, and a sustained 33% of On-Demand Instances is used for
any additional capacity.
option_settings:
aws:ec2:instances:
EnableSpot: true
InstanceTypes: 't2.micro,t3.micro,t3.small'
SpotFleetOnDemandBase: '1'
SpotFleetOnDemandAboveBasePercentage: '33'
For more information about CloudWatch metrics and alarms, see Amazon CloudWatch Concepts in the
Amazon CloudWatch User Guide.
519
AWS Elastic Beanstalk Developer Guide
Triggers
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Scaling triggers section, configure the following settings:
520
AWS Elastic Beanstalk Developer Guide
Triggers
6. Choose Apply.
521
AWS Elastic Beanstalk Developer Guide
Scheduled actions
option_settings:
AWSEBAutoScalingScaleDownPolicy.aws:autoscaling:trigger:
LowerBreachScaleIncrement: '-1'
AWSEBAutoScalingScaleUpPolicy.aws:autoscaling:trigger:
UpperBreachScaleIncrement: '1'
AWSEBCloudwatchAlarmHigh.aws:autoscaling:trigger:
UpperThreshold: '6000000'
AWSEBCloudwatchAlarmLow.aws:autoscaling:trigger:
BreachDuration: '5'
EvaluationPeriods: '1'
LowerThreshold: '2000000'
MeasureName: NetworkOut
Period: '5'
Statistic: Average
Unit: Bytes
You can define up to 120 active scheduled actions per environment. Elastic Beanstalk also retains up to
150 expired scheduled actions, which you can reuse by updating their settings.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. In the Time-based scaling section, choose Add scheduled action.
522
AWS Elastic Beanstalk Developer Guide
Scheduled actions
For recurrent actions, a start time is optional. Specify it to choose the earliest time the action is
performed. After this time, the action recurs according to the Recurrence expression.
• Recurrence – Use a Cron expression to specify the frequency with which you want the scheduled
action to occur. For example, 30 6 * * 2 runs the action every Tuesday at 6:30 AM UTC.
• End time (optional) – Optional for recurrent actions. If specified, the action recurs according to the
Recurrence expression, and is not performed again after this time.
When a scheduled action ends, Auto Scaling doesn't automatically go back to its previous settings.
Configure a second scheduled action to return Auto Scaling to the original settings as needed.
7. Choose Add.
8. Choose Apply.
Note
Scheduled actions will not be saved until applied.
523
AWS Elastic Beanstalk Developer Guide
Scheduled actions
These methods also let you access the Suspend option (p. 639) to temporarily deactivate a recurrent
scheduled action.
Note
When working with scheduled action configuration options outside of the console, use ISO 8601
time format to specify start and end times in UTC. For example, 2015-04-28T04:07:02Z. For
more information about ISO 8601 time format, see Date and Time Formats. The dates must be
unique across all scheduled actions.
Elastic Beanstalk provides configuration options for scheduled action settings in the
aws:autoscaling:scheduledaction (p. 639) namespace. Use the resource_name field to specify
the name of the scheduled action.
Example Scheduled-scale-up-specific-time-long.config
This configuration file instructs Elastic Beanstalk to scale out from five instances to 10 instances at
2015-12-12T00:00:00Z.
option_settings:
- namespace: aws:autoscaling:scheduledaction
resource_name: ScheduledScaleUpSpecificTime
option_name: MinSize
value: '5'
- namespace: aws:autoscaling:scheduledaction
resource_name: ScheduledScaleUpSpecificTime
option_name: MaxSize
value: '10'
- namespace: aws:autoscaling:scheduledaction
resource_name: ScheduledScaleUpSpecificTime
option_name: DesiredCapacity
value: '5'
- namespace: aws:autoscaling:scheduledaction
resource_name: ScheduledScaleUpSpecificTime
option_name: StartTime
value: '2015-12-12T00:00:00Z'
Example Scheduled-scale-up-specific-time.config
To use the shorthand syntax with the EB CLI or configuration files, prepend the resource name to the
namespace.
option_settings:
ScheduledScaleUpSpecificTime.aws:autoscaling:scheduledaction:
MinSize: '5'
MaxSize: '10'
DesiredCapacity: '5'
StartTime: '2015-12-12T00:00:00Z'
Example Scheduled-scale-down-specific-time.config
option_settings:
ScheduledScaleDownSpecificTime.aws:autoscaling:scheduledaction:
MinSize: '1'
MaxSize: '1'
DesiredCapacity: '1'
StartTime: '2015-12-12T07:00:00Z'
524
AWS Elastic Beanstalk Developer Guide
Health check setting
Example Scheduled-periodic-scale-up.config
This configuration file instructs Elastic Beanstalk to scale out every day at 9AM. The action is scheduled
to begin May 14, 2015 and end January 12, 2016.
option_settings:
ScheduledPeriodicScaleUp.aws:autoscaling:scheduledaction:
MinSize: '5'
MaxSize: '10'
DesiredCapacity: '5'
StartTime: '2015-05-14T07:00:00Z'
EndTime: '2016-01-12T07:00:00Z'
Recurrence: 0 9 * * *
Example Scheduled-periodic-scale-down.config
This configuration file instructs Elastic Beanstalk to scale in to no running instance every day at 6PM.
If you know that your application is mostly idle outside of business hours, you can create a similar
scheduled action. If your application must be down outside of business hours, change MaxSize to 0.
option_settings:
ScheduledPeriodicScaleDown.aws:autoscaling:scheduledaction:
MinSize: '0'
MaxSize: '1'
DesiredCapacity: '0'
StartTime: '2015-05-14T07:00:00Z'
EndTime: '2016-01-12T07:00:00Z'
Recurrence: 0 18 * * *
Example Scheduled-weekend-scale-down.config
This configuration file instructs Elastic Beanstalk to scale in every Friday at 6PM. If you know that your
application doesn’t receive as much traffic over the weekend, you can create a similar scheduled action.
option_settings:
ScheduledWeekendScaleDown.aws:autoscaling:scheduledaction:
MinSize: '1'
MaxSize: '4'
DesiredCapacity: '1'
StartTime: '2015-12-12T07:00:00Z'
EndTime: '2016-01-12T07:00:00Z'
Recurrence: 0 18 * * 5
Amazon EC2 status checks only cover an instance's health, not the health of your application, server,
or any Docker containers running on the instance. If your application crashes, but the instance that
it runs on is still healthy, it may be kicked out of the load balancer, but Auto Scaling won't replace it
automatically. The default behavior is good for troubleshooting. If Auto Scaling replaced the instance
as soon as the application crashed, you might not realize that anything went wrong, even if it crashed
quickly after starting up.
525
AWS Elastic Beanstalk Developer Guide
Load balancer
If you want Auto Scaling to replace instances whose application has stopped responding, you can use
a configuration file (p. 683) to configure the Auto Scaling group to use Elastic Load Balancing health
checks. The following example sets the group to use the load balancer's health checks, in addition to the
Amazon EC2 status check, to determine an instance's health.
Example .ebextensions/autoscaling.config
Resources:
AWSEBAutoScalingGroup:
Type: "AWS::AutoScaling::AutoScalingGroup"
Properties:
HealthCheckType: ELB
HealthCheckGracePeriod: 300
For more information about the HealthCheckType and HealthCheckGracePeriod properties, see
AWS::AutoScaling::AutoScalingGroup in the AWS CloudFormation User Guide and Health Checks for Auto
Scaling Instances in the Amazon EC2 Auto Scaling User Guide.
By default, the Elastic Load Balancing health check is configured to attempt a TCP connection to
your instance over port 80. This confirms that the web server running on the instance is accepting
connections. However, you might want to customize the load balancer health check (p. 526) to ensure
that your application, and not just the web server, is in a good state. The grace period setting sets the
number of seconds that an instance can fail the health check without being terminated and replaced.
Instances can recover after being kicked out of the load balancer, so give the instance an amount of time
that is appropriate for your application.
Alternatively, you can choose to share a load balancer across several Elastic Beanstalk environments.
With a shared load balancer, you save on operational cost by avoiding a dedicated load balancer for each
environment. You also assume more of the management responsibility for the shared load balancer that
your environments use.
• Classic Load Balancer – The previous-generation load balancer. Routes HTTP, HTTPS, or TCP request
traffic to different ports on environment instances.
• Application Load Balancer – An application layer load balancer. Routes HTTP or HTTPS request traffic
to different ports on environment instances based on the request path.
• Network Load Balancer – A network layer load balancer. Routes TCP request traffic to different ports
on environment instances. Supports both active and passive health checks.
Elastic Beanstalk supports all three load balancer types. The following table shows which types you can
use with the two usage patterns:
526
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
By default, Elastic Beanstalk creates an Application Load Balancer for your environment when you enable
load balancing with the Elastic Beanstalk console or the EB CLI. It configures the load balancer to listen
for HTTP traffic on port 80 and forward this traffic to instances on the same port. You can choose the
type of load balancer that your environment uses only during environment creation. Later, you can
change settings to manage the behavior of your running environment's load balancer, but you can't
change its type.
Note
Your environment must be in a VPC with subnets in at least two Availability Zones to create
an Application Load Balancer. All new AWS accounts include default VPCs that meet this
requirement. If your environment is in a VPC with subnets in only one Availability Zone, it
defaults to a Classic Load Balancer. If you don't have any subnets, you can't enable load
balancing.
You can create and manage environments with all load balancer types using the Elastic Beanstalk
console, the EB CLI eb create (p. 1003) command, or the Elastic Beanstalk APIs.
See the following topics to learn about each load balancer type that Elastic Beanstalk supports, its
functionality, how to configure and manage it in an Elastic Beanstalk environment, and how to configure
a load balancer to upload access logs (p. 577) to Amazon S3.
Topics
• Configuring a Classic Load Balancer (p. 527)
• Configuring an Application Load Balancer (p. 536)
• Configuring a shared Application Load Balancer (p. 554)
• Configuring a Network Load Balancer (p. 568)
• Configuring access logs (p. 577)
This topic describes the configuration of a Classic Load Balancer that Elastic Beanstalk creates and
dedicates to your environment. For information about configuring all the load balancer types that Elastic
Beanstalk supports, see Load balancer for your Elastic Beanstalk environment (p. 526).
Note
You can choose the type of load balancer that your environment uses only during environment
creation. Later, you can change settings to manage the behavior of your running environment's
load balancer, but you can't change its type.
Introduction
A Classic Load Balancer is the Elastic Load Balancing previous-generation load balancer. It supports
routing HTTP, HTTPS, or TCP request traffic to different ports on environment instances.
527
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
When your environment uses a Classic Load Balancer, Elastic Beanstalk configures it by default to listen
for HTTP traffic on port 80 and forward it to instances on the same port. To support secure connections,
you can configure your load balancer with a listener on port 443 and a TLS certificate.
The load balancer uses a health check to determine whether the Amazon EC2 instances running your
application are healthy. The health check makes a request to a specified URL at a set interval. If the URL
returns an error message, or fails to return within a specified timeout period, the health check fails.
If your application performs better by serving multiple requests from the same client on a single server,
you can configure your load balancer to use sticky sessions. With sticky sessions, the load balancer adds
a cookie to HTTP responses that identifies the Amazon EC2 instance that served the request. When
a subsequent request is received from the same client, the load balancer uses the cookie to send the
request to the same instance.
With cross-zone load balancing, each load balancer node for your Classic Load Balancer distributes
requests evenly across the registered instances in all enabled Availability Zones. If cross-zone load
balancing is disabled, each load balancer node distributes requests evenly across the registered instances
in its Availability Zone only.
When an instance is removed from the load balancer because it has become unhealthy or the
environment is scaling down, connection draining gives the instance time to complete requests before
closing the connection between the instance and the load balancer. You can change the amount of time
given to instances to send a response, or disable connection draining completely.
Note
Connection draining is enabled by default when you create an environment with the Elastic
Beanstalk console or the EB CLI. For other clients, you can enable it with configuration
options (p. 536).
You can use advanced load balancer settings to configure listeners on arbitrary ports, modify additional
sticky session settings, and configure the load balancer to connect to EC2 instances securely. These
settings are available through configuration options (p. 536) that you can set by using configuration
files in your source code, or directly on an environment by using the Elastic Beanstalk API. Many of these
settings are also available in the Elastic Beanstalk console. In addition, you can configure a load balancer
to upload access logs (p. 577) to Amazon S3.
To configure a Classic Load Balancer in the Elastic Beanstalk console during environment
creation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments.
3. Choose Create a new environment (p. 409) to start creating your environment.
4. On the wizard's main page, before choosing Create environment, choose Configure more options.
5. Choose the High availability configuration preset.
Alternatively, in the Capacity configuration category, configure a Load balanced environment type.
For details, see Capacity (p. 417).
6. In the Load balancer configuration category, choose Edit.
7. Select the Classic Load Balancer option, if it isn't already selected.
528
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
8. Make any Classic Load Balancer configuration changes that your environment requires.
9. Choose Save, and then make any other configuration changes that your environment requires.
10. Choose Create environment.
To configure a running environment's Classic Load Balancer in the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Load balancer configuration category, choose Edit.
Note
If the Load balancer configuration category doesn't have an Edit button, your environment
doesn't have a load balancer. To learn how to set one up, see Changing environment
type (p. 481).
5. Make the Classic Load Balancer configuration changes that your environment requires.
6. Choose Apply.
Listeners
Use this list to specify listeners for your load balancer. Each listener routes incoming client traffic on a
specified port using a specified protocol to your instances. Initially, the list shows the default listener,
which routes incoming HTTP traffic on port 80 to your environment's instance servers that are listening
to HTTP traffic on port 80.
529
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
1. Select the check box next to its table entry, choose Actions, and then choose the action you want.
2. If you chose Edit, use the Classic Load Balancer listener dialog box to edit settings, and then choose
Save.
For example, you can edit the default listener and change the Protocol from HTTP to TCP if you want
the load balancer to forward a request as is. This prevents the load balancer from rewriting headers
(including X-Forwarded-For). The technique doesn't work with sticky sessions.
530
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
To add a listener
Adding a secure listener is a common use case. The example in the following image adds a listener for
HTTPS traffic on port 443. This listener routes the incoming traffic to environment instance servers
listening to HTTPS traffic on port 443.
Before you can configure an HTTPS listener, ensure that you have a valid SSL certificate. Do one of the
following:
• If AWS Certificate Manager (ACM) is available in your AWS Region, create or import a certificate using
ACM. For more information about requesting an ACM certificate, see Request a Certificate in the AWS
Certificate Manager User Guide. For more information about importing third-party certificates into
ACM, see Importing Certificates in the AWS Certificate Manager User Guide.
531
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
• If ACM isn't available in your AWS Region, upload your existing certificate and key to IAM. For more
information about creating and uploading certificates to IAM, see Working with Server Certificates in
the IAM User Guide.
For more detail on configuring HTTPS and working with certificates in Elastic Beanstalk, see Configuring
HTTPS for your Elastic Beanstalk environment (p. 734).
For SSL certificate, choose the ARN of your SSL certificate. For example,
arn:aws:iam::123456789012:server-certificate/abc/certs/build, or arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678.
For details about configuring HTTPS and working with certificates in Elastic Beanstalk, see Configuring
HTTPS for your Elastic Beanstalk environment (p. 734).
532
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
Sessions
Select or clear the Session stickiness enabled box to enable or disable sticky sessions. Use Cookie
duration to configure a sticky session's duration, up to 1000000 seconds. On the Load balancer ports
list, select listener ports that the default policy (AWSEB-ELB-StickinessPolicy) applies to.
Connection draining
Select or clear the Connection draining enabled box to enable or disable connection draining. Set the
Draining timeout, up to 3600 seconds.
533
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
Health check
Use the following settings to configure load balancer health checks:
• Health check path – The path to which the load balancer sends health check requests. If you don't set
the path, the load balancer attempts to make a TCP connection on port 80 to verify health.
• Timeout – The amount of time, in seconds, to wait for a health check response.
• Interval – The amount of time, in seconds, between health checks of an individual instance. The
interval must be greater than the timeout.
• Unhealthy threshold, Healthy threshold – The number of health checks that must fail or pass,
respectively, before Elastic Load Balancing changes an instance's health state.
534
AWS Elastic Beanstalk Developer Guide
Classic Load Balancer
Note
The Elastic Load Balancing health check doesn't affect the health check behavior of an
environment's Auto Scaling group. Instances that fail an Elastic Load Balancing health check are
not automatically replaced by Amazon EC2 Auto Scaling unless you manually configure Amazon
EC2 Auto Scaling to do so. See Auto Scaling health check setting (p. 525) for details.
For more information about health checks and how they influence your environment's overall health, see
Basic health reporting (p. 773).
$ eb create
Enter Environment Name
(default is my-app): test-env
Enter DNS CNAME prefix
(default is my-app): test-env-DLW24ED23SF
535
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
1) classic
2) application
3) network
(default is 1):
You can also specify a load balancer type by using the --elb-type option.
• aws:elb:healthcheck (p. 661) – Configure the thresholds, check interval, and timeout for load
balancer health checks.
• aws:elasticbeanstalk:application (p. 647) – Configure the health check URL.
• aws:elb:loadbalancer (p. 662) – Enable cross-zone load balancing. Assign security groups to the
load balancer and override the default security group that Elastic Beanstalk creates. This namespace
also includes deprecated options for configuring the standard and secure listeners that have been
replaced by options in the aws:elb:listener namespace.
• aws:elb:listener (p. 663) – Configure the default listener on port 80, a secure listener on port
443, or additional listeners for any protocol on any port. If you specify aws:elb:listener as the
namespace, settings apply to the default listener on port 80. If you specify a port (for example,
aws:elb:listener:443), a listener is configured on that port.
• aws:elb:policies (p. 665) – Configure additional settings for your load balancer. Use options in
this namespace to configure listeners on arbitrary ports, modify additional sticky session settings, and
configure the load balancer to connect to Amazon EC2 instances securely.
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
Example .ebextensions/loadbalancer-terminatehttps.config
The following example configuration file creates an HTTPS listener on port 443, assigns a certificate
that the load balancer uses to terminate the secure connection, and disables the default listener on port
80. The load balancer forwards the decrypted requests to the EC2 instances in your environment on
HTTP:80.
option_settings:
aws:elb:listener:443:
ListenerProtocol: HTTPS
SSLCertificateId: arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678
InstancePort: 80
InstanceProtocol: HTTP
aws:elb:listener:
ListenerEnabled: false
536
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
Elastic Load Balancing supports several load balancer types. To learn about them, see the Elastic Load
Balancing User Guide. Elastic Beanstalk can create a load balancer for you, or let you specify a shared
load balancer that you've created.
This topic describes the configuration of an Application Load Balancer that Elastic Beanstalk creates and
dedicates to your environment. See also the section called “Shared Application Load Balancer” (p. 554).
For information about configuring all the load balancer types that Elastic Beanstalk supports, see the
section called “Load balancer” (p. 526).
Note
You can choose the type of load balancer that your environment uses only during environment
creation. You can change settings to manage the behavior of your running environment's load
balancer, but you can't change its type. You also can't switch from a dedicated to a shared load
balancer or vice versa.
Introduction
An Application Load Balancer inspects traffic at the application network protocol layer to identify the
request's path so that it can direct requests for different paths to different destinations.
When your environment uses an Application Load Balancer, Elastic Beanstalk configures it by default to
perform the same function as a Classic Load Balancer. The default listener accepts HTTP requests on port
80 and distributes them to the instances in your environment. You can add a secure listener on port 443
with a certificate to decrypt HTTPS traffic, configure health check behavior, and push access logs from
the load balancer to an Amazon Simple Storage Service (Amazon S3) bucket.
Note
Unlike a Classic Load Balancer or a Network Load Balancer, an Application Load Balancer can't
have transport layer (layer 4) TCP or SSL/TLS listeners. It supports only HTTP and HTTPS
listeners. Additionally, it can't use backend authentication to authenticate HTTPS connections
between the load balancer and backend instances.
In an Elastic Beanstalk environment, you can use an Application Load Balancer to direct traffic for certain
paths to a different process on your web server instances. With a Classic Load Balancer, all traffic to
a listener is routed to a single process on the backend instances. With an Application Load Balancer,
you can configure multiple rules on the listener to route requests to certain paths to different backend
process. You configure each process with the port that the process listens on.
For example, you could run a login process separately from your main application. While the main
application on your environment's instances accepts the majority of requests and listens on port 80, your
login process listens on port 5000 and accepts requests to the /login path. All incoming requests from
clients come in on port 80. With an Application Load Balancer, you can configure a single listener for
incoming traffic on port 80, with two rules that route traffic to two separate processes, depending on the
path in the request. You add a custom rule that routes traffic to /login to the login process listening on
port 5000. The default rule routes all other traffic to the main application process listening on port 80.
An Application Load Balancer rule maps a request to a target group. In Elastic Beanstalk, a target group
is represented by a process. You can configure a process with a protocol, port, and health check settings.
The process represents the process running on the instances in your environment. The default process is
a listener on port 80 of the reverse proxy (nginx or Apache) that runs in front of your application.
Note
Outside of Elastic Beanstalk, a target group maps to a group of instances. A listener can use
rules and target groups to route traffic to different instances based on the path. Within Elastic
Beanstalk, all of your instances in your environment are identical, so the distinction is made
between processes listening on different ports.
A Classic Load Balancer uses a single health check path for the entire environment. With an Application
Load Balancer, each process has a separate health check path that is monitored by the load balancer and
Elastic Beanstalk-enhanced health monitoring.
537
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments.
3. Choose Create a new environment (p. 409) to start creating your environment.
4. On the wizard's main page, before choosing Create environment, choose Configure more options.
5. Choose the High availability configuration preset.
Alternatively, in the Capacity configuration category, configure a Load balanced environment type.
For details, see Capacity (p. 417).
6. In the Load balancer configuration category, choose Edit.
7. Select the Application Load Balancer and Dedicated options, if they aren't already selected.
538
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
8. Make any Application Load Balancer configuration changes that your environment requires.
9. Choose Save, and then make any other configuration changes that your environment requires.
10. Choose Create environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Load balancer configuration category, choose Edit.
Note
If the Load balancer configuration category doesn't have an Edit button, your environment
doesn't have a load balancer. To learn how to set one up, see Changing environment
type (p. 481).
5. Make the Application Load Balancer configuration changes that your environment requires.
6. Choose Apply.
539
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
Listeners
Use this list to specify listeners for your load balancer. Each listener routes incoming client traffic on a
specified port using a specified protocol to one or more processes on your instances. Initially, the list
shows the default listener, which routes incoming HTTP traffic on port 80 to a process named default.
1. Select the check box next to its table entry, and then choose Actions, Edit.
2. Use the Application Load Balancer listener dialog box to edit settings, and then choose Save.
To add a listener
Use the Application Load Balancer listener dialog box settings to choose the port and protocol on
which the listener listens to traffic, and the process to route the traffic to. If you choose the HTTPS
protocol, configure SSL settings.
540
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
Before you can configure an HTTPS listener, ensure that you have a valid SSL certificate. Do one of the
following:
• If AWS Certificate Manager (ACM) is available in your AWS Region, create or import a certificate using
ACM. For more information about requesting an ACM certificate, see Request a Certificate in the AWS
Certificate Manager User Guide. For more information about importing third-party certificates into
ACM, see Importing Certificates in the AWS Certificate Manager User Guide.
• If ACM isn't available in your AWS Region, upload your existing certificate and key to IAM. For more
information about creating and uploading certificates to IAM, see Working with Server Certificates in
the IAM User Guide.
For more detail on configuring HTTPS and working with certificates in Elastic Beanstalk, see Configuring
HTTPS for your Elastic Beanstalk environment (p. 734).
Processes
Use this list to specify processes for your load balancer. A process is a target for listeners to route traffic
to. Each listener routes incoming client traffic on a specified port using a specified protocol to one or
more processes on your instances. Initially, the list shows the default process, which listens to incoming
HTTP traffic on port 80.
541
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
You can edit the settings of an existing process, or add a new process. To start editing a process on the
list or adding a process to it, use the same steps listed for the listener list (p. 540). The Environment
process dialog box opens.
Definition
Use these settings to define the process: its Name, and the Port and Protocol on which it listens to
requests.
542
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
Health check
543
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
544
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
Note
The Elastic Load Balancing health check doesn't affect the health check behavior of an
environment's Auto Scaling group. Instances that fail an Elastic Load Balancing health check are
not automatically replaced by Amazon EC2 Auto Scaling unless you manually configure Amazon
EC2 Auto Scaling to do so. See Auto Scaling health check setting (p. 525) for details.
For more information about health checks and how they influence your environment's overall health, see
Basic health reporting (p. 773).
Sessions
Select or clear the Stickiness policy enabled box to enable or disable sticky sessions. Use Cookie
duration to configure a sticky session's duration, up to 604800 seconds.
Rules
Use this list to specify custom listener rules for your load balancer. A rule maps requests that the listener
receives on a specific path pattern to a target process. Each listener can have multiple rules, routing
requests on different paths to different processes on your instances.
Rules have numeric priorities that determine the precedence in which they are applied to incoming
requests. For each new listener you add, Elastic Beanstalk adds a default rule that routes all the listener's
traffic to the default process. The default rule's precedence is the lowest; it's applied if no other rule for
the same listener matches the incoming request. Initially, if you haven't added custom rules, the list is
empty. Default rules of all listeners aren't displayed.
545
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
You can edit the settings of an existing rule, or add a new rule. To start editing a rule on the list or
adding a rule to it, use the same steps listed for the listener list (p. 540). The Listener rule dialog box
opens, with the following settings:
When editing any existing rule, you can't change its Name and Listener port.
546
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
547
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
For details about access logs, including permissions and other requirements, see Access logs for your
Application Load Balancer.
To configure your environment's Application Load Balancer to meet these requirements, you remove the
default listener, add an HTTPS listener, indicate that the default process listens to port 443 on HTTPS,
and add a process and a listener rule for admin traffic on a different path.
1. Add a secure listener. For Port, type 443. For Protocol, select HTTPS. For SSL certificate, select
the ARN of your SSL certificate. For example, arn:aws:iam::123456789012:server-
certificate/abc/certs/build, or arn:aws:acm:us-
east-2:123456789012:certificate/12345678-12ab-34cd-56ef-12345678.
548
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
2. Disable the default port 80 HTTP listener. For the default listener, turn off the Enabled option.
549
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
3. Configure the default process to HTTPS. Select the default process, and then for Actions, choose Edit.
For Port, type 443. For Protocol, select HTTPS.
4. Add an admin process. For Name, type admin. For Port, type 443. For Protocol, select HTTPS. Under
Health check, for Path type /admin.
550
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
5. Add a rule for admin traffic. For Name, type admin. For Listener port, type 443. For Match
conditions, add a PathPattern with the value /admin/*. For Process, select admin.
551
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
$ eb create
Enter Environment Name
(default is my-app): test-env
Enter DNS CNAME prefix
(default is my-app): test-env-DLW24ED23SF
552
AWS Elastic Beanstalk Developer Guide
Application Load Balancer
(default is 2):
You can also specify a load balancer type with the --elb-type option.
• aws:elasticbeanstalk:environment (p. 651) – Choose the load balancer type for the
environment. The value for an Application Load Balancer is application.
You can't set this option in configuration files (.Ebextensions (p. 683)).
• aws:elbv2:loadbalancer (p. 670) – Configure access logs and other settings that apply to the
Application Load Balancer as a whole.
• aws:elbv2:listener (p. 668) – Configure listeners on the Application Load Balancer. These
settings map to the settings in aws:elb:listener for Classic Load Balancers.
• aws:elbv2:listenerrule (p. 669) – Configure rules that route traffic to different processes,
depending on the request path. Rules are unique to Application Load Balancers.
• aws:elasticbeanstalk:environment:process (p. 651) – Configure health checks and
specify the port and protocol for the processes that run on your environment's instances. The port
and protocol settings map to the instance port and instance protocol settings in aws:elb:listener
for a listener on a Classic Load Balancer. Health check settings map to the settings in the
aws:elb:healthcheck and aws:elasticbeanstalk:application namespaces.
Example .ebextensions/alb-access-logs.config
The following configuration file enables access log uploads for an environment with an Application Load
Balancer.
option_settings:
aws:elbv2:loadbalancer:
AccessLogsS3Bucket: DOC-EXAMPLE-BUCKET
AccessLogsS3Enabled: 'true'
AccessLogsS3Prefix: beanstalk-alb
Example .ebextensions/alb-default-process.config
The following configuration file modifies health check and stickiness settings on the default process.
option_settings:
aws:elasticbeanstalk:environment:process:default:
DeregistrationDelay: '20'
HealthCheckInterval: '15'
HealthCheckPath: /
HealthCheckTimeout: '5'
HealthyThresholdCount: '3'
UnhealthyThresholdCount: '5'
Port: '80'
Protocol: HTTP
StickinessEnabled: 'true'
StickinessLBCookieDuration: '43200'
Example .ebextensions/alb-secure-listener.config
The following configuration file adds a secure listener and a matching process on port 443.
553
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
option_settings:
aws:elbv2:listener:443:
DefaultProcess: https
ListenerEnabled: 'true'
Protocol: HTTPS
SSLCertificateArns: arn:aws:acm:us-east-2:123456789012:certificate/21324896-0fa4-412b-
bf6f-f362d6eb6dd7
aws:elasticbeanstalk:environment:process:https:
Port: '443'
Protocol: HTTPS
Example .ebextensions/alb-admin-rule.config
The following configuration file adds a secure listener with a rule that routes traffic with a request path
of /admin to a process named admin that listens on port 4443.
option_settings:
aws:elbv2:listener:443:
DefaultProcess: https
ListenerEnabled: 'true'
Protocol: HTTPS
Rules: admin
SSLCertificateArns: arn:aws:acm:us-east-2:123456789012:certificate/21324896-0fa4-412b-
bf6f-f362d6eb6dd7
aws:elasticbeanstalk:environment:process:https:
Port: '443'
Protocol: HTTPS
aws:elasticbeanstalk:environment:process:admin:
HealthCheckPath: /admin
Port: '4443'
Protocol: HTTPS
aws:elbv2:listenerrule:admin:
PathPatterns: /admin/*
Priority: 1
Process: admin
This topic describes the configuration of a shared Application Load Balancer that you create and
associate with your environment. See also the section called “Application Load Balancer” (p. 536).
For information about configuring all the load balancer types that Elastic Beanstalk supports, see Load
balancer for your Elastic Beanstalk environment (p. 526).
Note
You can choose the type of load balancer that your environment uses only during environment
creation. You can change settings to manage the behavior of your running environment's load
balancer, but you can't change its type. You also can't switch from a dedicated to a shared load
balancer or vice versa.
Introduction
A shared load balancer is a load balancer that you create and manage yourself using the Amazon Elastic
Compute Cloud (Amazon EC2) service, and then use in multiple Elastic Beanstalk environments.
554
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
When you create a load-balanced, scaling environment and choose to use an Application Load
Balancer, Elastic Beanstalk creates a load balancer dedicated to your environment by default. To learn
what an Application Load Balancer is and how it works in an Elastic Beanstalk environment, see the
introduction (p. 537) to configuring an Application Load Balancer for Elastic Beanstalk.
In some situations you might want to save the cost of having multiple dedicated load balancers. This
can be helpful when you have multiple environments, for example, if your application is a suite of
microservices instead of a monolithic service. In such cases you can choose to use a shared load balancer.
To use a shared load balancer, first create it in Amazon EC2 and add one or more listeners. During the
creation of an Elastic Beanstalk environment, you then provide the load balancer and choose a listener
port. Elastic Beanstalk associates the listener with the default process in your environment. You can
add custom listener rules to route traffic from specific host headers and paths to other environment
processes.
Elastic Beanstalk adds a tag to the shared load balancer. The tag name is elasticbeanstalk:shared-
elb-environment-count, and its value is the number of environments sharing this load balancer.
Using a shared load balancer is different from using a dedicated one in several ways.
ManagementElastic Beanstalk creates and You create and manage the load balancer and
manages the load balancer, listeners, listeners outside of Elastic Beanstalk. Elastic
listener rules, and processes (target Beanstalk creates and manages a default rule
groups). Elastic Beanstalk also and a default process, and you can add rules and
removes them when you terminate processes. Elastic Beanstalk removes the listener
your environment. Elastic Beanstalk rules and processes that were added during
can set load balancer access log environment creation.
capture, if you choose that option.
Listener Elastic Beanstalk creates a default Elastic Beanstalk associates a default rule only
rules rule for each listener, to route all with a port 80 listener, if one exists. If you choose
traffic to the listener's default a different default listener port, you have to
process. associate the default rule with it (the Elastic
Beanstalk console and EB CLI do this for you).
Security Elastic Beanstalk creates a default You can configure one or more security groups
groups security group and attaches it to the to use for the load balancer. If you don't, Elastic
load balancer. Beanstalk checks if an existing security group that
Elastic Beanstalk manages is already attached to
the load balancer. If not, Elastic Beanstalk creates
a security group and attaches it to the load
balancer. Elastic Beanstalk deletes this security
group when the last environment sharing the load
balancer terminates.
555
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
Updates You can update your Application You can't use Elastic Beanstalk to configure access
Load Balancer after environment log capture in your Application Load Balancer,
creation. You can edit listeners, and you can't update listeners and listener rules
listener rules, and processes. You can after environment creation. You can only update
configure load balancer access log processes (target groups). To configure access log
capture. capture, and to update listeners and listener rules,
use Amazon EC2.
You can't edit your shared Application Load Balancer configuration in the Application Load Balancer
console after your environment is created. To configure listeners, listener rules, processes (target groups),
and access log capture, use Amazon EC2.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments.
3. Choose Create a new environment (p. 409) to start creating your environment.
4. On the wizard's main page, before choosing Create environment, choose Configure more options.
5. Choose the High availability configuration preset.
Alternatively, in the Capacity configuration category, configure a Load balanced environment type.
For details, see Capacity (p. 417).
6. In the Load balancer configuration category, choose Edit.
7. Select the Application Load Balancer option, if it isn't already selected, and then select the Shared
option.
556
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
8. Make any shared Application Load Balancer configuration changes that your environment requires.
9. Choose Save, and then make any other configuration changes that your environment requires.
10. Choose Create environment.
Before you can configure a shared Application Load Balancer here, use Amazon EC2 to define at least one
Application Load Balancer for sharing, with at least one listener, in your account. If you haven't done so
already, you can choose Manage load balancers. Elastic Beanstalk opens the Amazon EC2 console in a
new browser tab.
When you're done configuring shared load balancers outside of Elastic Beanstalk, configure the following
settings on this console section:
• Load balancer ARN – The shared load balancer to use in this environment. Select from a list of load
balancers or enter a load balancer Amazon Resource Name (ARN).
557
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
• Default listener port – A listener port that the shared load balancer listens on. Select from a list of
existing listener ports. Traffic from this listener with the environment's CNAME in the host header is
routed to a default process in this environment.
Processes
Use this list to specify processes for your shared load balancer. A process is a target for listeners to route
traffic to. Initially, the list shows the default process, which receives traffic from the default listener.
1. Select the check box next to its table entry, and then choose Actions, Edit.
2. Use the Environment process dialog box to edit settings, and then choose Save.
558
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
To add a process
Definition
Use these settings to define the process: its Name, and the Port and Protocol on which it listens to
requests.
Health check
559
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
560
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
Note
The Elastic Load Balancing health check doesn't affect the health check behavior of an
environment's Auto Scaling group. Instances that fail an Elastic Load Balancing health check are
not automatically replaced by Amazon EC2 Auto Scaling unless you manually configure Amazon
EC2 Auto Scaling to do so. See Auto Scaling health check setting (p. 525) for details.
For more information about health checks and how they influence your environment's overall health, see
Basic health reporting (p. 773).
Sessions
Select or clear the Stickiness policy enabled box to enable or disable sticky sessions. Use Cookie
duration to configure a sticky session's duration, up to 604800 seconds.
Rules
Use this list to specify custom listener rules for your shared load balancer. A rule maps requests that
the listener receives on a specific path pattern to a target process. Each listener can have multiple rules,
routing requests on different paths to different processes on instances of the different environments
sharing the listener.
Rules have numeric priorities that determine the precedence in which they are applied to incoming
requests. Elastic Beanstalk adds a default rule that routes all the default listener's traffic to the default
process of your new environment. The default rule's precedence is the lowest; it's applied if no other rule
for the same listener matches the incoming request. Initially, if you haven't added custom rules, the list is
empty. The default rule isn't displayed.
561
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
You can edit the settings of an existing rule, or add a new rule. To start editing a rule on the list or
adding a rule to it, use the same steps listed for the process list (p. 558). The Listener rule dialog box
opens, with the following settings:
562
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
To meet these requirements, use Amazon EC2 to create an Application Load Balancer that you'll share
among your micro services. Add a secure listener on port 443 and the HTTPS protocol. Then add multiple
SSL certificates to the listener—one per micro-service domain. For details about creating the Application
Load Balancer and secure listener, see Create an Application Load Balancer and Create an HTTPS listener
for your Application Load Balancer in the User Guide for Application Load Balancers.
563
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
In Elastic Beanstalk, configure each micro-service environment to use the shared Application Load
Balancer and set the default listener port to 443. In the case of the particular environment that we're
demonstrating here, indicate that the default process listens to port 443 on HTTPS, and add a process
and a listener rule for admin traffic on a different path.
1. In the Shared Application Load Balancer section, select your load balancer, and then, for Default
listener port, select 443. The listener port should already be selected if it's the only listener that the
load balancer has.
2. Configure the default process to HTTPS. Select the default process, and then for Actions, choose Edit.
For Port, enter 443. For Protocol, select HTTPS.
564
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
3. Add an admin process. For Name, enter admin. For Port, enter 443. For Protocol, select HTTPS.
Under Health check, for Path enter /admin.
4. Add a rule for admin traffic. For Name, enter admin. For Listener port, enter 443. For Match
conditions, add a PathPattern with the value /admin/*. For Process, select admin.
565
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
$ eb create
Enter Environment Name
(default is my-app): test-env
Enter DNS CNAME prefix
(default is my-app): test-env-DLW24ED23SF
566
AWS Elastic Beanstalk Developer Guide
Shared Application Load Balancer
1) classic
2) application
3) network
(default is 2):
Your account has one or more sharable load balancers. Would you like your new environment
to use a shared load balancer?(y/N) y
You can also specify a shared load balancer using command options.
• aws:elasticbeanstalk:environment (p. 651) – Choose the load balancer type for the
environment, and tell Elastic Beanstalk that you'll use a shared load balancer.
You can't set these two options in configuration files (.Ebextensions (p. 683)).
• aws:elbv2:loadbalancer (p. 670) – Configure the shared Application Load Balancer ARN and
security groups.
• aws:elbv2:listener (p. 668) – Associate listeners of the shared Application Load Balancer with
environment processes by listing listener rules.
• aws:elbv2:listenerrule (p. 669) – Configure listener rules that route traffic to different
processes, depending on the request path. Rules are unique to Application Load Balancers—both
dedicated and shared.
• aws:elasticbeanstalk:environment:process (p. 651) – Configure health checks and
specify the port and protocol for the processes that run on your environment's instances.
Example .ebextensions/application-load-balancer-shared.config
To get started with a shared Application Load Balancer, use the Elastic Beanstalk console, EB CLI, or
API to set the load balancer type to application and choose to use a shared load balancer. Use a
configuration file (p. 683) to configure the shared load balancer.
option_settings:
aws:elbv2:loadbalancer:
SharedLoadBalancer: arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/
app/MySharedALB2/e574ea4c37ad2ec8
Note
You can configure this option only during environment creation.
567
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
Example .ebextensions/alb-shared-secure-listener.config
The following configuration file selects a default secure listener on port 443 for the shared load balancer,
and sets the default process to listen to port 443.
option_settings:
aws:elbv2:loadbalancer:
SharedLoadBalancer: arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/
app/MySharedALB2/e574ea4c37ad2ec8
aws:elbv2:listener:443:
rules: default
aws:elasticbeanstalk:environment:process:default:
Port: '443'
Protocol: HTTPS
Example .ebextensions/alb-shared-admin-rule.config
The following configuration file builds on the previous example and adds a rule that routes traffic with a
request path of /admin to a process named admin that listens on port 4443.
option_settings:
aws:elbv2:loadbalancer:
SharedLoadBalancer: arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/
app/MySharedALB2/e574ea4c37ad2ec8
aws:elbv2:listener:443:
rules: default,admin
aws:elasticbeanstalk:environment:process:default:
Port: '443'
Protocol: HTTPS
aws:elasticbeanstalk:environment:process:admin:
HealthCheckPath: /admin
Port: '4443'
Protocol: HTTPS
aws:elbv2:listenerrule:admin:
PathPatterns: /admin/*
Priority: 1
Process: admin
This topic describes the configuration of a Network Load Balancer that Elastic Beanstalk creates and
dedicates to your environment. For information about configuring all the load balancer types that Elastic
Beanstalk supports, see Load balancer for your Elastic Beanstalk environment (p. 526).
Note
You can choose the type of load balancer that your environment uses only during environment
creation. You can change settings to manage the behavior of your running environment's load
balancer, but you can't change its type.
Introduction
With a Network Load Balancer, the default listener accepts TCP requests on port 80 and distributes them
to the instances in your environment. You can configure health check behavior, configure the listener
port, or add a listener on another port.
568
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
Note
Unlike a Classic Load Balancer or an Application Load Balancer, a Network Load Balancer can't
have application layer (layer 7) HTTP or HTTPS listeners. It only supports transport layer (layer
4) TCP listeners. HTTP and HTTPS traffic can be routed to your environment over TCP. To
establish secure HTTPS connections between web clients and your environment, install a self-
signed certificate (p. 735) on the environment's instances, and configure the instances to listen
on the appropriate port (typically 443) and terminate HTTPS connections. The configuration
varies per platform. See Configuring your application to terminate HTTPS connections at the
instance (p. 741) for instructions. Then configure your Network Load Balancer to add a listener
that maps to a process listening on the appropriate port.
A Network Load Balancer supports active health checks. These checks are based on messages to the root
(/) path. In addition, a Network Load Balancer supports passive health checks. It automatically detects
faulty backend instances and routes traffic only to healthy instances.
To configure a Network Load Balancer in the Elastic Beanstalk console during environment
creation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments.
3. Choose Create a new environment (p. 409) to start creating your environment.
4. On the wizard's main page, before choosing Create environment, choose Configure more options.
5. Choose the High availability configuration preset.
Alternatively, in the Capacity configuration category, configure a Load balanced environment type.
For details, see Capacity (p. 417).
6. In the Load balancer configuration category, choose Edit.
7. Select the Network Load Balancer option, if it isn't already selected.
8. Make any Network Load Balancer configuration changes that your environment requires.
9. Choose Save, and then make any other configuration changes that your environment requires.
10. Choose Create environment.
569
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Load balancer configuration category, choose Edit.
Note
If the Load balancer configuration category doesn't have an Edit button, your environment
doesn't have a load balancer. To learn how to set one up, see Changing environment
type (p. 481).
5. Make the Network Load Balancer configuration changes that your environment requires.
6. Choose Apply.
Listeners
Use this list to specify listeners for your load balancer. Each listener routes incoming client traffic on a
specified port to a process on your instances. Initially, the list shows the default listener, which routes
incoming traffic on port 80 to a process named default, which listens to port 80.
1. Select the check box next to its table entry, and then choose Actions, Edit.
2. Use the Network Load Balancer listener dialog box to edit settings, and then choose Save.
570
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
To add a listener
Use the Network Load Balancer listener dialog box to configure the port on which the listener listens
to traffic, and to choose the process to which you want to route traffic (specified by the port that the
process listens to).
Processes
Use this list to specify processes for your load balancer. A process is a target for listeners to route traffic
to. Each listener routes incoming client traffic on a specified port to a process on your instances. Initially,
the list shows the default process, which listens to incoming traffic on port 80.
571
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
You can edit the settings of an existing process, or add a new process. To start editing a process on the
list or adding a process to it, use the same steps listed for the listener list (p. 540). The Environment
process dialog box opens.
Definition
Use these settings to define the process: its Name and the Process port on which it listens to requests.
Health check
572
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
• Interval – The amount of time, in seconds, between health checks of an individual instance.
• Healthy threshold – The number of health checks that must pass before Elastic Load Balancing
changes an instance's health state. (For Network Load Balancer, Unhealthy threshold is a read-only
setting that is always equal to the healthy threshold value.)
• Deregistration delay – The amount of time, in seconds, to wait for active requests to complete before
deregistering an instance.
Note
The Elastic Load Balancing health check doesn't affect the health check behavior of an
environment's Auto Scaling group. Instances that fail an Elastic Load Balancing health check
will not automatically be replaced by Amazon EC2 Auto Scaling unless you manually configure
Amazon EC2 Auto Scaling to do so. See Auto Scaling health check setting (p. 525) for details.
For more information about health checks and how they influence your environment's overall health, see
Basic health reporting (p. 773).
573
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
1. Configure the default process. Select the default process, and then, for Actions, choose Edit. For
Process port, type 443.
2. Add a port 443 listener. Add a new listener. For Listener port, type 443. For Process port, make sure
that 443 is selected.
574
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
3. Disable the default port 80 listener. For the default listener, turn off the Enabled option.
575
AWS Elastic Beanstalk Developer Guide
Network Load Balancer
$ eb create
Enter Environment Name
(default is my-app): test-env
Enter DNS CNAME prefix
(default is my-app): test-env-DLW24ED23SF
You can also specify a load balancer type with the --elb-type option.
• aws:elasticbeanstalk:environment (p. 651) – Choose the load balancer type for the
environment. The value for a Network Load Balancer is network.
• aws:elbv2:listener (p. 668) – Configure listeners on the Network Load Balancer. These
settings map to the settings in aws:elb:listener for Classic Load Balancers.
• aws:elasticbeanstalk:environment:process (p. 651) – Configure health checks and
specify the port and protocol for the processes that run on your environment's instances. The port
and protocol settings map to the instance port and instance protocol settings in aws:elb:listener
for a listener on a Classic Load Balancer. Health check settings map to the settings in the
aws:elb:healthcheck and aws:elasticbeanstalk:application namespaces.
Example .ebextensions/network-load-balancer.config
To get started with a Network Load Balancer, use a configuration file (p. 683) to set the load balancer
type to network.
option_settings:
aws:elasticbeanstalk:environment:
LoadBalancerType: network
Note
You can set the load balancer type only during environment creation.
Example .ebextensions/nlb-default-process.config
The following configuration file modifies health check settings on the default process.
option_settings:
aws:elasticbeanstalk:environment:process:default:
DeregistrationDelay: '20'
HealthCheckInterval: '10'
HealthyThresholdCount: '5'
576
AWS Elastic Beanstalk Developer Guide
Configuring access logs
UnhealthyThresholdCount: '5'
Port: '80'
Protocol: TCP
Example .ebextensions/nlb-secure-listener.config
The following configuration file adds a listener for secure traffic on port 443 and a matching target
process that listens to port 443.
option_settings:
aws:elbv2:listener:443:
DefaultProcess: https
ListenerEnabled: 'true'
aws:elasticbeanstalk:environment:process:https:
Port: '443'
The DefaultProcess option is named this way because of Application Load Balancers, which
can have non-default listeners on the same port for traffic to specific paths (see Application Load
Balancer (p. 536) for details). For a Network Load Balancer the option specifies the only target process
for this listener.
In this example, we named the process https because it listens to secure (HTTPS) traffic. The listener
sends traffic to the process on the designated port using the TCP protocol, because a Network Load
Balancer works only with TCP. This is okay, because network traffic for HTTP and HTTPS is implemented
on top of TCP.
If you haven't used a database instance with your application before, we recommend that you first use
the process described in this topic to add a database to a test environment using the Elastic Beanstalk
service. By doing this, you can verify that your application can read the environment properties,
construct a connection string, and connect to a database instance, without the additional configuration
work required for a database external to Elastic Beanstalk.
After you verify that your application works correctly with the database, you may consider moving
towards a production environment. At this point you have the option to decouple the database from
577
AWS Elastic Beanstalk Developer Guide
Database lifecycle
your Elastic Beanstalk environment to move towards a configuration that offers greater flexibility. The
decoupled database can remain operational as an external Amazon RDS database instance. The health
of the environment isn't affected by decoupling the database. If you need to terminate the environment,
you can do so and also choose the option to keep the database available and operational outside of
Elastic Beanstalk.
Using an external database has several advantages. You can connect to the external database from
multiple environments, use database types that aren't supported with integrated databases, and
perform blue/green deployments. As an alternative to using a decoupled database that Elastic Beanstalk
created, you can also create a database instance outside of your Elastic Beanstalk environment. Both
options result in a database instance that's external to your Elastic Beanstalk environment and will
require additional security group and connection string configuration. For more information, see Using
Elastic Beanstalk with Amazon RDS (p. 923).
Sections
• Database lifecycle (p. 578)
• Adding an Amazon RDS DB instance to your environment using the console (p. 578)
• Connecting to the database (p. 580)
• Configuring an integrated RDS DB instance using the console (p. 580)
• Configuring an integrated RDS DB instance using configuration files (p. 581)
• Decoupling an RDS DB instance using the console (p. 581)
• Decoupling an RDS DB instance using configuration files (p. 583)
Database lifecycle
You can choose what you want to happen to the database after you decouple it from your Elastic
Beanstalk environment. The options that you can choose from are collectively referred to as deletion
policies. The following deletion policies apply to a database after you decouple it from an Elastic
Beanstalk environment (p. 581) or terminate the Elastic Beanstalk environment.
• Snapshot — Before Elastic Beanstalk terminates the database, it saves a snapshot of it. You can restore
a database from a snapshot when you add a DB instance to an Elastic Beanstalk environment or when
you create a standalone database. For more information about creating a new standalone DB instance
from a snapshot, see Restoring from a DB snapshot in the Amazon RDS User Guide. You might incur
charges for storing database snapshots. For more information, see the Backup Storage section of
Amazon RDS Pricing.
• Delete — Elastic Beanstalk terminates the database. After it's terminated, the database instance is no
longer available for any operation.
• Retain — The database instance isn't terminated. It remains available and operational, though
decoupled from Elastic Beanstalk. You can then configure one or multiple environments to connect to
the database as an external Amazon RDS database instance. For more information, see Using Elastic
Beanstalk with Amazon RDS (p. 923).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
578
AWS Elastic Beanstalk Developer Guide
Adding an Amazon RDS DB instance
to your environment using the console
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Choose a DB engine, and enter a user name and password.
6. Choose Apply.
• Snapshot – Choose an existing database snapshot. Elastic Beanstalk restores the snapshot and adds
it to your environment. The default value is None. When the value is None, you can configure a new
database using the other settings on this page.
• Engine – Choose a database engine.
• Engine version – Choose a specific version of the database engine.
• Instance class – Choose the DB instance class. For information about DB instance classes, see https://
aws.amazon.com/rds/.
• Storage – Choose the amount of storage to provision for your database. You can increase allocated
storage later, but you can't decrease it. For information about storage allocation, see Features.
• Username – Enter a user name of your choice using a combination of only numbers and letters.
• Password – Enter a password of your choice containing 8–16 printable ASCII characters (excluding /, \,
and @).
• Availability – Choose High (Multi-AZ) to run a warm backup in a second Availability Zone for high
availability.
• Database deletion policy – The deletion policy determines what happens to the database after it's
decoupled (p. 581) from your environment. It can be set to the following values: Create Snapshot,
Retain, or Delete. These values are described in Database lifecycle (p. 578) in this same topic.
Note
Elastic Beanstalk creates a master user for the database using the user name and password
you provide. To learn more about the master user and its privileges, see Master User Account
Privileges.
It takes about 10 minutes to add a DB instance. When the update is complete the new database is
coupled to your environment. The hostname and other connection information for the DB instance are
available to your application through the following environment properties.
RDS_PORT The port where the DB instance On the Connectivity & security
accepts connections. The default tab on the Amazon RDS console:
value varies among DB engines. Port.
579
AWS Elastic Beanstalk Developer Guide
Connecting to the database
RDS_PASSWORD The password that you Not available for reference in the
configured for your database. Amazon RDS console.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
You can modify the Instance class, Storage, Password, Availability, and Database deletion policy
settings after database creation. If you change the instance class, Elastic Beanstalk re-provisions the DB
instance.
If you no longer need Elastic Beanstalk to associate the database to the environment, you can choose to
decouple it by selecting Decouple database. It’s important to understand the options and considerations
involved with this operation. For more information, see the section called “Decoupling an RDS DB
instance using the console” (p. 581).
Warning
Don't modify settings on the coupled database instance outside of the functionality that's
provided by Elastic Beanstalk (for example, in the Amazon RDS console). If you do, your Amazon
580
AWS Elastic Beanstalk Developer Guide
Configuring an integrated RDS DB
instance using configuration files
RDS DB configuration might be out of sync with your environment's definition. When you
update or restart your environment, the settings specified in the environment override any
settings you made outside of Elastic Beanstalk.
If you need to modify settings that Elastic Beanstalk doesn't directly support, use Elastic
Beanstalk configuration files (p. 581).
Example .ebextensions/db-instance-options.config
option_settings:
aws:rds:dbinstance:
DBAllocatedStorage: 100
If you want to configure DB instance properties that Elastic Beanstalk doesn't support, you can still use a
configuration file, and specify your settings using the resources key. The following example sets values
to the StorageType and Iops Amazon RDS properties.
Example .ebextensions/db-instance-properties.config
Resources:
AWSEBRDSDatabase:
Type: AWS::RDS::DBInstance
Properties:
StorageType:io1
Iops: 1000
You can choose to create a snapshot of the database and then terminate it, retain the database
operational as a standalone database external to Elastic Beanstalk, or permanently delete the
database. The Database deletion policy setting determines this result. For a detailed description of
the deletion policies, see Database lifecycle (p. 578) in this same topic.
• Do you need make any changes to the database configuration settings before decoupling it?
If you need to make any configuration changes to the database, you should apply them before
decoupling the database. This includes changes to the Database deletion policy. Any pending changes
that are submitted simultaneously with the Decouple database setting will be ignored, while only the
decouple setting is applied.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
581
AWS Elastic Beanstalk Developer Guide
Decoupling an RDS DB instance using the console
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Database configuration category, choose Edit.
5. Review all of the configurations values in the Database settings section, especially the Database
deletion policy, which determines what happens to the database after it's decoupled.
If all of the other configuration settings are correct, skip to Step 6 to decouple the database.
582
AWS Elastic Beanstalk Developer Guide
Decoupling an RDS DB instance using configuration files
Warning
It’s important to apply the Database deletion policy setting separately from Decouple
database. If you select Apply with the intent to save both Decouple database and a newly
selected Database deletion policy, the new deletion policy that you chose will be ignored.
Elastic Beanstalk will decouple the database following the prior-set deletion policy. If the
prior-set deletion policy is Delete or Create Snapshot, you risk losing the database
instead of following the intended pending policy.
The deletion policy setting determines the outcome for the database and the length of time that's
required to decouple the database.
• If the deletion policy is set to Delete, the database is deleted. The operation can take approximately
10-20 minutes, depending on the size of database.
• If the deletion policy is set to Snapshot, a snapshot of the database is created. Then, the database is
deleted. The length of time required for this process varies according to the size of the database.
• If the deletion policy is set to Retain, the database remains operational external to the Elastic
Beanstalk environment. It usually takes less than five minutes to decouple a database.
If you decided to retain the database external to your Elastic Beanstalk environment, you'll need to
take additional steps to configure it. For more information, see Using Elastic Beanstalk with Amazon
RDS (p. 923). If you plan to use the database that you decouple for a production environment, verify
the storage type that the database uses is suitable for your workload. For more information, see DB
Instance Storage and Modifying a DB instance in the Amazon RDS User Guide.
583
AWS Elastic Beanstalk Developer Guide
Decoupling an RDS DB instance using configuration files
Both of the options required to decouple the database are in the the section called
“aws:rds:dbinstance” (p. 672) namespace. They are as follows:
• The DBDeletionPolicy option sets the deletion policy. It can be set to the following values:
Snapshot, Delete, or Retain. These values are described in Database lifecycle (p. 578) in this same
topic.
• The HasCoupledDatabase option determines if your environment has a coupled database.
• If toggled to true, Elastic Beanstalk creates a new DB instance coupled to your environment.
• If toggled to false, Elastic Beanstalk starts decoupling the DB instance from your environment.
If you want to change your database configuration before you decouple it, apply any configuration
changes first, in a separate operation. This includes changing the DBDeletionPolicy configuration.
After your changes are applied, run a separate command to set the decoupling option. If you submit
other configuration settings and the decouple setting at the same time, the other configuration option
settings are ignored while the decouple setting is applied.
Warning
It’s important that you run the commands to apply the DBDeletionPolicy and
HasCoupledDatabase settings as two separate operations. If the active deletion policy is
already set to Delete or Snapshot, you risk losing the database. The database follows the
deletion policy that's currently active, rather than the pending deletion policy that you intended.
Follow these steps to decouple the database from your Elastic Beanstalk environment. You can use
the EB CLI or the AWS CLI to complete the steps. For more information, see Advanced environment
customization with configuration files (p. 683).
1. If you want to change the deletion policy, set up a configuration file in the following format. In this
example, the deletion policy is set to retain.
Example
option_settings:
aws:rds:dbinstance:
DBDeletionPolicy: Retain
2. Run the command using your preferred tool to complete the configuration update.
3. Set up a configuration file to set HasCoupledDatabase to false.
Example
option_settings:
aws:rds:dbinstance:
HasCoupledDatabase: false
4. Run the command using your preferred tool to complete the configuration update.
The deletion policy setting determines the outcome for the database and the length of time that's
required to decouple the database.
• If the deletion policy is set to Delete, the database is deleted. The operation can take approximately
10-20 minutes, depending on the size of database.
• If the deletion policy is set to Snapshot, a snapshot of the database is created. Then, the database is
deleted. The length of time required for this process varies according to the size of the database.
584
AWS Elastic Beanstalk Developer Guide
Security
• If the deletion policy is set to Retain, the database remains operational external to the Elastic
Beanstalk environment. It usually takes less than five minutes to decouple a database.
If you decided to retain the database external to your Elastic Beanstalk environment, you'll need to
take additional steps to configure it. For more information, see Using Elastic Beanstalk with Amazon
RDS (p. 923). If you plan to use the database that you decouple for a production environment, verify
the storage type that the database uses is suitable for your workload. For more information, see DB
Instance Storage and Modifying a DB instance in the Amazon RDS User Guide.
Sections
• Configuring your environment security (p. 585)
• Environment security configuration namespaces (p. 587)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Security configuration category, choose Edit.
Settings
• Service role (p. 586)
• EC2 key pair (p. 586)
• IAM instance profile (p. 587)
585
AWS Elastic Beanstalk Developer Guide
Configuring your environment security
Service role
Select a service role (p. 860) to associate with your Elastic Beanstalk environment. Elastic Beanstalk
assumes the service role when it accesses other AWS services on your behalf. For details, see Managing
Elastic Beanstalk service roles (p. 860).
586
AWS Elastic Beanstalk Developer Guide
Environment security configuration namespaces
Choose an EC2 key pair from the drop-down menu to assign it to your environment's instances. When
you assign a key pair, the public key is stored on the instance to authenticate the private key, which you
store locally. The private key is never stored on AWS.
For more information about connecting to Amazon EC2 instances, see Connect to Your Instance and
Connecting to Linux/UNIX Instances from Windows using PuTTY in the Amazon EC2 User Guide for Linux
Instances.
The first time you create an environment in the Elastic Beanstalk console, Elastic Beanstalk prompts you
to create an instance profile with a default set of permissions. You can add permissions to this profile to
provide your instances access to other AWS services. For details, see Managing Elastic Beanstalk instance
profiles (p. 855).
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
Elastic Beanstalk applies environment tags to the environment resource itself, as well as to other AWS
resources that Elastic Beanstalk creates for the environment. You can use tags to manage permissions at
the specific resource level within an environment. For more information, see Tagging Your Amazon EC2
Resources in the Amazon EC2 User Guide for Linux Instances.
587
AWS Elastic Beanstalk Developer Guide
Adding tags during environment creation
You can specify tags when you create the Elastic Beanstalk environment. In an existing environment, you
can add or remove tags, and update the values of existing tags. An environment can have up to 50 tags
including the default tags.
If you use the EB CLI to create an environment, use the --tags option with eb create (p. 1003) to add
tags.
With the AWS CLI or other API-based clients, use the --tags parameter on the create-environment
command.
Saved configurations (p. 617) include user-defined tags. When you apply a saved configuration that
contains tags during environment creation, those tags are applied to the new environment, as long as
you don't specify any new tags. If you add tags to an environment using one of the preceding methods,
any tags defined in the saved configuration are discarded.
However, you can't edit the default tags that Elastic Beanstalk applies to your environment.
588
AWS Elastic Beanstalk Developer Guide
Managing tags of an existing environment
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Tags.
The tag management page shows the list of tags that currently exist in the environment.
• To add a tag, enter it into the empty boxes at the bottom of the list. To add another tag, choose
Add tag and Elastic Beanstalk adds another pair of empty boxes.
• To update a tag's key or value, edit the respective box in the tag's row.
• To delete a tag, choose Remove next to the tag's value box.
5. Choose Apply.
If you use the EB CLI to update your environment, use eb tags (p. 1040) to add, update, delete, or list
tags.
589
AWS Elastic Beanstalk Developer Guide
Software settings
For example, the following command lists the tags in your default environment.
The following command updates the tag mytag1 and deletes the tag mytag2.
For a complete list of options and more examples, see eb tags (p. 1040).
With the AWS CLI or other API-based clients, use the list-tags-for-resource command to list the tags of
an environment.
Specify both tags to add and tags to update in the --tags-to-add parameter of update-tags-for-
resource. A nonexisting tag is added, and an existing tag's value is updated.
Note
To use these two AWS CLI commands with an Elastic Beanstalk environment, you need the
environment's ARN. You can retrieve the ARN by using the following command.
590
AWS Elastic Beanstalk Developer Guide
Configure platform-specific settings
Topics
• Configure platform-specific settings (p. 591)
• Configuring environment properties (p. 592)
• Software setting namespaces (p. 593)
• Accessing environment properties (p. 595)
• Configuring AWS X-Ray debugging (p. 595)
• Viewing your Elastic Beanstalk environment logs (p. 598)
• Preset environment properties – The Ruby platform uses environment properties for framework
settings, such as RACK_ENV and BUNDLE_WITHOUT.
• Placeholder environment properties – The Tomcat platform defines an environment property named
JDBC_CONNECTION_STRING that is not set to any value. This type of setting was more common on
older platform versions.
• Configuration options – Most platforms define configuration options (p. 613) in
platform-specific or shared namespaces, such as aws:elasticbeanstalk:xray or
aws:elasticbeanstalk:container:python.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
591
AWS Elastic Beanstalk Developer Guide
Configuring environment properties
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. Under Platform options, make necessary option setting changes.
6. Choose Apply.
For information about platform-specific options, and about getting environment property values in your
code, see the platform topic for your language or framework:
In addition, when you add a database to your environment (p. 577), Elastic Beanstalk sets environment
properties, such as RDS_HOSTNAME, that you can read in your application code to construct a connection
object or string.
Environment variables
In most cases, environment properties are passed to your application as environment
variables, but the behavior is platform dependent. For example, the Java SE platform (p. 126)
sets environment variables that you retrieve with System.getenv, while the Tomcat
platform (p. 115) sets Java system properties that you retrieve with System.getProperty. In
general, properties are not visible if you connect to an instance and run env.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. Under Environment properties, enter key-value pairs.
592
AWS Elastic Beanstalk Developer Guide
Software setting namespaces
6. Choose Apply.
• Keys can contain any alphanumeric characters and the following symbols: _ . : / + \ - @
The symbols listed are valid for environment property keys, but might not be valid for environment
variable names on your environment's platform. For compatibility with all platforms, limit
environment properties to the following pattern: [A-Z_][A-Z0-9_]*
• Values can contain any alphanumeric characters, white space, and the following symbols: _ . : / =
+ \ - @ ' "
Note
Single and double quotation marks in values must be escaped.
• Keys can contain up to 128 characters. Values can contain up to 256 characters.
• Keys and values are case sensitive.
• The combined size of all environment properties cannot exceed 4,096 bytes when stored as strings
with the format key=value.
You can use Elastic Beanstalk configuration files (p. 683) to set environment
properties and configuration options in your source code. Use the
aws:elasticbeanstalk:application:environment namespace (p. 648) to define environment
properties.
Example .ebextensions/options.config
option_settings:
aws:elasticbeanstalk:application:environment:
593
AWS Elastic Beanstalk Developer Guide
Software setting namespaces
API_ENDPOINT: www.example.com/api
If you use configuration files or AWS CloudFormation templates to create custom resources (p. 703),
you can use an AWS CloudFormation function to get information about the resource and assign it to
an environment property dynamically during deployment. The following example from the elastic-
beanstalk-samples GitHub repository uses the Ref function (p. 708) to get the ARN of an Amazon SNS
topic that it creates, and assigns it to an environment property named NOTIFICATION_TOPIC.
Notes
• If you use an AWS CloudFormation function to define an environment property, the Elastic
Beanstalk console displays the value of the property before the function is evaluated. You can
use the get-config platform script (p. 42) to confirm the values of environment properties
that are available to your application.
• The Multicontainer Docker (p. 65) platform doesn't use AWS CloudFormation to create
container resources. As a result, this platform doesn't support defining environment
properties using AWS CloudFormation functions.
Example .Ebextensions/sns-topic.config
Resources:
NotificationTopic:
Type: AWS::SNS::Topic
option_settings:
aws:elasticbeanstalk:application:environment:
NOTIFICATION_TOPIC: '`{"Ref" : "NotificationTopic"}`'
You can also use this feature to propagate information from AWS CloudFormation pseudo parameters.
This example gets the current region and assigns it to a property named AWS_REGION.
Example .Ebextensions/env-regionname.config
option_settings:
aws:elasticbeanstalk:application:environment:
AWS_REGION: '`{"Ref" : "AWS::Region"}`'
Most Elastic Beanstalk platforms define additional namespaces with options for configuring software
that runs on the instance, such as the reverse proxy that relays requests to your application. For more
information about the namespaces available for your platform, see the following:
Elastic Beanstalk provides many configuration options for customizing your environment. In addition to
configuration files, you can also set configuration options using the console, saved configurations, the EB
CLI, or the AWS CLI. See Configuration options (p. 613) for more information.
594
AWS Elastic Beanstalk Developer Guide
Accessing environment properties
endpoint := os.Getenv("API_ENDPOINT")
$endpoint = $_SERVER['API_ENDPOINT'];
import os
endpoint = os.environ['API_ENDPOINT']
endpoint = ENV['API_ENDPOINT']
Outside of application code, such as in a script that runs during deployment, you can access environment
properties with the get-config platform script (p. 42). See the elastic-beanstalk-samples GitHub
repository for example configurations that use get-config.
595
AWS Elastic Beanstalk Developer Guide
Debugging
Note
Some regions don't offer X-Ray. If you create an environment in one of these regions, you can't
run the X-Ray daemon on the instances in your environment.
For information about the AWS services offered in each Region, see Region Table.
X-Ray provides an SDK that you can use to instrument your application code, and a daemon application
that relays debugging information from the SDK to the X-Ray API.
Supported platforms
You can use the X-Ray SDK with the following Elastic Beanstalk platforms:
596
AWS Elastic Beanstalk Developer Guide
Debugging
On supported platforms, you can use a configuration option to run the X-Ray daemon on the instances
in your environment. You can enable the daemon in the Elastic Beanstalk console (p. 597) or by using a
configuration file (p. 597).
To upload data to X-Ray, the X-Ray daemon requires IAM permissions in the AWSXrayWriteOnlyAccess
managed policy. These permissions are included in the Elastic Beanstalk instance profile (p. 21). If you
don't use the default instance profile, see Giving the Daemon Permission to Send Data to X-Ray in the
AWS X-Ray Developer Guide.
Debugging with X-Ray requires the use of the X-Ray SDK. See the Getting Started with AWS X-Ray in the
AWS X-Ray Developer Guide for instructions and sample applications.
If you use a platform version that doesn't include the daemon, you can still run it with a script in a
configuration file. For more information, see Downloading and Running the X-Ray Daemon Manually
(Advanced) in the AWS X-Ray Developer Guide.
Sections
• Configuring debugging (p. 597)
• The aws:elasticbeanstalk:xray namespace (p. 597)
Configuring debugging
You can enable the X-Ray daemon on a running environment in the Elastic Beanstalk console.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the AWS X-Ray section, select X-Ray daemon.
6. Choose Apply.
You can also enable this option during environment creation. For more information, see The create new
environment wizard (p. 409).
To enable debugging automatically when you deploy your application, set the option in a configuration
file (p. 683) in your source code, as follows.
Example .ebextensions/debugging.config
option_settings:
aws:elasticbeanstalk:xray:
XRayEnabled: true
597
AWS Elastic Beanstalk Developer Guide
Log viewing
• Configure your Elastic Beanstalk environment to upload rotated instance logs to the environment's
Amazon S3 bucket.
• Configure the environment to stream instance logs to Amazon CloudWatch Logs.
When you configure instance log streaming to CloudWatch Logs, Elastic Beanstalk creates CloudWatch
Logs log groups for proxy and deployment logs on the Amazon EC2 instances, and transfers these log
files to CloudWatch Logs in real time. For more information about instance logs, see Viewing logs from
Amazon EC2 instances in your Elastic Beanstalk environment (p. 820).
In addition to instance logs, if you enable enhanced health (p. 776) for your environment, you can
configure the environment to stream health information to CloudWatch Logs. When the environment's
health status changes, Elastic Beanstalk adds a record to a health log group, with the new status and
a description of the cause of the change. For information about environment health streaming, see
Streaming Elastic Beanstalk environment health information to Amazon CloudWatch Logs (p. 839).
To configure instance log rotation and log streaming in the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the S3 log storage section, select Rotate logs to enable uploading rotated logs to Amazon S3.
6. in the Instance log streaming to CloudWatch Logs section, configure the following settings:
598
AWS Elastic Beanstalk Developer Guide
Log viewing
7. Choose Apply.
After you enable log streaming, you can return to the Software configuration category or page and find
the Log Groups link. Click this link to see your instance logs in the CloudWatch console.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Monitoring configuration category, choose Edit.
5. Under Health event streaming to CloudWatch Logs, configure the following settings:
After you enable log streaming, you can return to the Monitoring configuration category or page and
find the Log Group link. Click this link to see your environment health logs in the CloudWatch console.
599
AWS Elastic Beanstalk Developer Guide
Notifications
When you configure notifications for your environment, Elastic Beanstalk creates an Amazon SNS topic
for your environment on your behalf. To send messages to an Amazon SNS topic, Elastic Beanstalk
must have the required permission. For more information, see Configuring permissions to send
notifications (p. 603).
When a notable event (p. 816) occurs, Elastic Beanstalk sends a message to the topic. Then, Amazon
SNS relays the messages that it receives to the topic's subscribers. Notable events include environment
creation errors and all changes in environment and instance health (p. 776). Events for Amazon
600
AWS Elastic Beanstalk Developer Guide
Configuring notifications using
the Elastic Beanstalk console
EC2 Auto Scaling operations (like adding and removing instances from the environment) and other
informational events don't trigger notifications.
You can enter an email address in the Elastic Beanstalk console when you create an environment or
sometime afterwards. This will create an Amazon SNS topic and subscribe to it. Elastic Beanstalk
manages the lifecycle of the topic, and deletes it when your environment is terminated or when you
remove your email address in the environment management console (p. 396).
You can only turn Amazon SNS notifications on or off. The frequency of notifications sent to the topic
can be high, depending on the size and composition of your environment. For configuring notifications
to be sent on specific circumstances, you have other options. You can set up event-driven rules (p. 841)
with Amazon EventBridge that notify you when Elastic Beanstalk emits events that meet specific criteria.
Or, alternatively, you can configure your environment to publish custom metrics (p. 800) and set
Amazon CloudWatch alarms (p. 811) to notify you when those metrics reach an unhealthy threshold.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Notifications configuration category, choose Edit.
5. Enter an email address.
601
AWS Elastic Beanstalk Developer Guide
Configuring notifications using configuration options
6. Choose Apply.
When you enter an email address for notifications, Elastic Beanstalk creates an Amazon SNS topic for
your environment and adds a subscription. Amazon SNS sends an email to the subscribed address to
confirm the subscription. You must click the link in the confirmation email to activate the subscription
and receive notifications.
• Notification Endpoint – The email address, Amazon SQS queue, or URL to send notifications to. If
you set this option, then an SQS queue and a subscription for the specified endpoint are created. If
the endpoint isn't an email address, you must also set the Notification Protocol option. SNS
validates the value of Notification Endpoint based on the value of Notification Protocol.
Setting this option multiple times creates additional subscriptions to the topic. If you remove this
option, the topic is deleted.
• Notification Protocol – The protocol that's used to send notifications to the Notification
Endpoint. This option defaults to email. Set this option to email-json to send JSON-formatted
emails, http or https to post JSON-formatted notifications to an HTTP endpoint, or sqs to send
notifications to an SQS queue.
Note
AWS Lambda notifications aren't supported.
• Notification Topic ARN – After setting a notification endpoint for your environment, read this
setting to get the ARN of the SNS topic. You can also set this option to use an existing SNS topic for
notifications. A topic that you attach to your environment though this option isn't deleted when you
change this option or terminate the environment.
602
AWS Elastic Beanstalk Developer Guide
Configuring permissions to send notifications
To configure Amazon SNS notifications, you need to have the required permissions. If your IAM user
uses the Elastic Beanstalk AdministratorAccess-AWSElasticBeanstalk managed user policy (p. 879),
then you should already have the required permissions to configure the default Amazon SNS topic that
Elastic Beanstalk creates for your environment. However, if you configure an Amazon SNS topic that
Elastic Beanstalk doesn't manage, then you need to add the following policy to your user role.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:SetTopicAttributes",
"sns:GetTopicAttributes",
"sns:Subscribe",
"sns:Unsubscribe",
"sns:Publish"
],
"Resource": [
"arn:aws:sns:us-east-2:123456789012:sns_topic_name"
]
}
]
}
• Notification Topic Name – Set this option to customize the name of the Amazon SNS topic used for
environment notifications. If a topic with the same name already exists, Elastic Beanstalk attaches that
topic to the environment.
Warning
If you attach an existing SNS topic to an environment with Notification Topic Name,
Elastic Beanstalk will delete the topic in the event that you terminate the environment or
change this setting sometime in the future.
If you change this option, the Notification Topic ARN is also changed. If a topic is already
attached to the environment, Elastic Beanstalk deletes the old topic and creates a new topic and
subscription.
By using a custom topic name, you must also provide an ARN of an externally created custom topic.
The managed user policy doesn't automatically detect a topic with a custom name, so you must
provide custom Amazon SNS permissions to your IAM users. Use a policy similar to the one that's used
for a custom topic ARN, but include the following additions:
• Include two more actions in the Actions list, specifically: sns:CreateTopic, sns:DeleteTopic
• If you're changing the Notification Topic Name from one custom topic name to another, you
must also include the ARNs of both topics in the Resource list. Alternatively, include a regular
expression that covers both topics. This way Elastic Beanstalk has permissions to delete the old topic
and create the new one.
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
• Use the default Amazon SNS topic that Elastic Beanstalk creates for your environment.
603
AWS Elastic Beanstalk Developer Guide
Configuring permissions to send notifications
The default access policy for an Amazon SNS topic allows only the topic owner to publish or subscribe
to it. However, through the proper policy configuration, Elastic Beanstalk can be granted permission to
publish to an Amazon SNS topic in either one of the two cases described in this section. The following
subsections provide more information.
However, if you provided a custom service role when you created your environment, make sure that this
custom service role includes the following policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": [
"arn:aws:sns:us-east-2:123456789012:ElasticBeanstalkNotifications*"
]
}
]
}
If you provide a custom service role for your environment, make sure that your custom service role
includes the following policy to allow Elastic Beanstalk to send messages to the Amazon SNS topic. In
the following code, replace sns_topic_name with the name of the Amazon SNS topic that you provided
in the configuration options.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
604
AWS Elastic Beanstalk Developer Guide
Amazon VPC
],
"Resource": [
"arn:aws:sns:us-east-2:123456789012:sns_topic_name"
]
}
]
}
For more information about Amazon SNS access control, see Example cases for Amazon SNS access
control in the Amazon Simple Notification Service Developer Guide.
You can launch your environment in a custom VPC to customize networking and security settings. Elastic
Beanstalk lets you choose which subnets to use for your resources, and how to configure IP addresses for
the instances and load balancer in your environment. An environment is locked to a VPC when you create
it, but you can change subnet and IP address settings on a running environment.
Note
If you created your AWS account before December 4, 2013, you might have environments
using the Amazon EC2-Classic network configuration in some AWS Regions instead of
Amazon VPC. For information on migrating your environments from an EC2-Classic to a VPC
network configuration, see Migrating Elastic Beanstalk environments from EC2-Classic to a
VPC (p. 609).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Network configuration category, choose Edit.
Options
• VPC (p. 606)
605
AWS Elastic Beanstalk Developer Guide
Configuring VPC settings in the Elastic Beanstalk console
VPC
Choose a VPC for your environment. You can only change this setting during environment creation.
606
AWS Elastic Beanstalk Developer Guide
Configuring VPC settings in the Elastic Beanstalk console
Instance subnets
Choose subnets for your application instances. Choose at least one subnet for each availability zone that
your load balancer uses. If you choose private subnets for your instances, your VPC must have a NAT
gateway in a public subnet that the instances can use to access the Internet.
607
AWS Elastic Beanstalk Developer Guide
The aws:ec2:vpc namespace
Database subnets
When you run an Amazon RDS database attached to your Elastic Beanstalk environment, choose subnets
for your database instances. For high availability, make the database multi-AZ and choose a subnet for
each availability zone. To ensure that your application can connect to your database, run both in the
same subnets.
The following configuration file (p. 683) uses options in this namespace to set the environment's
VPC and subnets for a public-private configuration. In order to set the VPC ID in a configuration file,
the file must be included in the application source bundle during environment creation. See Setting
configuration options during environment creation (p. 620) for other methods of configuring these
settings during environment creation.
option_settings:
aws:ec2:vpc:
VPCId: vpc-087a68c03b9c50c84
AssociatePublicIpAddress: 'false'
608
AWS Elastic Beanstalk Developer Guide
Migrating from EC2-Classic to a VPC
ELBScheme: public
ELBSubnets: subnet-0fe6b36bcb0ffc462,subnet-032fe3068297ac5b2
Subnets: subnet-026c6117b178a9c45,subnet-0839e902f656e8bd1
This example shows a public-public configuration, where the load balancer and EC2 instances run in the
same public subnets.
option_settings:
aws:ec2:vpc:
VPCId: vpc-087a68c03b9c50c84
AssociatePublicIpAddress: 'true'
ELBScheme: public
ELBSubnets: subnet-0fe6b36bcb0ffc462,subnet-032fe3068297ac5b2
Subnets: subnet-0fe6b36bcb0ffc462,subnet-032fe3068297ac5b2
If you created your AWS account before December 4, 2013, you might have environments that use the
EC2-Classic network configuration in some AWS Regions. All AWS accounts created on or after December
4, 2013 are already VPC-only in every AWS Region. The only exemptions are if Amazon EC2-Classic was
enabled as a result of a support request.
Note
You can view the network configuration settings for your environment in the Network
configuration category on the Configuration overview (p. 492) page of the Elastic Beanstalk
console.
When you migrate your Elastic Beanstalk environments from Amazon EC2-Classic to Amazon VPC, you
must create a new AWS account. You must also re-create your AWS EC2-Classic environments in your
new AWS account. No additional configuration work for your environments is required to use the default
VPC. If the default VPC doesn't meet your requirements, manually create a custom VPC and associate it
with your environments.
Alternatively, if your existing AWS account has resources that you can't migrate to a new AWS account,
add a VPC into your current account. Then, configure your environments to use the VPC.
For more information, see the EC2-Classic Networking is Retiring - Here's How to Prepare blog post.
609
AWS Elastic Beanstalk Developer Guide
Migrating from EC2-Classic to a VPC
1. Your new AWS account provides a default VPC to its environments. If you don't need to create a
custom VPC, skip to step 2.
• Create a VPC quickly using the Amazon VPC console wizard with one of the available configuration
options. For more information, see Amazon VPC console wizard configurations.
• Create a custom VPC on the Amazon VPC console if you have more specific requirements for
your VPC. We recommend you do this, for example, if your use case requires a specific number of
subnets. For more information, see VPCs and subnets.
• Create a VPC using the elastic-beanstalk-samples repository on the GitHub website if you prefer
to use AWS CloudFormation templates with your Elastic Beanstalk environments. This repository
includes AWS CloudFormation templates. For more information, see Using Elastic Beanstalk with
Amazon VPC (p. 938).
Note
You can also create a custom VPC at the same time you recreate the environment in your
new AWS account using the create new environment wizard (p. 409). If you use the wizard
and choose to create a custom VPC, the wizard redirects you to the Amazon VPC console.
2. In your new AWS account, create a new environment. We recommend that the environment includes
the same configuration as your existing environment in the AWS account that you're migrating from.
You can do this by using one of the following approaches.
Note
If your new environment must use the same CNAME after you migrate, terminate the
original environment on the EC2-Classic platform. This releases the CNAME for use.
However, doing so can result in downtime for that environment and can also risk that
another customer might select your CNAME between you terminating your EC2-Classic
environment and creating the new one. For more information, see Terminate an Elastic
Beanstalk environment (p. 430).
For environments that have their own proprietary domain name, the CNAME doesn't have
this issue. You can just update your Domain Name System (DNS) to forward requests to
your new CNAME.
• Use the create new environment wizard (p. 409) on the Elastic Beanstalk console. The wizard
provides an option to create a custom VPC. If you don't choose to create a custom VPC, a
default VPC is assigned.
• Use the Elastic Beanstalk Command Line Interface (EB CLI) to re-create your environment in
your new AWS account. One of the examples (p. 1011) in the eb create command description
demonstrates the creation of an environment in a custom VPC. If you don't provide a VPC ID,
the environment uses the default VPC.
By using this approach, you can use a saved configurations file across the two AWS accounts. As
a result, you don't need to manually enter all the configuration information. However, you must
save the configuration settings for the EC2-Classic environment that you're migrating with the
eb config save (p. 997) command. Copy the saved configuration file to a new directory for the
new account environment.
Note
You must edit some of the data in the saved configuration file before you can use it
in the new account. You must also update information that pertains to your previous
account with the correct data for your new account. For example, you must replace the
Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role
with the IAM role ARN for the new account.
If you use the eb create (p. 1003) command with the cfg, the new environment is created using
the specified saved configuration file. For more information, see Using Elastic Beanstalk saved
configurations (p. 721).
610
AWS Elastic Beanstalk Developer Guide
Migrating from EC2-Classic to a VPC
Prerequisites
Before you begin, you must have a VPC. You can create a non-default (custom) VPC in one of the
following ways:
• Create a VPC quickly using the Amazon VPC console wizard with one of the available configuration
options. For more information, see Amazon VPC console wizard configurations.
• Create a custom VPC on the Amazon VPC console if you have more specific requirements for your VPC.
We recommend you do this, for example, if your use case requires a specific number of subnets. For
more information, see VPCs and subnets.
• Create a VPC using the elastic-beanstalk-samples repository on the GitHub website if you prefer to
use AWS CloudFormation templates with your Elastic Beanstalk environments. This repository includes
AWS CloudFormation templates. For more information, see Using Elastic Beanstalk with Amazon
VPC (p. 938).
In the following steps, you use the generated VPC ID and subnet IDs when you configure the VPC in the
new environment.
1. Create a new environment that includes the same configuration as your existing environment. You
can do this by using one of the following approaches.
Note
The Saved Configurations feature can help you re-create your environments in the new
account. This feature can save an environment’s configuration, so you can apply it when
you create or update other environments. For more information, see Using Elastic Beanstalk
saved configurations (p. 721).
• Using the Elastic Beanstalk console, apply a saved configuration from your EC2-Classic
environment when you configure the new environment. This configuration will use the VPC. For
more information, see Using Elastic Beanstalk saved configurations (p. 721).
• Using Elastic Beanstalk Command Line Interface (EB CLI), run the eb create (p. 1003) command
to re-create your environment. Provide the parameters of your original environment and the
VPC identifier. One of the examples (p. 1011) in the eb create command description shows how
to create an environment in a custom VPC.
• Use the AWS Command Line Interface (AWS CLI), and re-create your environment using
the elasticbeanstalk create-environment command. Provide the parameters of your
original environment with the VPC identifier. For instructions, see Creating Elastic Beanstalk
environments with the AWS CLI (p. 431).
2. Swap the CNAMEs of the existing environment with the new environment. This way, the new
environment that you created can be referenced with the familiar address. You can use the EB CLI or
the AWS CLI.
• Using the EB CLI, swap the environment CNAMEs by running the eb swap command. For more
information, see Using the Elastic Beanstalk command line interface (EB CLI) (p. 956).
• Using the AWS CLI, swap the environment CNAMEs with the elasticbeanstalk swap-
environment-cnames command. For more information, see the AWS CLI Command Reference.
611
AWS Elastic Beanstalk Developer Guide
Domain name
To route users to your environment, Elastic Beanstalk registers a CNAME record that points to your
environment's load balancer. You can see URL of your environment's application with the current value of
the CNAME in the environment overview (p. 398) page of the Elastic Beanstalk console.
Choose the URL on the overview page, or choose Go to environment on the navigation pane, to navigate
to your application's web page.
You can change the CNAME on your environment by swapping it with the CNAME of another
environment. For instructions, see Blue/Green deployments with Elastic Beanstalk (p. 449).
If you own a domain name, you can use Amazon Route 53 to resolve it to your environment. You can
purchase a domain name with Amazon Route 53, or use one that you purchase from another provider.
To purchase a domain name with Route 53, see Registering a New Domain in the Amazon Route 53
Developer Guide.
To learn more about using a custom domain, see Routing Traffic to an AWS Elastic Beanstalk
Environment in the Amazon Route 53 Developer Guide.
Important
If you terminate an environment, you must also delete any CNAME mappings you created, as
other customers can reuse an available hostname.
612
AWS Elastic Beanstalk Developer Guide
Configuration options
Most of the configuration options have default values that are applied automatically by Elastic
Beanstalk. You can override these defaults with configuration files, saved configurations, command line
options, or by directly calling the Elastic Beanstalk API. The EB CLI and Elastic Beanstalk console also
apply recommended values for some options.
You can easily customize your environment at the same time that you deploy your application version by
including a configuration file with your source bundle. When customizing the software on your instance,
it is more advantageous to use a configuration file than to create a custom AMI because you do not need
to maintain a set of AMIs.
When deploying your applications, you may want to customize and configure the software that your
application depends on. These files could be either dependencies required by the application—for
example, additional packages from the yum repository—or they could be configuration files such as a
replacement for httpd.conf to override specific settings that are defaulted by AWS Elastic Beanstalk.
Topics
• Configuration options (p. 613)
• Advanced environment customization with configuration files (.ebextensions) (p. 683)
• Using Elastic Beanstalk saved configurations (p. 721)
• Environment manifest (env.yaml) (p. 727)
• Using a custom Amazon machine image (AMI) (p. 729)
• Serving static files (p. 732)
• Configuring HTTPS for your Elastic Beanstalk environment (p. 734)
Configuration options
Elastic Beanstalk defines a large number of configuration options that you can use to configure your
environment's behavior and the resources that it contains. Configuration options are organized into
namespaces like aws:autoscaling:asg, which defines options for an environment's Auto Scaling
group.
The Elastic Beanstalk console and EB CLI set configuration options when you create an environment,
including options that you set explicitly, and recommended values (p. 614) defined by the client. You
can also set configuration options in saved configurations and configuration files. If the same option is
set in multiple locations, the value used is determined by the order of precedence (p. 614).
Configuration option settings can be composed in text format and saved prior to environment creation,
applied during environment creation using any supported client, and added, modified or removed
after environment creation. For a detailed breakdown of all of the available methods for working with
configuration options at each of these three stages, read the following topics:
613
AWS Elastic Beanstalk Developer Guide
Precedence
For a complete list of namespaces and options, including default and supported values for each, see
General options for all environments (p. 632) and Platform specific options (p. 674).
Precedence
During environment creation, configuration options are applied from multiple sources with the following
precedence, from highest to lowest:
• Settings applied directly to the environment – Settings specified during a create environment
or update environment operation on the Elastic Beanstalk API by any client, including the Elastic
Beanstalk console, EB CLI, AWS CLI, and SDKs. The Elastic Beanstalk console and EB CLI also apply
recommended values (p. 614) for some options that apply at this level unless overridden.
• Saved Configurations – Settings for any options that are not applied directly to the environment are
loaded from a saved configuration, if specified.
• Configuration Files (.ebextensions) – Settings for any options that are not applied directly to the
environment, and also not specified in a saved configuration, are loaded from configuration files in the
.ebextensions folder at the root of the application source bundle.
If the same configuration option is defined in more than one location, the setting with the highest
precedence is applied. When a setting is applied from a saved configuration or settings applied directly
to the environment, the setting is stored as part of the environment's configuration. These settings can
be removed with the AWS CLI (p. 631) or with the EB CLI (p. 629).
Settings in configuration files are not applied directly to the environment and cannot be removed
without modifying the configuration files and deploying a new application version. If a setting applied
with one of the other methods is removed, the same setting will be loaded from configuration files in the
source bundle.
For example, say you set the minimum number of instances in your environment to 5 during
environment creation, using either the Elastic Beanstalk console, a command line option, or a saved
configuration. The source bundle for your application also includes a configuration file that sets the
minimum number of instances to 2.
When you create the environment, Elastic Beanstalk sets the MinSize option in the
aws:autoscaling:asg namespace to 5. If you then remove the option from the environment
configuration, the value in the configuration file is loaded, and the minimum number of instances is set
to 2. If you then remove the configuration file from the source bundle and redeploy, Elastic Beanstalk
uses the default setting of 1.
Recommended values
The Elastic Beanstalk Command Line Interface (EB CLI) and Elastic Beanstalk console provide
recommended values for some configuration options. These values can be different from the default
values and are set at the API level when your environment is created. Recommended values allow Elastic
Beanstalk to improve the default environment configuration without making backwards incompatible
changes to the API.
614
AWS Elastic Beanstalk Developer Guide
Recommended values
For example, both the EB CLI and Elastic Beanstalk console set the configuration option for EC2
instance type (InstanceType in the aws:autoscaling:launchconfiguration namespace).
Each client provides a different way of overriding the default setting. In the console you can choose
a different instance type from a drop down menu on the Configuration Details page of the Create
New Environment wizard. With the EB CLI, you can use the --instance_type parameter for eb
create (p. 1003).
Because the recommended values are set at the API level, they will override values for the same options
that you set in configuration files or saved configurations. The following options are set:
• Namespace: aws:autoscaling:launchconfiguration
EB CLI
• Namespace: aws:autoscaling:launchconfiguration
615
AWS Elastic Beanstalk Developer Guide
Before environment creation
Elastic Beanstalk supports two methods of saving configuration option settings. Configuration files
in YAML or JSON format can be included in your application's source code in a directory named
.ebextensions and deployed as part of your application source bundle. You create and manage
configuration files locally.
Saved configurations are templates that you create from a running environment or JSON options file
and store in Elastic Beanstalk. Existing saved configurations can also be extended to create a new
configuration.
Note
Settings defined in configuration files and saved configurations have lower precedence than
settings configured during or after environment creation, including recommended values
applied by the Elastic Beanstalk console and EB CLI (p. 956). See Precedence (p. 614) for
details.
Options can also be specified in a JSON document and provided directly to Elastic Beanstalk when
you create or update an environment with the EB CLI or AWS CLI. Options provided directly to Elastic
Beanstalk in this manner override all other methods.
For a full list of available options, see Configuration options (p. 613).
Methods
• Configuration files (.ebextensions) (p. 616)
• Saved configurations (p. 617)
• JSON document (p. 619)
• EB CLI configuration (p. 619)
616
AWS Elastic Beanstalk Developer Guide
Before environment creation
To use configuration files, create a folder named .ebextensions at the top level of your project's
source code. Add a file with the extension .config and specify options in the following manner:
option_settings:
- namespace: namespace
option_name: option name
value: option value
- namespace: namespace
option_name: option name
value: option value
For example, the following configuration file sets the application's health check url to /health:
healthcheckurl.config
option_settings:
- namespace: aws:elasticbeanstalk:application
option_name: Application Healthcheck URL
value: /health
In JSON:
{
"option_settings" :
[
{
"namespace" : "aws:elasticbeanstalk:application",
"option_name" : "Application Healthcheck URL",
"value" : "/health"
}
]
}
This configures the Elastic Load Balancing load balancer in your Elastic Beanstalk environment to make
an HTTP request to the path /health to each EC2 instance to determine if it is healthy or not.
Note
YAML relies on consistent indentation. Match the indentation level when replacing content in an
example configuration file and ensure that your text editor uses spaces, not tab characters, to
indent.
Include the .ebextensions directory in your Application Source Bundle (p. 385) and deploy it to a new
or existing Elastic Beanstalk environment.
Saved configurations
Create a saved configuration to save settings that you have applied to an existing environment during
or after environment creation by using the Elastic Beanstalk console, EB CLI, or AWS CLI. Saved
configurations belong to an application and can be applied to new or existing environments for that
application.
Clients
• Elastic Beanstalk console (p. 618)
• EB CLI (p. 618)
• AWS CLI (p. 618)
617
AWS Elastic Beanstalk Developer Guide
Before environment creation
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Save configuration.
4. Use the on-screen dialog box to complete the action.
Saved configurations are stored in the Elastic Beanstalk S3 bucket in a folder named after your
application. For example, configurations for an application named my-app in the us-west-2
region for account number 123456789012 can be found at s3://elasticbeanstalk-us-
west-2-123456789012/resources/templates/my-app.
EB CLI
The EB CLI (p. 956) also provides subcommands for interacting with saved configurations under eb
config (p. 997):
AWS CLI
Create a saved configuration from a running environment with aws elasticbeanstalk create-
configuration-template
618
AWS Elastic Beanstalk Developer Guide
Before environment creation
"EndpointURL": "awseb-e-v-AWSEBLoa-1JUM8159RA11M-43V6ZI1194.us-
west-2.elb.amazonaws.com",
"SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.2 running Multi-
container Docker 1.7.1 (Generic)",
"CNAME": "my-env-nfptuqaper.elasticbeanstalk.com",
"Health": "Green",
"AbortableOperationInProgress": false,
"Tier": {
"Version": " ",
"Type": "Standard",
"Name": "WebServer"
},
"HealthStatus": "Ok",
"DateUpdated": "2015-10-01T00:24:04.045Z",
"DateCreated": "2015-09-30T23:27:55.768Z"
}
]
}
Elastic Beanstalk saves the configuration to your Elastic Beanstalk bucket in Amazon S3.
JSON document
If you use the AWS CLI to create and update environments, you can also provide configuration options
in JSON format. A library of configuration files in JSON is useful if you use the AWS CLI to create and
manage environments.
For example, the following JSON document sets the application's health check url to /health:
~/ebconfigs/healthcheckurl.json
[
{
"Namespace": "aws:elasticbeanstalk:application",
"OptionName": "Application Healthcheck URL",
"Value": "/health"
}
]
EB CLI configuration
In addition to supporting saved configurations and direct environment configuration with eb config
commands, the EB CLI has a configuration file with an option named default_ec2_keyname
that you can use to specify an Amazon EC2 key pair for SSH access to the instances in your
environment. The EB CLI uses this option to set the EC2KeyName configuration option in the
aws:autoscaling:launchconfiguration namespace.
~/workspace/my-app/.elasticbeanstalk/config.yml
branch-defaults:
master:
environment: my-env
develop:
environment: my-env-dev
619
AWS Elastic Beanstalk Developer Guide
During creation
deploy:
artifact: ROOT.war
global:
application_name: my-app
default_ec2_keyname: my-keypair
default_platform: Tomcat 8 Java 8
default_region: us-west-2
profile: null
sc: git
For anything other than a one-off configuration change, you can store configuration files (p. 616)
locally, in your source bundle, or in Amazon S3.
This topic includes procedures for all of the methods to set configuration options during environment
creation.
Clients
• In the Elastic Beanstalk console (p. 620)
• Using the EB CLI (p. 621)
• Using the AWS CLI (p. 623)
Methods
• Using configuration files (.ebextensions) (p. 620)
• Using a saved configuration (p. 621)
• Using the new environment wizard (p. 621)
~/workspace/my-app-v1.zip
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- index.php
`-- styles.css
Upload the source bundle to Elastic Beanstalk normally, during environment creation (p. 407).
620
AWS Elastic Beanstalk Developer Guide
During creation
The Elastic Beanstalk console applies recommended values (p. 614) for some configuration options and
has form fields for others. Options configured by the Elastic Beanstalk console are applied directly to the
environment and override settings in configuration files.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Saved configurations.
4. Select the saved configuration you want to apply, and then choose Launch environment.
5. Proceed through the wizard to create your environment.
Saved configurations are application-specific. See Saved configurations (p. 617) for details on creating
saved configurations.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications.
3. Choose or create (p. 377) an application.
4. Choose Actions, and then choose Create environment.
5. Proceed through the wizard, and choose Configure more options.
6. Choose any of the configuration presets, and then choose Edit in one or more of the configuration
categories to change a group of related configuration options.
7. When you are done making option selections, choose Create environment.
Any options that you set in the new environment wizard are set directly on the environment and override
any option settings in saved configurations or configuration files (.ebextensions) that you apply. You
can remove settings after the environment is created using the EB CLI (p. 627) or AWS CLI (p. 629) to
allow the settings in saved configurations or configuration files to surface.
For details about the new environment wizard, see The create new environment wizard (p. 409).
621
AWS Elastic Beanstalk Developer Guide
During creation
~/workspace/my-app/
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- .elasticbeanstalk
| `-- config.yml
|-- index.php
`-- styles.css
Create your environment and deploy your source code to it with eb create.
You can store the saved configuration in your project folder or in your Elastic Beanstalk storage location
on Amazon S3. In the previous example, the EB CLI first looks for a saved configuration file named
savedconfig.cfg.yml in the folder .elasticbeanstalk/saved_configs/. Do not include the file
name extensions (.cfg.yml) when applying a saved configuration with --cfg.
~/workspace/my-app/
|-- .ebextensions
| `-- healthcheckurl.config
|-- .elasticbeanstalk
| |-- saved_configs
| | `-- savedconfig.cfg.yml
| `-- config.yml
|-- index.php
`-- styles.css
If the EB CLI does not find the configuration locally, it looks in the Elastic Beanstalk storage location
in Amazon S3. For details on creating, editing, and uploading saved configurations, see Saved
configurations (p. 617).
For example, the EB CLI uses the t2.micro instance type by default. To choose a different instance type,
use the --instance_type option.
622
AWS Elastic Beanstalk Developer Guide
During creation
To create an Amazon RDS database instance and attach it to your environment, use the --database
options.
If you leave out the environment name, database password, or any other parameters that are required to
create your environment, the EB CLI prompts you to enter them.
See eb create (p. 1003) for a full list of available options and usage examples.
Methods
• Using configuration files (.ebextensions) (p. 623)
• Using a saved configuration (p. 624)
• Using command line options (p. 624)
~/workspace/my-app-v1.zip
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- index.php
`-- styles.css
To upload an application source bundle and create an environment with the AWS CLI
1. If you don't already have an Elastic Beanstalk bucket in Amazon S3, create one with create-
storage-location.
623
AWS Elastic Beanstalk Developer Guide
After creation
When you specify a saved configuration, do not also specify a solution stack name. Saved configurations
already specify a solution stack and Elastic Beanstalk will return an error if you try to use both options.
Elastic Beanstalk applies option settings that you specify with the --option-settings option directly
to your environment. If the same options are specified in a saved configuration or configuration file, --
option-settings overrides those values.
When you set or change a configuration option, you can trigger a full environment
update, depending on the severity of the change. For example, changes to options in the
aws:autoscaling:launchconfiguration (p. 633), such as InstanceType, require that the
Amazon EC2 instances in your environment are reprovisioned. This triggers a rolling update (p. 453).
Other configuration changes can be applied without any interruption or reprovisioning.
You can remove option settings from an environment with EB CLI or AWS CLI commands. Removing an
option that has been set directly on an environment at an API level allows settings in configuration files,
which are otherwise masked by settings applied directly to an environment, to surface and take effect.
624
AWS Elastic Beanstalk Developer Guide
After creation
Settings in saved configurations and configuration files can be overridden by setting the same option
directly on the environment with one of the other configuration methods. However, these can only be
removed completely by applying an updated saved configuration or configuration file. When an option is
not set in a saved configuration, in a configuration file, or directly on an environment, the default value
applies, if there is one. See Precedence (p. 614) for details.
Clients
• The Elastic Beanstalk console (p. 625)
• The EB CLI (p. 627)
• The AWS CLI (p. 629)
Methods
• Using configuration files (.ebextensions) (p. 625)
• Using a saved configuration (p. 625)
• Using the Elastic Beanstalk console (p. 626)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. On the environment overview page, choose Upload and deploy.
4. Use the on-screen dialog box to upload the source bundle.
5. Choose Deploy.
6. When the deployment completes, you can choose the site URL to open your website in a new tab.
Changes made to configuration files will not override option settings in saved configurations or settings
applied directly to the environment at the API level. See Precedence (p. 614) for details.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
625
AWS Elastic Beanstalk Developer Guide
After creation
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Saved configurations.
4. Select the saved configuration you want to apply, and then choose Load.
5. Select an environment, and then choose Load.
Settings defined in a saved configuration override settings in configuration files, and are overridden by
settings configured using the environment management console.
See Saved configurations (p. 617) for details on creating saved configurations.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. Find the configuration page you want to edit:
• If you see the option you're interested in, or you know which configuration category it's in,
choose Edit in the configuration category for it.
• To look for an option, turn on Table View, and then enter search terms into the search box. As
you type, the list gets shorter and shows only options that match your search terms.
When you see the option you're looking for, choose Edit in the configuration category that
contains it.
626
AWS Elastic Beanstalk Developer Guide
After creation
Changes made to configuration options in the environment management console are applied directly to
the environment. These changes override settings for the same options in configuration files or saved
configurations. For details, see Precedence (p. 614).
For details about changing configuration options on a running environment using the Elastic Beanstalk
console, see the topics under Configuring Elastic Beanstalk environments (p. 491).
The EB CLI
You can update configuration option settings with the EB CLI by deploying source code that contains
configuration files, applying settings from a saved configuration, or modifying the environment
configuration directly with the eb config command.
Methods
• Using configuration files (.ebextensions) (p. 627)
• Using a saved configuration (p. 627)
• Using eb config (p. 628)
• Using eb setenv (p. 629)
~/workspace/my-app/
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- .elasticbeanstalk
| `-- config.yml
|-- index.php
`-- styles.css
~/workspace/my-app$ eb deploy
$ eb config --cfg v1
In this example, v1 is the name of a previously created and saved configuration file (p. 617).
627
AWS Elastic Beanstalk Developer Guide
After creation
Settings applied to an environment with this command override settings that were applied during
environment creation, and settings defined in configuration files in your application source bundle.
Using eb config
The EB CLI's eb config command lets you set and remove option settings directly on an environment by
using a text editor.
When you run eb config, the EB CLI shows settings applied to your environment from all sources,
including configuration files, saved configurations, recommended values, options set directly on the
environment, and API defaults.
Note
eb config does not show environment properties. To set environment properties that you can
read from within your application, use eb setenv (p. 629).
• Two recommended values, for IamInstanceProfile and InstanceType, applied by the EB CLI
during environment creation.
• The option EC2KeyName, set directly on the environment during creation based on repository
configuration.
• API default values for the other options.
ApplicationName: tomcat
DateUpdated: 2015-09-30 22:51:07+00:00
EnvironmentName: tomcat
SolutionStackName: 64bit Amazon Linux 2015.03 v2.0.1 running Tomcat 8 Java 8
settings:
...
aws:autoscaling:launchconfiguration:
BlockDeviceMappings: null
EC2KeyName: my-key
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
ImageId: ami-1f316660
InstanceType: t2.micro
...
~/workspace/my-app/$ eb config
2. Change any of the setting values using the default text editor.
aws:autoscaling:launchconfiguration:
BlockDeviceMappings: null
EC2KeyName: my-key
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
ImageId: ami-1f316660
InstanceType: t2.medium
Setting configuration options with eb config overrides settings from all other sources.
628
AWS Elastic Beanstalk Developer Guide
After creation
You can also remove options from your environment with eb config.
~/workspace/my-app/$ eb config
2. Replace any value shown with the string null. You can also delete the entire line containing the
option that you want to remove.
aws:autoscaling:launchconfiguration:
BlockDeviceMappings: null
EC2KeyName: my-key
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
ImageId: ami-1f316660
InstanceType: null
Removing options from your environment with eb config allows settings for the same options to surface
from configuration files in your application source bundle. See Precedence (p. 614) for details.
Using eb setenv
To set environment properties with the EB CLI, use eb setenv.
~/workspace/my-app/$ eb printenv
Environment Variables:
ENVVAR = TEST
Methods
• Using configuration files (.ebextensions) (p. 630)
• Using a saved configuration (p. 630)
• Using command line options (p. 631)
629
AWS Elastic Beanstalk Developer Guide
After creation
~/workspace/my-app-v1.zip
|-- .ebextensions
| |-- environmentvariables.config
| `-- healthcheckurl.config
|-- index.php
`-- styles.css
To upload an application source bundle and apply it to a running environment (AWS CLI)
1. If you don't already have an Elastic Beanstalk bucket in Amazon S3, create one with create-
storage-location:
The saved configuration must be in your Elastic Beanstalk bucket in a path named after your application
under resources/templates. For example, the v1 template for the my-app application in the US
West (Oregon) Region (us-west-2) for account 123456789012 is located at s3://elasticbeanstalk-
us-west-2-123456789012/resources/templates/my-app/v1
630
AWS Elastic Beanstalk Developer Guide
After creation
Elastic Beanstalk places saved configurations in this location when you create them with aws
elasticbeanstalk create-configuration-template. You can also modify saved configurations
locally and place them in this location yourself.
In this example, as-zero.json defines options that configure the environment with a minimum
and maximum of zero instances. This stops the instances in the environment without terminating the
environment.
~/ebconfigs/as-zero.json
[
{
"Namespace": "aws:autoscaling:asg",
"OptionName": "MinSize",
"Value": "0"
},
{
"Namespace": "aws:autoscaling:asg",
"OptionName": "MaxSize",
"Value": "0"
},
{
"Namespace": "aws:autoscaling:updatepolicy:rollingupdate",
"OptionName": "RollingUpdateEnabled",
"Value": "false"
}
]
Note
Setting configuration options with update-environment overrides settings from all other
sources.
You can also remove options from your environment with update-environment.
Removing options from your environment with update-environment allows settings for the same
options to surface from configuration files in your application source bundle. If an option isn't configured
using any of these methods, the API default value applies, if one exists. See Precedence (p. 614) for
details.
631
AWS Elastic Beanstalk Developer Guide
General options
aws:autoscaling:asg
Configure your environment's Auto Scaling group. For more information, see the section called “Auto
Scaling group” (p. 511).
632
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:autoscaling:asg
us-east-1c
us-east-1d
us-east-1e
eu-central-1
EnableCapacityRebalancing
Specifies whether to enable the Capacity false true
Rebalancing feature for Spot Instances
in your Auto Scaling Group. For more false
information, see Capacity Rebalancing in
the Amazon EC2 Auto Scaling User Guide.
aws:autoscaling:launchconfiguration
Configure the Amazon Elastic Compute Cloud (Amazon EC2) instances for your environment.
The instances that are used for your environment are created using either an Amazon EC2 launch
template or an Auto Scaling group launch configuration resource. The following options work with both
of these resource types.
For more information, see the section called “Amazon EC2 instances” (p. 497).
633
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:autoscaling:launchconfiguration
EC2KeyName You can use a key pair to securely log into None
your EC2 instance.
Note
If you use the Elastic
Beanstalk console to create
an environment, you can't set
this option in a configuration
file (p. 683). The console
overrides this option with a
recommended value (p. 614).
IamInstanceProfile
An instance profile enables AWS Identity None Instance profile
and Access Management (IAM) users name or ARN.
and AWS services to access temporary
security credentials to make AWS API
calls. Specify the instance profile's name
or its ARN.
Examples:
• aws-elasticbeanstalk-ec2-role
• arn:aws:iam::123456789012:instance-
profile/aws-elasticbeanstalk-
ec2-role
Note
If you use the Elastic Beanstalk
console or EB CLI to create
an environment, you can't set
this option in a configuration
file (p. 683). The console and
EB CLI override this option with a
recommended value (p. 614).
Example: ami-1f316660
The instance type that's used to run Varies by account and One EC2 instance
your application in an Elastic Beanstalk Region. type.
InstanceType environment.
Varies by account,
Important Region, and
The InstanceType option Availability Zone.
is obsolete. It's replaced by
634
AWS Elastic Beanstalk Developer Guide
General options
Note
If you use the Elastic Beanstalk
console or EB CLI to create
an environment, you can't set
this option in a configuration
file (p. 683). The console and
EB CLI override this option with a
recommended value (p. 614).
635
AWS Elastic Beanstalk Developer Guide
General options
MonitoringInterval
The interval (in minutes) that you want 5 minute 1 minute
Amazon CloudWatch metrics to be
returned at. 5 minute
636
AWS Elastic Beanstalk Developer Guide
General options
protocol
637
AWS Elastic Beanstalk Developer Guide
General options
BlockDeviceMappings
Attach additional Amazon EBS volumes None
or instance store volumes on all of the
instances in the Auto Scaling group.
• snapshot ID
• size, in GB
• delete on terminate (true or false)
• storage type (only for gp3, gp2,
standard, st1, sc1, or io1)
• IOPS (only for gp3 or io1)
• throughput (only for gp3)
/dev/sdj=:100:true:gp2,/
dev/sdh=snap-51eef269,/dev/
sdi=:20:true:io1:2000,/dev/
sdb=ephemeral0
RootVolumeType
Volume type (magnetic, general purpose Varies by platform. standard for
SSD or provisioned IOPS SSD) to use for magnetic storage.
the root Amazon EBS volume attached to
the EC2 instances for your environment. gp2 or gp3 for
general purpose
SSD.
io1 for
provisioned IOPS
SSD.
RootVolumeSizeThe storage capacity of the root Amazon Varies per platform 10 to 16384
EBS volume in whole GB. for magnetic storage GB for general
and general purpose purpose and
Required if you set RootVolumeType to SSD. provisioned IOPS
provisioned IOPS SSD. SSD.
None for provisioned
For example, "64". IOPS SSD. 8 to 1024 GB for
magnetic.
638
AWS Elastic Beanstalk Developer Guide
General options
RootVolumeIOPS
The desired input/output operations per None 100 to 20000 for
second (IOPS) for a provisioned IOPS SSD io1 provisioned
root volume or for a general purpose gp3 IOPS SSD root
SSD root volume. volumes.
RootVolumeThroughput
The desired throughput of mebibytes None 125 to 1000
per second (MiB/s) to provision for the
Amazon EBS root volume attached to
your environment's EC2 instance.
Note
This option is only applicable to
gp3 storage types.
aws:autoscaling:scheduledaction
Configure scheduled actions (p. 522) for your environment's Auto Scaling group. For each action, specify
a resource_name in addition to the option name, namespace, and value for each setting. See The
aws:autoscaling:scheduledaction namespace (p. 523) for examples.
Namespace: aws:autoscaling:scheduledaction
EndTime A date and time in the future (in the None A ISO-8601
UTC/GMT time zone) when you want timestamp unique
the scheduled scaling action to stop across all scheduled
repeating. If you don't specify an scaling actions.
EndTime, the action recurs according to
the Recurrence expression.
Example: 2015-04-28T04:07:2Z
639
AWS Elastic Beanstalk Developer Guide
General options
DesiredCapacity Set the initial desired capacity for the None 0 to 10000
Auto Scaling group. After the scheduled
action is applied, triggers adjust the
desired capacity based on their settings.
Recurrence The frequency that you want the None A Cron expression.
scheduled action to occur at. If you don't
specify a recurrence, then the scaling
action occurs only once, as specified by
the StartTime.
aws:autoscaling:trigger
Configure scaling triggers for your environment's Auto Scaling group.
Note
Three options in this namespace determine how long the metric for a trigger can remain beyond
its defined limits before the trigger initates. These options are related as follows:
BreachDuration = Period * EvaluationPeriods
The default values for these options (5, 5, and 1, respectively) satisfy this equation. If you
specify inconsistent values, Elastic Beanstalk might modify one of the values so that the
equation is still satisfied.
Namespace: aws:autoscaling:trigger
LowerBreachScaleIncrement
How many Amazon EC2 instances to -1
remove when performing a scaling
activity.
MeasureName The metric that's used for your Auto NetworkOut CPUUtilization
Scaling trigger.
NetworkIn
Note
HealthyHostCount, NetworkOut
UnhealthyHostCount
and TargetResponseTime DiskWriteOps
are only applicable for
environments with a dedicated DiskReadBytes
load balancer. These aren't valid
metric values for environments DiskReadOps
640
AWS Elastic Beanstalk Developer Guide
General options
HealthyHostCount
UnhealthyHostCount
TargetResponseTime
Sum
Average
Bytes
Bits
Count
Bytes/Second
Bits/Second
Count/Second
None
UpperBreachScaleIncrement
Specifies how many Amazon EC2 1
instances to add when performing a
scaling activity.
641
AWS Elastic Beanstalk Developer Guide
General options
aws:autoscaling:updatepolicy:rollingupdate
Configure rolling updates your environment's Auto Scaling group.
Namespace: aws:autoscaling:updatepolicy:rollingupdate
642
AWS Elastic Beanstalk Developer Guide
General options
Time-based rolling
updates apply a
PauseTime between
batches. Health-based
rolling updates wait for
new instances to pass
health checks before
moving on to the next
batch. Immutable
updates (p. 456) launch
a full set of instances
in a new Auto Scaling
group.
Note
If you use
the Elastic
Beanstalk
console or
EB CLI to
create an
environment,
you can't set
this option in a
configuration
file (p. 683).
The console
and EB CLI
override this
option with a
recommended
value (p. 614).
643
AWS Elastic Beanstalk Developer Guide
General options
aws:ec2:instances
Configure your environment's instances, including Spot options. This namespace complements
aws:autoscaling:launchconfiguration (p. 633) and aws:autoscaling:asg (p. 632).
For more information, see the section called “Auto Scaling group” (p. 511).
Namespace: aws:ec2:instances
644
AWS Elastic Beanstalk Developer Guide
General options
Note
Some older AWS accounts might
provide Elastic Beanstalk with
default instance types that
don't support Spot Instances
(for example, t1.micro). If
you activate Spot Instance
requests and you get an error
about an instance type that
doesn’t support Spot, be sure
to configure instance types that
support Spot. To choose Spot
Instance types, use the Spot
Instance Advisor.
645
AWS Elastic Beanstalk Developer Guide
General options
SpotFleetOnDemandBase
The minimum number of On-Demand 0 0 to MaxSize option in
Instances that your Auto Scaling group aws:autoscaling:asg (p. 632)
provisions before considering Spot namespace
Instances as your environment scales up.
SpotFleetOnDemandAboveBasePercentage
The percentage of On-Demand Instances 0 0 to 100
as part of additional capacity that your for a
Auto Scaling group provisions beyond single-
the SpotOnDemandBase instances. instance
environment
This option is relevant only when
EnableSpot is true. 70
for a
load-
balanced
environment
SpotMaxPrice The maximum price per unit hour, in On- 0.001 to 20.0
USD, that you're willing to pay for a Demand
Spot Instance. For recommendations price, null
about maximum price options for Spot for
Instances, see Spot Instance pricing each
history in the Amazon EC2 User Guide for instance
Linux Instances. type.
The
This option is relevant only when option's
EnableSpot is true. value
in this
case
is
null.
646
AWS Elastic Beanstalk Developer Guide
General options
aws:ec2:vpc
Configure your environment to launch resources in a custom Amazon Virtual Private Cloud (Amazon
VPC). If you don't configure settings in this namespace, Elastic Beanstalk launches resources in the
default VPC.
Namespace: aws:ec2:vpc
Subnets The IDs of the Auto Scaling group subnet or subnets. If None
you have multiple subnets, specify the value as a single
comma-separated string of subnet IDs (for example,
"subnet-11111111,subnet-22222222").
ELBSubnets The IDs of the subnet or subnets for the elastic load None
balancer. If you have multiple subnets, specify the value
as a single comma-separated string of subnet IDs (for
example, "subnet-11111111,subnet-22222222").
AssociatePublicIpAddress
Specifies whether to launch instances with public IP None true
addresses in your Amazon VPC. Instances with public IP
addresses don't require a NAT device to communicate false
with the Internet. You must set the value to true if you
want to include your load balancer and instances in a
single public subnet.
aws:elasticbeanstalk:application
Configure a health check path for your application. For more information, see Basic health
reporting (p. 773).
647
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elasticbeanstalk:application
Application The path where health check requests None Valid values include:
Healthcheck URL are sent to. If this path isn't set, the
load balancer attempts to make a TCP / (HTTP GET to root path)
connection on port 80 to verify the
health status of your application. Set to /health
a path starting with / to send an HTTP
HTTPS:443/
GET request to that path. You can also
include a protocol (HTTP, HTTPS, TCP, or HTTPS:443/health
SSL) and port before the path to check
HTTPS connectivity or use a non-default
port.
Note
If you use the Elastic
Beanstalk console to create
an environment, you can't set
this option in a configuration
file (p. 683). The console
overrides this option with a
recommended value (p. 614).
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must
remove these settings if you want to use configuration files to configure the same. See Recommended
values (p. 614) for details.
aws:elasticbeanstalk:application:environment
Configure environment properties for your application.
Namespace: aws:elasticbeanstalk:application:environment
See Environment properties and other software settings (p. 590) for more information.
aws:elasticbeanstalk:cloudwatch:logs
Configure instance log streaming for your application.
Namespace: aws:elasticbeanstalk:cloudwatch:logs
648
AWS Elastic Beanstalk Developer Guide
General options
DeleteOnTerminate
Specifies whether to delete the log groups when the false true
environment is terminated. If false, the logs are kept
RetentionInDays days. false
aws:elasticbeanstalk:cloudwatch:logs:health
Configure environment health log streaming for your application.
Namespace: aws:elasticbeanstalk:cloudwatch:logs:health
HealthStreamingEnabled
For environments with enhanced health reporting false true
enabled, specifies whether to create a group in
CloudWatch Logs for environment health and archive false
Elastic Beanstalk environment health data. For
information about enabling enhanced health, see
aws:elasticbeanstalk:healthreporting:system (p. 656).
DeleteOnTerminate
Specifies whether to delete the log group when the false true
environment is terminated. If false, the health data is
kept RetentionInDays days. false
aws:elasticbeanstalk:command
Configure the deployment policy for your application code. For more information, see the section called
“Deployment options” (p. 444).
649
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elasticbeanstalk:command
650
AWS Elastic Beanstalk Developer Guide
General options
aws:elasticbeanstalk:environment
Configure your environment's architecture and service role.
Namespace: aws:elasticbeanstalk:environment
ServiceRole The name of an IAM role that Elastic Beanstalk None IAM role name,
uses to manage resources for the environment. path/name, or
Specify a role name (optionally prefixed with a ARN
custom path) or its ARN.
Examples:
• aws-elasticbeanstalk-service-role
• custom-path/custom-role
• arn:aws:iam::123456789012:role/
aws-elasticbeanstalk-service-role
Note
If you use the Elastic Beanstalk
console or EB CLI to create an
environment, you can't set this option
in a configuration file (p. 683). The
console and EB CLI override this option
with a recommended value (p. 614).
network
LoadBalancerIsShared
Specifies whether the environment's load false true
balancer is dedicated or shared. This option can
only be set for an Application Load Balancer. false
It can't be changed after the environment is
created.
aws:elasticbeanstalk:environment:process:default
Configure your environment's default process.
651
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elasticbeanstalk:environment:process:default
This option is
only applicable to
environments with
an application load
balancer.
652
AWS Elastic Beanstalk Developer Guide
General options
StickinessLBCookieDuration
The lifetime, in seconds, 86400 (one day) 1 to 604800
of the sticky session
cookie.
This option is
only applicable to
environments with
an application load
balancer.
This option is
only applicable to
environments with
an application load
balancer.
UnhealthyThresholdCountThe number 5 2 to 10
of consecutive
unsuccessful requests
before Elastic Load
Balancing changes the
instance health status.
aws:elasticbeanstalk:environment:process:process_name
Configure additional processes for your environment.
Namespace: aws:elasticbeanstalk:environment:process:process_name
653
AWS Elastic Beanstalk Developer Guide
General options
This option is
only applicable to
environments with
an application load
balancer.
654
AWS Elastic Beanstalk Developer Guide
General options
StickinessLBCookieDuration
The lifetime, in seconds, 86400 (one day) 1 to 604800
of the sticky session
cookie.
This option is
only applicable to
environments with
an application load
balancer.
This option is
only applicable to
environments with
an application load
balancer.
UnhealthyThresholdCountThe number 5 2 to 10
of consecutive
unsuccessful requests
before Elastic Load
Balancing changes the
instance health status.
aws:elasticbeanstalk:environment:proxy:staticfiles
You can use the following namespace to configure the proxy server to serve static files. When the proxy
server receives a request for a file under the specified path, it serves the file directly instead of routing
the request to your application. This reduces the number of requests that your application has to process.
Map a path served by the proxy server to a folder in your source code that contains static assets. Each
option that you define in this namespace maps a different path.
Note
This namespace applies to platform branches based on Amazon Linux 2. If your environment
uses a platform version based on Amazon Linux AMI (preceding Amazon Linux 2), refer to the
section called “Platform specific options” (p. 674) for platform-specific static file namespaces.
Namespace: aws:elasticbeanstalk:environment:proxy:staticfiles
Name Value
The path where the proxy server serves the files. The name of the folder containing the files.
Start the value with /.
655
AWS Elastic Beanstalk Developer Guide
General options
Name Value
For example, specify /images to serve files For example, specify staticimages to serve files
at subdomain.eleasticbeanstalk.com/ from a folder named staticimages at the top
images. level of your source bundle.
aws:elasticbeanstalk:healthreporting:system
Configure enhanced health reporting for your environment.
Namespace: aws:elasticbeanstalk:healthreporting:system
SystemType The health reporting system (basic (p. 773) or basic basic
enhanced (p. 776)). Enhanced health reporting
requires a service role (p. 20) and a version 2 or enhanced
newer platform version (p. 29).
Note
If you use the Elastic Beanstalk console
or EB CLI to create an environment, you
can't set this option in a configuration
file (p. 683). The console and EB CLI
override this option with a recommended
value (p. 614).
EnhancedHealthAuthEnabled
Enables authorization for the internal API that true true
Elastic Beanstalk uses to communicate enhanced
health information from your environment false
instances to the Elastic Beanstalk service.
HealthCheckSuccessThreshold
Lowers the threshold for instances to pass health Ok Ok
checks.
Warning
Note
If you use the Elastic Beanstalk console to Degraded
create an environment, you can't set this
option in a configuration file (p. 683). Severe
The console overrides this option with a
recommended value (p. 614).
aws:elasticbeanstalk:hostmanager
Configure the EC2 instances in your environment to upload rotated logs to Amazon S3.
656
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elasticbeanstalk:hostmanager
LogPublicationControl Copy the log files of the Amazon EC2 instances for false true
your application to the Amazon S3 bucket that's
associated with your application. false
aws:elasticbeanstalk:managedactions
Configure managed platform updates for your environment.
Namespace: aws:elasticbeanstalk:managedactions
format.
ServiceRoleForManagedUpdates
The name of an IAM role that None Same as
Elastic Beanstalk uses to perform ServiceRole
managed platform updates for
your environment. or
aws:elasticbeanstalk:managedactions:platformupdate
Configure managed platform updates for your environment.
657
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elasticbeanstalk:managedactions:platformupdate
aws:elasticbeanstalk:monitoring
Configure your environment to terminate EC2 instances that fail health checks.
Namespace: aws:elasticbeanstalk:monitoring
aws:elasticbeanstalk:sns:topics
Configure notifications for your environment.
Namespace: aws:elasticbeanstalk:sns:topics
658
AWS Elastic Beanstalk Developer Guide
General options
email-json
sqs
aws:elasticbeanstalk:sqsd
Configure the Amazon SQS queue for a worker environment.
Namespace: aws:elasticbeanstalk:sqsd
WorkerQueueURL The URL of the queue that the automaticallyIf you don't specify a value,
daemon in the worker environment generated then Elastic Beanstalk
tier reads messages from. automatically creates a
queue.
Note
When you don't specify a
value, the queue that Elastic
Beanstalk automatically
creates is a standard
Amazon SQS queue. When
you provide a value, you can
provide the URL of either a
standard or a FIFO Amazon
SQS queue. Be aware that if
you provide a FIFO queue,
periodic tasks (p. 485) aren't
supported.
659
AWS Elastic Beanstalk Developer Guide
General options
application/xml
text/plain
ErrorVisibilityTimeout
The amount of time, in seconds, 2 seconds 0 to 43200 seconds
that elapses before Elastic Beanstalk
returns a message to the Amazon
SQS queue after a processing
attempt fails with an explicit error.
660
AWS Elastic Beanstalk Developer Guide
General options
aws:elasticbeanstalk:trafficsplitting
Configure traffic-splitting deployments for your environment.
This namespace applies when you set the DeploymentPolicy option of the
aws:elasticbeanstalk:command (p. 649) namespace to TrafficSplitting. For more information
about deployment policies, see the section called “Deployment options” (p. 444).
Namespace: aws:elasticbeanstalk:trafficsplitting
aws:elasticbeanstalk:xray
Run the AWS X-Ray daemon to relay trace information from your X-Ray integrated (p. 595) application.
Namespace: aws:elasticbeanstalk:xray
aws:elb:healthcheck
Configure healthchecks for a Classic Load Balancer.
661
AWS Elastic Beanstalk Developer Guide
General options
Namespace: aws:elb:healthcheck
Interval The interval that Elastic Load Balancing checks the health 10 5 to 300
of your application's Amazon EC2 instances at.
UnhealthyThreshold
The number of consecutive unsuccessful requests before 5 2 to 10
Elastic Load Balancing changes the instance health status.
(deprecated) The destination on a backend instance that health checks TCP:80 Target in
Target are sent to. Use Application Healthcheck URL in the format
the aws:elasticbeanstalk:application (p. 647) PROTOCOL:PORT/
namespace instead. PATH
aws:elb:loadbalancer
Configure your environment's Classic Load Balancer.
Several of the options in this namespace are no longer supported in favor of listener-specific options in
the aws:elb:listener (p. 663) namespace. With these options that aren't supported anymore, you can
only configure two listeners (one secure and one unsecure) on standard ports.
Namespace: aws:elb:loadbalancer
SecurityGroups Assign one or more security groups that you None One or more
created to the load balancer. security
group IDs.
662
AWS Elastic Beanstalk Developer Guide
General options
(deprecated) The port to listen on for the secure listener. OFF OFF
LoadBalancerHTTPSPort
443
8443
aws:elb:listener
Configure the default listener (port 80) on a Classic Load Balancer.
Namespace: aws:elb:listener
InstanceProtocol The protocol that this listener uses to HTTP when HTTP or
communicate with the EC2 instances. HTTPS when
ListenerProtocol
is HTTP ListenerProtocol
It must be at the same internet protocol layer is HTTP or
as the ListenerProtocol. It also must have TCP when HTTPS
the same security level as any other listener ListenerProtocol
using the same InstancePort as this listener. is TCP TCP or
SSL when
For example, if ListenerProtocol is ListenerProtocol
HTTPS (application layer, using a secure is TCP or SSL
connection), you can set InstanceProtocol
to HTTP (also at the application layer, using
an insecure connection). If, in addition, you
set InstancePort to 80, you must set
InstanceProtocol to HTTP in all other
listeners with InstancePort set to 80.
663
AWS Elastic Beanstalk Developer Guide
General options
aws:elb:listener:listener_port
Configure additional listeners on a Classic Load Balancer.
Namespace: aws:elb:listener:listener_port
InstancePort The port that this listener uses to The same as 1 to 65535
communicate with the EC2 instances. listener_port.
InstanceProtocol The protocol that this listener uses to HTTP when HTTP or
communicate with the EC2 instances. HTTPS when
ListenerProtocol
is HTTP or ListenerProtocol
It must be at the same internet protocol layer HTTPS is HTTP or
as the ListenerProtocol. It also must have HTTPS
the same security level as any other listener TCP when
using the same InstancePort as this listener. ListenerProtocol
TCP or
is TCP or SSL when
For example, if ListenerProtocol is SSL ListenerProtocol
HTTPS (application layer, using a secure is TCP or SSL
connection), you can set InstanceProtocol
to HTTP (also at the application layer, using
an insecure connection). If, in addition, you
set InstancePort to 80, you must set
InstanceProtocol to HTTP in all other
listeners with InstancePort set to 80.
664
AWS Elastic Beanstalk Developer Guide
General options
aws:elb:policies
Modify the default stickiness and global load balancer policies for a Classic Load Balancer.
Namespace: aws:elb:policies
ConnectionDrainingEnabled
Specifies whether the load balancer false true
maintains existing connections to instances
that have become unhealthy or deregistered false
to complete in-progress requests.
Note
If you use the Elastic Beanstalk
console or EB CLI to create
an environment, you can't set
this option in a configuration
file (p. 683). The console and
EB CLI override this option with a
recommended value (p. 614).
ConnectionDrainingTimeout
The maximum number of seconds that the 20 1 to 3600
load balancer maintains existing connections
to an instance during connection draining
before forcibly closing the connections.
Note
If you use the Elastic Beanstalk
console to create an environment,
you can't set this option in a
configuration file (p. 683). The
console overrides this option with a
recommended value (p. 614).
ConnectionSettingIdleTimeout
The amount of time, in seconds, that the 60 1 to 3600
load balancer waits for any data to be sent
or received over the connection. If no data
has been sent or received after this time
period elapses, the load balancer closes the
connection.
Stickiness Policy Binds a user's session to a specific server false true false
instance so that all requests coming from
the user during the session are sent to the
same server instance. Uses the default policy
(AWSEB-ELB-StickinessPolicy) .
665
AWS Elastic Beanstalk Developer Guide
General options
aws:elb:policies:policy_name
Create additional load balancer policies for a Classic Load Balancer.
Namespace: aws:elb:policies:policy_name
666
AWS Elastic Beanstalk Developer Guide
General options
Stickiness Policy Binds a user's session to a specific server false true false
instance so that all requests coming from the
user during the session are sent to the same
server instance.
aws:elbv2:listener:default
Configure the default listener (port 80) on an Application Load Balancer or a Network Load Balancer.
This namespace doesn't apply to an environment that uses a shared load balancer. Shared load balancers
don't have a default listener.
Namespace: aws:elbv2:listener:default
Protocol The protocol of traffic With application load With application load
to process. balancer: HTTP balancer: HTTP, HTTPS
This option is
only applicable to
environments with
an Application Load
Balancer.
This option is
only applicable to
environments with
an Application Load
Balancer.
667
AWS Elastic Beanstalk Developer Guide
General options
SSLPolicy Specify a security policy None (ELB default) The name of a load
to apply to the listener. balancer security policy.
This option is
only applicable to
environments with
an Application Load
Balancer.
aws:elbv2:listener:listener_port
Configure additional listeners on an Application Load Balancer or a Network Load Balancer.
Note
For a shared Application Load Balancer, you can specify only the Rule option. The other options
aren't applicable to shared load balancers.
Namespace: aws:elbv2:listener:listener_port
Protocol The protocol of traffic With application load With application load
to process. balancer: HTTP balancer: HTTP, HTTPS
If your environment
uses a shared
Application Load
Balancer, and you don't
specify this option for
any listener, Elastic
Beanstalk automatically
associates the default
rule with a port 80
listener.
668
AWS Elastic Beanstalk Developer Guide
General options
This option is
only applicable to
environments with
an Application Load
Balancer.
SSLPolicy Specify a security policy None (ELB default) The name of a load
to apply to the listener. balancer security policy.
This option is
only applicable to
environments with
an Application Load
Balancer.
aws:elbv2:listenerrule:rule_name
Define listener rules for an Application Load Balancer. If a request matches the host names or paths in
a rule, the load balancer forwards it to the specified process. To use a rule, add it to a listener with the
Rules option in the aws:elbv2:listener:listener_port (p. 668) namespace.
Note
This namespace isn't applicable to environments with a network load balancer.
Namespace: aws:elbv2:listenerrule:rule_name
HostHeadersA list of host names to match. For example, Dedicated Each name can contain
my.example.com. load balancer: up to 128 characters.
None A pattern can include
both uppercase and
Shared load lowercase letters,
balancer: The numbers, hyphens
environment's (–), and up to three
CNAME wildcard characters
(* matches zero or
more characters; ?
matches exactly one
character). You can list
more than one name,
each separated by a
comma. Application
Load Balancer supports
up to five combined
HostHeader and
PathPattern rules.
669
AWS Elastic Beanstalk Developer Guide
General options
PathPatternsThe path patterns to match (for example, / None Each pattern can
img/*). contain up to 128
characters. A pattern
This option is only applicable to environments can include uppercase
with an application load balancer. and lowercase letters,
numbers, hyphens
(–), and up to three
wildcard characters (*
matches zero or more
characters; ? matches
exactly one character).
You can add multiple
comma-separated path
patterns. Application
Load Balancer supports
up to five combined
HostHeader and
PathPattern rules.
Process The name of the process (p. 651) to forward default A process name.
traffic when this rule matches the request.
aws:elbv2:loadbalancer
Configure an Application Load Balancer.
For a shared load balancer, only the SharedLoadBalancer and SecurityGroups options are valid.
Note
This namespace isn't applicable to environments with a Network Load Balancer.
Namespace: aws:elbv2:loadbalancer
670
AWS Elastic Beanstalk Developer Guide
General options
false
671
AWS Elastic Beanstalk Developer Guide
General options
SharedLoadBalancer The Amazon Resource Name (ARN) None ARN of a valid load
of a shared load balancer. This option balancer that meets all
is relevant only to an Application of the criteria described
Load Balancer. It's required when here.
the LoadBalancerIsShared
option of the
aws:elasticbeanstalk:environment (p. 651)
namespace is set to true. You can't
change the shared load balancer ARN
after the environment is created.
Example:
arn:aws:elasticloadbalancing:us-
east-2:123456789012:loadbalancer/
app/
FrontEndLB/0dbf78d8ad96abbc
aws:rds:dbinstance
Configure an attached Amazon RDS DB instance.
Namespace: aws:rds:dbinstance
DBAllocatedStorage
The allocated database storage size, specified MySQL: 5 MySQL: 5-1024
in gigabytes.
Oracle: 10 Oracle: 10-1024
sqlserver-ex: 30
sqlserver-web:
30
672
AWS Elastic Beanstalk Developer Guide
General options
DBEngine The name of the database engine to use for mysql mysql
this instance.
oracle-se1
sqlserver-ex
sqlserver-web
sqlserver-se
postgres
DBSnapshotIdentifier
The identifier for the DB snapshot to restore None
from.
673
AWS Elastic Beanstalk Developer Guide
Platform specific options
HasCoupledDatabase
Specifies whether a DB instance is coupled to false true
your environment. If toggled to true, Elastic
Beanstalk creates a new DB instance coupled false
to your environment. If toggled to false,
Elastic Beanstalk initiates decoupling of the
DB instance from your environment.
Platforms
• Docker platform options (p. 675)
• Go platform options (p. 675)
674
AWS Elastic Beanstalk Developer Guide
Platform specific options
Namespace: aws:elasticbeanstalk:environment:proxy
Go platform options
Amazon Linux AMI (pre-Amazon Linux 2) platform options
Namespace: aws:elasticbeanstalk:container:golang:staticfiles
You can use the following namespace to configure the proxy server to serve static files. When the proxy
server receives a request for a file under the specified path, it serves the file directly instead of routing
the request to your application. This reduces the number of requests that your application has to process.
Map a path served by the proxy server to a folder in your source code that contains static assets. Each
option that you define in this namespace maps a different path.
Name Value
Path where the proxy server will serve the files. Name of the folder containing the files.
675
AWS Elastic Beanstalk Developer Guide
Platform specific options
You can use the following namespace to configure the proxy server to serve static files. When the proxy
server receives a request for a file under the specified path, it serves the file directly instead of routing
the request to your application. This reduces the number of requests that your application has to process.
Map a path served by the proxy server to a folder in your source code that contains static assets. Each
option that you define in this namespace maps a different path.
Name Value
Path where the proxy server will serve the files. Name of the folder containing the files.
See Environment properties and other software settings (p. 590) for more information.
Namespace: aws:elasticbeanstalk:container:tomcat:jvmoptions
XX:MaxPermSize Section of the JVM heap that is used to store 64m n/a
class definitions and associated metadata.
Note
This option only applies to Java versions
earlier than Java 8, and isn't supported
on Elastic Beanstalk Tomcat platforms
based on Amazon Linux 2.
676
AWS Elastic Beanstalk Developer Guide
Platform specific options
Namespace: aws:elasticbeanstalk:environment:proxy
GzipCompression
Set to false to disable response compression. true true
none
Target Runtime Choose the version of .NET Framework for your 4.0 2.0
application.
4.0
677
AWS Elastic Beanstalk Developer Guide
Platform specific options
GzipCompression
Specifies if gzip compression is enabled. false true
If ProxyServer is set to none, then gzip
compression is disabled. false
678
AWS Elastic Beanstalk Developer Guide
Platform specific options
Namespace: aws:elasticbeanstalk:container:nodejs:staticfiles
You can use the following namespace to configure the proxy server to serve static files. When the proxy
server receives a request for a file under the specified path, it serves the file directly instead of routing
the request to your application. This reduces the number of requests that your application has to process.
Map a path served by the proxy server to a folder in your source code that contains static assets. Each
option that you define in this namespace maps a different path.
Note
Static file settings do not apply if
aws:elasticbeanstalk:container:nodejs::ProxyFiles is set to none.
Name Value
Path where the proxy server will serve the files. Name of the folder containing the files.
document_root Specify the child directory of your project / A blank string is treated
that is treated as the public-facing web root. as /, or specify a string
starting with /
zlib.output_compression
Specifies whether or not PHP should use Off On
compression for output.
Off
true
false
true
false
679
AWS Elastic Beanstalk Developer Guide
Platform specific options
Namespace: aws:elasticbeanstalk:environment:proxy
Note
For more information about the PHP platform, see Using the Elastic Beanstalk PHP
platform (p. 276).
See Environment properties and other software settings (p. 590) for more information.
Namespace: aws:elasticbeanstalk:container:python
WSGIPath The file that contains the WSGI application. This file must On Amazon n/a
have an application callable. Linux 2
Python
platform
versions:
application
On Amazon
Linux AMI
Python
platform
versions:
application.py
680
AWS Elastic Beanstalk Developer Guide
Platform specific options
Namespace: aws:elasticbeanstalk:environment:proxy
You can use the following namespace to configure the proxy server to serve static files. When the proxy
server receives a request for a file under the specified path, it serves the file directly instead of routing
the request to your application. This reduces the number of requests that your application has to process.
Map a path served by the proxy server to a folder in your source code that contains static assets. Each
option that you define in this namespace maps a different path.
By default, the proxy server in a Python environment serves any files in a folder named static at the /
static path.
Namespace: aws:elasticbeanstalk:container:python:staticfiles
Name Value
Path where the proxy server will serve the files. Name of the folder containing the files.
RAILS_SKIP_ASSET_COMPILATION
Specifies whether the container should false true
run `rake assets:precompile` on
behalf of the users' applications; or whether false
681
AWS Elastic Beanstalk Developer Guide
Custom options
See Environment properties and other software settings (p. 590) for more information.
Custom options
Use the aws:elasticbeanstalk:customoption namespace to define options and values that can
be read in Resources blocks in other configuration files. Use custom options to collect user specified
settings in a single configuration file.
For example, you may have a complex configuration file that defines a resource that can be configured
by the user launching the environment. If you use Fn::GetOptionSetting to retrieve the value of a
custom option, you can put the definition of that option in a different configuration file, where it is more
easily discovered and modified by the user.
Also, because they are configuration options, custom options can be set at the API level to override
values set in a configuration file. See Precedence (p. 614) for more information.
option_settings:
aws:elasticbeanstalk:customoption:
option name: option value
For example, the following configuration file creates an option named ELBAlarmEmail and sets the
value to someone@example.com:
option_settings:
aws:elasticbeanstalk:customoption:
ELBAlarmEmail: someone@example.com
Elsewhere, a configuration file defines an SNS topic that reads the option with Fn::GetOptionSetting
to populate the value of the Endpoint attribute:
Resources:
MySNSTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint:
Fn::GetOptionSetting:
OptionName: ELBAlarmEmail
DefaultValue: nobody@example.com
Protocol: email
682
AWS Elastic Beanstalk Developer Guide
.Ebextensions
You can find more example snippets using Fn::GetOptionSetting at Adding and customizing Elastic
Beanstalk environment resources (p. 703).
Example .ebextensions/network-load-balancer.config
This example makes a simple configuration change. It modifies a configuration option to set the type of
your environment's load balancer to Network Load Balancer.
option_settings:
aws:elasticbeanstalk:environment:
LoadBalancerType: network
We recommend using YAML for your configuration files, because it's more readable than JSON. YAML
supports comments, multi-line commands, several alternatives for using quotes, and more. However, you
can make any configuration change in Elastic Beanstalk configuration files identically using either YAML
or JSON.
Tip
When you are developing or testing new configuration files, launch a clean environment running
the default application and deploy to that. Poorly formatted configuration files will cause a new
environment launch to fail unrecoverably.
The option_settings section of a configuration file defines values for configuration options (p. 613).
Configuration options let you configure your Elastic Beanstalk environment, the AWS resources in it,
and the software that runs your application. Configuration files are only one of several ways to set
configuration options.
The Resources section (p. 703) lets you further customize the resources in your application's
environment, and define additional AWS resources beyond the functionality provided by configuration
options. You can add and configure any resources supported by AWS CloudFormation, which Elastic
Beanstalk uses to create environments.
The other sections of a configuration file (packages, sources, files, users, groups, commands,
container_commands, and services) let you configure the EC2 instances that are launched in your
environment. Whenever a server is launched in your environment, Elastic Beanstalk runs the operations
defined in these sections to prepare the operating system and storage system for your application.
For examples of commonly used .ebextensions, see the Elastic Beanstalk Configuration Files Repository.
Requirements
• Location – Place all of your configuration files in a single folder, named .ebextensions, in the
root of your source bundle. Folders starting with a dot can be hidden by file browsers, so make
sure that the folder is added when you create your source bundle. See Create an application source
bundle (p. 385) for instructions.
• Naming – Configuration files must have the .config file extension.
• Formatting – Configuration files must conform to YAML or JSON specifications.
683
AWS Elastic Beanstalk Developer Guide
Option settings
When using YAML, always use spaces to indent keys at different nesting levels. For more information
about YAML, see YAML Ain't Markup Language (YAML™) Version 1.1.
• Uniqueness – Use each key only once in each configuration file.
Warning
If you use a key (for example, option_settings) twice in the same configuration file, one of
the sections will be dropped. Combine duplicate sections into a single section, or place them
in separate configuration files.
The process for deploying varies slightly depending on the client that you use to manage your
environments. See the following sections for details:
Topics
• Option settings (p. 684)
• Customizing software on Linux servers (p. 685)
• Customizing software on Windows servers (p. 697)
• Adding and customizing Elastic Beanstalk environment resources (p. 703)
Option settings
You can use the option_settings key to modify the Elastic Beanstalk configuration and define
variables that can be retrieved from your application using environment variables. Some namespaces
allow you to extend the number of parameters, and specify the parameter names. For a list of
namespaces and configuration options, see Configuration options (p. 613).
Option settings can also be applied directly to an environment during environment creation or an
environment update. Settings applied directly to the environment override the settings for the same
options in configuration files. If you remove settings from an environment's configuration, settings in
configuration files will take effect. See Precedence (p. 614) for details.
Syntax
The standard syntax for option settings is an array of objects, each having a namespace, option_name
and value key.
option_settings:
- namespace: namespace
option_name: option name
value: option value
- namespace: namespace
option_name: option name
value: option value
The namespace key is optional. If you do not specify a namespace, the default used is
aws:elasticbeanstalk:application:environment:
option_settings:
- option_name: option name
value: option value
- option_name: option name
684
AWS Elastic Beanstalk Developer Guide
Linux server
Elastic Beanstalk also supports a shorthand syntax for option settings that lets you specify options as
key-value pairs underneath the namespace:
option_settings:
namespace:
option name: option value
option name: option value
Examples
The following examples set a Tomcat platform-specific option in the
aws:elasticbeanstalk:container:tomcat:jvmoptions namespace and an environment
property named MYPARAMETER.
Example .ebextensions/options.config
option_settings:
- namespace: aws:elasticbeanstalk:container:tomcat:jvmoptions
option_name: Xmx
value: 256m
- option_name: MYPARAMETER
value: parametervalue
In shorthand format:
Example .ebextensions/options.config
option_settings:
aws:elasticbeanstalk:container:tomcat:jvmoptions:
Xmx: 256m
aws:elasticbeanstalk:application:environment:
MYPARAMETER: parametervalue
In JSON:
Example .ebextensions/options.config
{
"option_settings": [
{
"namespace": "aws:elasticbeanstalk:container:tomcat:jvmoptions",
"option_name": "Xmx",
"value": "256m"
},
{
"option_name": "MYPARAMETER",
"value": "parametervalue"
}
]
}
685
AWS Elastic Beanstalk Developer Guide
Linux server
or directly create files on your environment instances. These files might be either dependencies required
by the application—for example, additional packages from the yum repository—or they might be
configuration files such as a replacement for a proxy configuration file to override specific settings that
are defaulted by Elastic Beanstalk.
This section describes the type of information you can include in a configuration file to customize
the software on your EC2 instances running Linux. For general information about customizing
and configuring your Elastic Beanstalk environments, see Configuring Elastic Beanstalk
environments (p. 491). For information about customizing software on your EC2 instances running
Windows, see Customizing software on Windows servers (p. 697).
Notes
Configuration files support the following keys that affect the Linux server your application runs on.
Keys
• Packages (p. 686)
• Groups (p. 687)
• Users (p. 688)
• Sources (p. 689)
• Files (p. 689)
• Commands (p. 691)
• Services (p. 692)
• Container commands (p. 694)
• Example: Using custom Amazon CloudWatch metrics (p. 695)
Keys are processed in the order that they are listed here.
Watch your environment's events (p. 816) while developing and testing configuration files. Elastic
Beanstalk ignores a configuration file that contains validation errors, like an invalid key, and doesn't
process any of the other keys in the same file. When this happens, Elastic Beanstalk adds a warning event
to the event log.
Packages
You can use the packages key to download and install prepackaged applications and components.
Syntax
packages:
name of package manager:
package name: version
...
name of package manager:
package name: version
...
686
AWS Elastic Beanstalk Developer Guide
Linux server
...
You can specify multiple packages under each package manager's key.
Specifying versions
Within each package manager, each package is specified as a package name and a list of versions. The
version can be a string, a list of versions, or an empty string or list. An empty string or list indicates that
you want the latest version. For rpm manager, the version is specified as a path to a file on disk or a URL.
Relative paths are not supported.
If you specify a version of a package, Elastic Beanstalk attempts to install that version even if a newer
version of the package is already installed on the instance. If a newer version is already installed, the
deployment fails. Some package managers support multiple versions, but others may not. Please check
the documentation for your package manager for more information. If you do not specify a version and
a version of the package is already installed, Elastic Beanstalk does not install a new version—it assumes
that you want to keep and use the existing version.
Example snippet
The following snippet specifies a version URL for rpm, requests the latest version from yum, and version
0.10.2 of chef from rubygems.
packages:
yum:
libmemcached: []
ruby-devel: []
gcc: []
rpm:
epel: http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
rubygems:
chef: '0.10.2'
Groups
You can use the groups key to create Linux/UNIX groups and to assign group IDs. To create a group, add
a new key-value pair that maps a new group name to an optional group ID. The groups key can contain
one or more group names. The following table lists the available keys.
Syntax
groups:
name of group: {}
name of group:
687
AWS Elastic Beanstalk Developer Guide
Linux server
Options
gid
A group ID number.
If a group ID is specified, and the group already exists by name, the group creation will fail. If
another group has the specified group ID, the operating system may reject the group creation.
Example snippet
The following snippet specifies a group named groupOne without assigning a group ID and a group
named groupTwo that specified a group ID value of 45.
groups:
groupOne: {}
groupTwo:
gid: "45"
Users
You can use the users key to create Linux/UNIX users on the EC2 instance.
Syntax
users:
name of user:
groups:
- name of group
uid: "id of the user"
homeDir: "user's home directory"
Options
uid
A user ID. The creation process fails if the user name exists with a different user ID. If the user ID is
already assigned to an existing user, the operating system may reject the creation request.
groups
A list of group names. The user is added to each group in the list.
homeDir
Users are created as noninteractive system users with a shell of /sbin/nologin. This is by design and
cannot be modified.
Example snippet
users:
myuser:
groups:
- group1
688
AWS Elastic Beanstalk Developer Guide
Linux server
- group2
uid: "50"
homeDir: "/tmp"
Sources
You can use the sources key to download an archive file from a public URL and unpack it in a target
directory on the EC2 instance.
Syntax
sources:
target directory: location of archive file
Supported formats
Supported formats are tar, tar+gzip, tar+bz2, and zip. You can reference external locations such as
Amazon Simple Storage Service (Amazon S3) (e.g., https://mybucket.s3.amazonaws.com/
myobject) as long as the URL is publicly accessible.
Example snippet
The following example downloads a public .zip file from an Amazon S3 bucket and unpacks it into /etc/
myapp:
sources:
/etc/myapp: https://mybucket.s3.amazonaws.com/myobject
Note
Multiple extractions should not reuse the same target path. Extracting another source to the
same target path will replace rather than append to the contents.
Files
You can use the files key to create files on the EC2 instance. The content can be either inline in the
configuration file, or the content can be pulled from a URL. The files are written to disk in lexicographic
order.
You can use the files key to download private files from Amazon S3 by providing an instance profile
for authorization.
If the file path you specify already exists on the instance, the existing file is retained with the extension
.bak appended to its name.
Syntax
files:
"target file location on disk":
mode: "six-digit octal value"
owner: name of owning user for file
group: name of owning group for file
source: URL
authentication: authentication name:
689
AWS Elastic Beanstalk Developer Guide
Linux server
content: |
# this is my
# file content
encoding: encoding format
authentication: authentication name:
Options
content
String content to add to the file. Specify either content or source, but not both.
source
URL of a file to download. Specify either content or source, but not both.
encoding
The encoding format of the string specified with the content option.
A six-digit octal value representing the mode for this file. Not supported for Windows systems.
Use the first three digits for symlinks and the last three digits for setting permissions. To create
a symlink, specify 120xxx, where xxx defines the permissions of the target file. To specify
permissions for a file, use the last three digits, such as 000644.
authentication
The name of a AWS CloudFormation authentication method to use. You can add authentication
methods to the Auto Scaling group metadata with the Resources key. See below for an example.
Example snippet
files:
"/home/ec2-user/myfile" :
mode: "000755"
owner: root
group: root
source: http://foo.bar/myfile
"/home/ec2-user/myfile2" :
mode: "000755"
owner: root
group: root
content: |
this is my
file content
Example using a symlink. This creates a link /tmp/myfile2.txt that points at the existing file /tmp/
myfile1.txt.
files:
"/tmp/myfile2.txt" :
mode: "120400"
690
AWS Elastic Beanstalk Developer Guide
Linux server
content: "/tmp/myfile1.txt"
The following example uses the Resources key to add an authentication method named S3Auth and uses
it to download a private file from an Amazon S3 bucket:
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["elasticbeanstalk-us-west-2-123456789012"]
roleName:
"Fn::GetOptionSetting":
Namespace: "aws:autoscaling:launchconfiguration"
OptionName: "IamInstanceProfile"
DefaultValue: "aws-elasticbeanstalk-ec2-role"
files:
"/tmp/data.json" :
mode: "000755"
owner: root
group: root
authentication: "S3Auth"
source: https://elasticbeanstalk-us-west-2-123456789012.s3-us-west-2.amazonaws.com/
data.json
Commands
You can use the commands key to execute commands on the EC2 instance. The commands run before the
application and web server are set up and the application version file is extracted.
The specified commands run as the root user, and are processed in alphabetical order by name. By
default, commands run in the root directory. To run commands from another directory, use the cwd
option.
To troubleshoot issues with your commands, you can find their output in instance logs (p. 820).
Syntax
commands:
command name:
command: command to run
cwd: working directory
env:
variable name: variable value
test: conditions for command
ignoreErrors: true
Options
command
Either an array (block sequence collection in YAML syntax) or a string specifying the command to
run. Some important notes:
• If you use a string, you don't need to enclose the entire string in quotes. If you do use quotes,
escape literal occurrences of the same type of quote.
• If you use an array, you don't need to escape space characters or enclose command parameters in
quotes. Each array element is a single command argument. Don't use an array to specify multiple
commands.
691
AWS Elastic Beanstalk Developer Guide
Linux server
commands:
command1:
command: git commit -m "This is a comment."
command2:
command: "git commit -m \"This is a comment.\""
command3:
command: 'git commit -m "This is a comment."'
command4:
command:
- git
- commit
- -m
- This is a comment.
To specify multiple commands, use a literal block scalar, as shown in the following example.
commands:
command block:
command: |
git commit -m "This is a comment."
git push
env
(Optional) Sets environment variables for the command. This property overwrites, rather than
appends, the existing environment.
cwd
(Optional) The working directory. If not specified, commands run from the root directory (/).
test
(Optional) A command that must return the value true (exit code 0) in order for Elastic Beanstalk to
process the command, such as a shell script, contained in the command key.
ignoreErrors
(Optional) A boolean value that determines if other commands should run if the command
contained in the command key fails (returns a nonzero value). Set this value to true if you want to
continue running commands even if the command fails. Set it to false if you want to stop running
commands if the command fails. The default value is false.
Example snippet
The following example snippet runs a Python script.
commands:
python_install:
command: myscript.py
cwd: /home/ec2-user
env:
myvarname: myvarvalue
test: "[ -x /usr/bin/python ]"
Services
You can use the services key to define which services should be started or stopped when the instance
is launched. The services key also allows you to specify dependencies on sources, packages, and
692
AWS Elastic Beanstalk Developer Guide
Linux server
files so that if a restart is needed due to files being installed, Elastic Beanstalk takes care of the service
restart.
Syntax
services:
sysvinit:
name of service:
enabled: "true"
ensureRunning: "true"
files:
- "file name"
sources:
- "directory"
packages:
name of package manager:
"package name[: version]"
commands:
- "name of command"
Options
ensureRunning
Set to true to ensure that the service is running after Elastic Beanstalk finishes.
Set to false to ensure that the service is not running after Elastic Beanstalk finishes.
Set to true to ensure that the service is started automatically upon boot.
Set to false to ensure that the service is not started automatically upon boot.
A list of files. If Elastic Beanstalk changes one directly via the files block, the service is restarted.
sources
A list of directories. If Elastic Beanstalk expands an archive into one of these directories, the service
is restarted.
packages
A map of the package manager to a list of package names. If Elastic Beanstalk installs or updates
one of these packages, the service is restarted.
commands
A list of command names. If Elastic Beanstalk runs the specified command, the service is restarted.
Example snippet
The following is an example snippet:
services:
sysvinit:
693
AWS Elastic Beanstalk Developer Guide
Linux server
myservice:
enabled: true
ensureRunning: true
Container commands
You can use the container_commands key to execute commands that affect your application
source code. Container commands run after the application and web server have been set up and the
application version archive has been extracted, but before the application version is deployed. Non-
container commands and other customization operations are performed prior to the application source
code being extracted.
The specified commands run as the root user, and are processed in alphabetical order by name. Container
commands are run from the staging directory, where your source code is extracted prior to being
deployed to the application server. Any changes you make to your source code in the staging directory
with a container command will be included when the source is deployed to its final location.
To troubleshoot issues with your container commands, you can find their output in instance
logs (p. 820).
You can use leader_only to only run the command on a single instance, or configure a test to
only run the command when a test command evaluates to true. Leader-only container commands
are only executed during environment creation and deployments, while other commands and server
customization operations are performed every time an instance is provisioned or updated. Leader-only
container commands are not executed due to launch configuration changes, such as a change in the AMI
Id or instance type.
Syntax
container_commands:
name of container_command:
command: "command to run"
leader_only: true
name of container_command:
command: "command to run"
Options
command
(Optional) Set environment variables prior to running the command, overriding any existing value.
cwd
(Optional) The working directory. By default, this is the staging directory of the unzipped
application.
leader_only
(Optional) Only run the command on a single instance chosen by Elastic Beanstalk. Leader-only
container commands are run before other container commands. A command can be leader-only or
have a test, but not both (leader_only takes precedence).
test
(Optional) Run a test command that must return the true in order to run the container command. A
command can be leader-only or have a test, but not both (leader_only takes precedence).
694
AWS Elastic Beanstalk Developer Guide
Linux server
ignoreErrors
(Optional) Do not fail deployments if the container command returns a value other than 0 (success).
Set to true to enable.
Example snippet
The following is an example snippet.
container_commands:
collectstatic:
command: "django-admin.py collectstatic --noinput"
01syncdb:
command: "django-admin.py syncdb --noinput"
leader_only: true
02migrate:
command: "django-admin.py migrate"
leader_only: true
99customize:
command: "scripts/customize.sh"
The Amazon CloudWatch agent enables CloudWatch metric and log collection from both Amazon EC2
instances and on-premises servers across operating systems. The agent supports metrics collected at
the system level. It also supports custom log and metric collection from your applications or services.
For more information about the Amazon CloudWatch agent, see Collecting metrics and logs with the
CloudWatch agent in the Amazon CloudWatch User Guide. The CloudWatch agent has now replaced
the Amazon CloudWatch Monitoring Scripts. For more information and recommendations, see Monitor
memory and disk metrics in the Amazon EC2 User Guide for Linux Instances.
Note
Elastic Beanstalk Enhanced Health Reporting (p. 776) has native support for publishing a wide
range of instance and environment metrics to CloudWatch. See Publishing Amazon CloudWatch
custom metrics for an environment (p. 800) for details.
Topics
• .Ebextensions configuration file (p. 695)
• Permissions (p. 696)
• Viewing metrics in the CloudWatch console (p. 697)
To use this sample, save it to a file named cloudwatch.config in a directory named .ebextensions
at the top level of your project directory, then deploy your application using the Elastic Beanstalk
console (include the .ebextensions directory in your source bundle (p. 385)) or the EB CLI (p. 956).
695
AWS Elastic Beanstalk Developer Guide
Linux server
For more information about configuration files, see Advanced environment customization with
configuration files (.ebextensions) (p. 683).
.ebextensions/cloudwatch.config
files:
"/opt/aws/amazon-cloudwatch-agent/bin/config.json":
mode: "000600"
owner: root
group: root
content: |
{
"agent": {
"metrics_collection_interval": 60,
"run_as_user": "root"
},
"metrics": {
"append_dimensions": {
"AutoScalingGroupName": "${aws:AutoScalingGroupName}"
},
"metrics_collected": {
"mem": {
"measurement": [
"used_percent"
]
}
}
}
}
container_commands:
start_cloudwatch_agent:
command: /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-
config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json
• files — This section adds the agent configuration file. It indicates which metrics and logs the agent
should send to Amazon CloudWatch. In this example, we're only sending the mem_used_percent
metric. For a complete listing of system level metrics supported by the Amazon CloudWatch agent, see
Metrics collected by the CloudWatch agent in the Amazon CloudWatch User Guide.
• container_commands — This section contains the command that starts the agent, passing in the
configuration file as a parameter. For more details about container_commands, see Container
commands (p. 694).
Permissions
The instances in your environment need the proper IAM permissions in order to publish custom Amazon
CloudWatch metrics using the Amazon CloudWatch agent. You grant permissions to your environment's
instances by adding them to the environment's instance profile (p. 21). You can add permissions to the
instance profile before or after deploying your application.
696
AWS Elastic Beanstalk Developer Guide
Windows server
6. Under Attach Permissions, choose the AWS managed policy CloudWatchAgentServerPolicy. Then
click Attach policy.
For more information about managing policies, see Working with Policies in the IAM User Guide.
For more information, see Viewing available metrics in the Amazon CloudWatch User Guide.
Configuration files support the following keys that affect the Windows server on which your application
runs.
Keys
• Packages (p. 697)
• Sources (p. 698)
• Files (p. 698)
• Commands (p. 700)
• Services (p. 701)
• Container commands (p. 702)
Keys are processed in the order that they are listed here.
Note
Older (non-versioned) .NET platform versions do not process configuration files in the correct
order. Learn more at Migrating across major versions of the Elastic Beanstalk Windows server
platform (p. 187).
Watch your environment's events (p. 816) while developing and testing configuration files. Elastic
Beanstalk ignores a configuration file that contains validation errors, like an invalid key, and doesn't
process any of the other keys in the same file. When this happens, Elastic Beanstalk adds a warning event
to the event log.
Packages
Use the packages key to download and install prepackaged applications and components.
In Windows environments, Elastic Beanstalk supports downloading and installing MSI packages.
(Linux environments support additional package managers. For details, see Packages (p. 686) on the
Customizing Software on Linux Servers page.)
You can reference any external location, such as an Amazon Simple Storage Service (Amazon S3) object,
as long as the URL is publicly accessible.
697
AWS Elastic Beanstalk Developer Guide
Windows server
If you specify several msi: packages, their installation order isn't guaranteed.
Syntax
Specify a name of your choice as the package name, and a URL to an MSI file location as the value. You
can specify multiple packages under the msi: key.
packages:
msi:
package name: package url
...
Examples
The following example specifies a URL to download mysql from https://dev.mysql.com/.
packages:
msi:
mysql: https://dev.mysql.com/get/Downloads/Connector-Net/mysql-connector-net-8.0.11.msi
The following example specifies an Amazon S3 object as the MSI file location.
packages:
msi:
mymsi: https://mybucket.s3.amazonaws.com/myobject.msi
Sources
Use the sources key to download an archive file from a public URL and unpack it in a target directory
on the EC2 instance.
Syntax
sources:
target directory: location of archive file
Supported formats
In Windows environments, Elastic Beanstalk supports the .zip format. (Linux environments support
additional formats. For details, see Sources (p. 689) on the Customizing Software on Linux Servers page.)
You can reference any external location, such as an Amazon Simple Storage Service (Amazon S3) object,
as long as the URL is publicly accessible.
Example
The following example downloads a public .zip file from an Amazon S3 bucket and unpacks it into c:/
myproject/myapp.
sources:
"c:/myproject/myapp": https://mybucket.s3.amazonaws.com/myobject.zip
Files
Use the files key to create files on the EC2 instance. The content can be either inline in the
configuration file, or from a URL. The files are written to disk in lexicographic order. To download private
files from Amazon S3, provide an instance profile for authorization.
698
AWS Elastic Beanstalk Developer Guide
Windows server
Syntax
files:
"target file location on disk":
source: URL
authentication: authentication name:
Options
content
(Optional) A string.
source
(Optional) The URL from which the file is loaded. This option cannot be specified with the content
key.
encoding
(Optional) The encoding format. This option is only used for a provided content key value. The
default value is plain.
(Optional) The name of a AWS CloudFormation authentication method to use. You can add
authentication methods to the Auto Scaling group metadata with the Resources key.
Examples
The following example shows the two ways to provide file content: from a URL, or inline in the
configuration file.
files:
"c:\\targetdirectory\\targetfile.txt":
source: http://foo.bar/myfile
"c:/targetdirectory/targetfile.txt":
content: |
# this is my file
# with content
Note
If you use a backslash (\) in your file path, you must precede that with another backslash (the
escape character) as shown in the previous example.
The following example uses the Resources key to add an authentication method named S3Auth and uses
it to download a private file from an Amazon S3 bucket:
files:
"c:\\targetdirectory\\targetfile.zip":
source: https://elasticbeanstalk-us-east-2-123456789012.s3.amazonaws.com/prefix/
myfile.zip
authentication: S3Auth
699
AWS Elastic Beanstalk Developer Guide
Windows server
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["elasticbeanstalk-us-east-2-123456789012"]
roleName:
"Fn::GetOptionSetting":
Namespace: "aws:autoscaling:launchconfiguration"
OptionName: "IamInstanceProfile"
DefaultValue: "aws-elasticbeanstalk-ec2-role"
Commands
Use the commands key to execute commands on the EC2 instance. The commands are processed in
alphabetical order by name, and they run before the application and web server are set up and the
application version file is extracted.
To troubleshoot issues with your commands, you can find their output in instance logs (p. 820).
Syntax
commands:
command name:
command: command to run
Options
command
Either an array or a string specifying the command to run. If you use an array, you don't need to
escape space characters or enclose command parameters in quotation marks.
cwd
(Optional) The working directory. By default, Elastic Beanstalk attempts to find the directory
location of your project. If not found, it uses c:\Windows\System32 as the default.
env
(Optional) Sets environment variables for the command. This property overwrites, rather than
appends, the existing environment.
ignoreErrors
(Optional) A Boolean value that determines if other commands should run if the command
contained in the command key fails (returns a nonzero value). Set this value to true if you want to
continue running commands even if the command fails. Set it to false if you want to stop running
commands if the command fails. The default value is false.
test
(Optional) A command that must return the value true (exit code 0) in order for Elastic Beanstalk to
process the command contained in the command key.
waitAfterCompletion
(Optional) Seconds to wait after the command completes before running the next command. If
the system requires a reboot after the command completes, the system reboots after the specified
700
AWS Elastic Beanstalk Developer Guide
Windows server
number of seconds elapses. If the system reboots as a result of a command, Elastic Beanstalk will
recover to the point after the command in the configuration file. The default value is 60 seconds.
You can also specify forever, but the system must reboot before you can run another command.
Example
The following example saves the output of the set command to the specified file. If there is a
subsequent command, Elastic Beanstalk runs that command immediately after this command completes.
If this command requires a reboot, Elastic Beanstalk reboots the instance immediately after the
command completes.
commands:
test:
command: set > c:\\myapp\\set.txt
waitAfterCompletion: 0
Services
Use the services key to define which services should be started or stopped when the instance is
launched. The services key also enables you to specify dependencies on sources, packages, and files so
that if a restart is needed due to files being installed, Elastic Beanstalk takes care of the service restart.
Syntax
services:
windows:
name of service:
files:
- "file name"
sources:
- "directory"
packages:
name of package manager:
"package name[: version]"
commands:
- "name of command"
Options
ensureRunning
(Optional) Set to true to ensure that the service is running after Elastic Beanstalk finishes.
Set to false to ensure that the service is not running after Elastic Beanstalk finishes.
(Optional) Set to true to ensure that the service is started automatically upon boot.
Set to false to ensure that the service is not started automatically upon boot.
A list of files. If Elastic Beanstalk changes one directly via the files block, the service is restarted.
701
AWS Elastic Beanstalk Developer Guide
Windows server
sources
A list of directories. If Elastic Beanstalk expands an archive into one of these directories, the service
is restarted.
packages
A map of the package manager to a list of package names. If Elastic Beanstalk installs or updates
one of these packages, the service is restarted.
commands
A list of command names. If Elastic Beanstalk runs the specified command, the service is restarted.
Example
services:
windows:
myservice:
enabled: true
ensureRunning: true
Container commands
Use the container_commands key to execute commands that affect your application source code.
Container commands run after the application and web server have been set up and the application
version archive has been extracted, but before the application version is deployed. Non-container
commands and other customization operations are performed prior to the application source code being
extracted.
Container commands are run from the staging directory, where your source code is extracted prior to
being deployed to the application server. Any changes you make to your source code in the staging
directory with a container command will be included when the source is deployed to its final location.
To troubleshoot issues with your container commands, you can find their output in instance
logs (p. 820).
Use the leader_only option to only run the command on a single instance, or configure a test to
only run the command when a test command evaluates to true. Leader-only container commands
are only executed during environment creation and deployments, while other commands and server
customization operations are performed every time an instance is provisioned or updated. Leader-only
container commands are not executed due to launch configuration changes, such as a change in the AMI
Id or instance type.
Syntax
container_commands:
name of container_command:
command: command to run
Options
command
(Optional) Set environment variables prior to running the command, overriding any existing value.
702
AWS Elastic Beanstalk Developer Guide
Custom resources
cwd
(Optional) The working directory. By default, this is the staging directory of the unzipped
application.
leader_only
(Optional) Only run the command on a single instance chosen by Elastic Beanstalk. Leader-only
container commands are run before other container commands. A command can be leader-only or
have a test, but not both (leader_only takes precedence).
test
(Optional) Run a test command that must return the true in order to run the container command. A
command can be leader-only or have a test, but not both (leader_only takes precedence).
ignoreErrors
(Optional) Do not fail deployments if the container command returns a value other than 0 (success).
Set to true to enable.
waitAfterCompletion
(Optional) Seconds to wait after the command completes before running the next command. If
the system requires a reboot after the command completes, the system reboots after the specified
number of seconds elapses. If the system reboots as a result of a command, Elastic Beanstalk will
recover to the point after the command in the configuration file. The default value is 60 seconds.
You can also specify forever, but the system must reboot before you can run another command.
Example
The following example saves the output of the set command to the specified file. Elastic Beanstalk runs
the command on one instance, and reboots the instance immediately after the command completes.
container_commands:
foo:
command: set > c:\\myapp\\set.txt
leader_only: true
waitAfterCompletion: 0
You can use the Resources key in a configuration file (p. 683) to create and customize AWS resources
in your environment. Resources defined in configuration files are added to the AWS CloudFormation
template used to launch your environment. All AWS CloudFormation resources types are supported.
Note
Whenever you add a resource that isn't managed by Elastic Beanstalk, be sure to add a
user policy with the appropriate permissions to your AWS Identity and Access Management
(IAM) users. The managed user policies (p. 879) that Elastic Beanstalk provides only cover
permissions to Elastic Beanstalk-managed resources.
703
AWS Elastic Beanstalk Developer Guide
Custom resources
For example, the following configuration file adds an Auto Scaling lifecycle hook to the default Auto
Scaling group created by Elastic Beanstalk:
~/my-app/.ebextensions/as-hook.config
Resources:
hookrole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument: {
"Version" : "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Principal": {
"Service": [ "autoscaling.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ]
} ]
}
Policies: [ {
"PolicyName": "SNS",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Resource": "*",
"Action": [
"sqs:SendMessage",
"sqs:GetQueueUrl",
"sns:Publish"
]
}
]
}
} ]
hooktopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint: "my-email@example.com"
Protocol: email
lifecyclehook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
NotificationTargetARN: { "Ref" : "hooktopic" }
RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
This example defines three resources, hookrole, hooktopic and lifecyclehook. The first two
resources are an IAM role, which grants Amazon EC2 Auto Scaling permission to publish messages to
Amazon SNS, and an SNS topic, which relays messages from the Auto Scaling group to an email address.
Elastic Beanstalk creates these resources with the specified properties and types.
lifecyclehook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
NotificationTargetARN: { "Ref" : "hooktopic" }
RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
704
AWS Elastic Beanstalk Developer Guide
Custom resources
The lifecycle hook definition uses two functions (p. 708) to populate values for the hook's properties.
{ "Ref" : "AWSEBAutoScalingGroup" } retrieves the name of the Auto Scaling group created
by Elastic Beanstalk for the environment. AWSEBAutoScalingGroup is one of the standard resource
names (p. 705) provided by Elastic Beanstalk.
For AWS::IAM::Role, Ref only returns the name of the role, not the ARN. To get the ARN for the
RoleARN parameter, you use another intrinsic function, Fn::GetAtt instead, which can get any
attribute from a resource. RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] } gets the Arn
attribute from the hookrole resource.
{ "Ref" : "hooktopic" } gets the ARN of the Amazon SNS topic created earlier in the configuration
file. The value returned by Ref varies per resource type and can be found in the AWS CloudFormation
User Guide topic for the AWS::SNS::Topic resource type.
In a load-balanced environment, you can access additional resources related to the load balancer. Classic
load balancers have a resource for the load balancer and one for the security group attached to it.
Application and network load balancers have additional resources for the load balancer's default listener,
listener rule, and target group.
Load-balanced environments
705
AWS Elastic Beanstalk Developer Guide
Custom resources
Worker environments have resources for the SQS queue that buffers incoming requests, and a Amazon
DynamoDB table that the instances use for leader election.
Worker environments
• AWSEBWorkerQueue (AWS::SQS::Queue) – The Amazon SQS queue from which the daemon pulls
requests that need to be processed.
• AWSEBWorkerDeadLetterQueue (AWS::SQS::Queue) – The Amazon SQS queue that stores messages
that cannot be delivered or otherwise were not successfully processed by the daemon.
• AWSEBWorkerCronLeaderRegistry (AWS::DynamoDB::Table) – The Amazon DynamoDB table that is
the internal registry used by the daemon for periodic tasks.
Keys
• Parameters (p. 706)
• Outputs (p. 707)
• Mappings (p. 707)
Parameters
Parameters are an alternative to Elastic Beanstalk's own custom options (p. 682) that you can use
to define values that you use in other places in your configuration files. Like custom options, you can
use parameters to gather user configurable values in one place. Unlike custom options, you can not
use Elastic Beanstalk's API to set parameter values, and the number of parameters you can define in a
template is limited by AWS CloudFormation.
One reason you might want to use parameters is to make your configuration files double as AWS
CloudFormation templates. If you use parameters instead of custom options, you can use the
configuration file to create the same resource in AWS CloudFormation as its own stack. For example, you
could have a configuration file that adds an Amazon EFS file system to your environment for testing, and
then use the same file to create an independent file system that isn't tied to your environment's lifecycle
for production use.
The following example shows the use of parameters to gather user-configurable values at the top of a
configuration file.
706
AWS Elastic Beanstalk Developer Guide
Custom resources
Parameters:
bucket:
Type: String
Description: "Name of the Amazon S3 bucket in which to store load balancer logs"
Default: "DOC-EXAMPLE-BUCKET"
bucketprefix:
Type: String
Description: "Optional prefix. Can't start or end with a /, or contain the word
AWSLogs"
Default: ""
Outputs
You can use an Outputs block to export information about created resources to AWS CloudFormation.
You can then use the Fn::ImportValue function to pull the value into a AWS CloudFormation
template outside of Elastic Beanstalk.
The following example creates an Amazon SNS topic and exports its ARN to AWS CloudFormation with
the name NotificationTopicArn.
Example sns-topic.config
Resources:
NotificationTopic:
Type: AWS::SNS::Topic
Outputs:
NotificationTopicArn:
Description: Notification topic ARN
Value: { "Ref" : "NotificationTopic" }
Export:
Name: NotificationTopicArn
In a configuration file for a different environment, or a AWS CloudFormation template outside of Elastic
Beanstalk, you can use the Fn::ImportValue function to get the exported ARN. This example assigns
the exported value to an environment property named TOPIC_ARN.
Example env.config
option_settings:
aws:elasticbeanstalk:application:environment:
TOPIC_ARN: '`{ "Fn::ImportValue" : "NotificationTopicArn" }`'
Mappings
You can use a mapping to store key-value pairs organized by namespace. A mapping can help you
organize values that you use throughout your configs, or change a parameter value depending on
another value. For example, the following configuration sets the value of an account ID parameter based
on the current region.
Mappings:
Region2ELBAccountId:
us-east-1:
AccountId: "111122223333"
707
AWS Elastic Beanstalk Developer Guide
Custom resources
us-west-2:
AccountId: "444455556666"
us-west-1:
AccountId: "123456789012"
eu-west-1:
AccountId: "777788889999"
...
Principal:
AWS:
? "Fn::FindInMap"
:
- Region2ELBAccountId
-
Ref: "AWS::Region"
- AccountId
Functions
You can use functions in your configuration files to populate values for resource properties with
information from other resources or from Elastic Beanstalk configuration option settings. Elastic
Beanstalk supports AWS CloudFormation functions (Ref, Fn::GetAtt, Fn::Join), and one Elastic
Beanstalk-specific function, Fn::GetOptionSetting.
Functions
• Ref (p. 708)
• Fn::GetAtt (p. 708)
• Fn::Join (p. 709)
• Fn::GetOptionSetting (p. 709)
Ref
Use Ref to retrieve the default string representation of an AWS resource. The value returned by Ref
depends on the resource type, and sometimes depends on other factors as well. For example, a security
group (AWS::EC2::SecurityGroup) returns either the name or ID of the security group, depending on if the
security group is in a default Amazon Virtual Private Cloud (Amazon VPC), EC2 classic, or a custom VPC.
Note
For details on each resource type, including the return value(s) of Ref, see AWS Resource Types
Reference in the AWS CloudFormation User Guide.
Resources:
lifecyclehook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
You can also use Ref to retrieve the value of a AWS CloudFormation parameter defined elsewhere in the
same file or in a different configuration file.
Fn::GetAtt
Use Fn::GetAtt to retrieve the value of an attribute on an AWS resource.
708
AWS Elastic Beanstalk Developer Guide
Custom resources
Resources:
lifecyclehook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
Fn::Join
Use Fn::Join to combine strings with a delimiter. The strings can be hard-coded or use the output from
Fn::GetAtt or Ref.
Fn::GetOptionSetting
Use Fn::GetOptionSetting to retrieve the value of a configuration option (p. 613) setting applied
to the environment.
"Fn::GetOptionSetting":
Namespace: "namespace"
OptionName: "option name"
DefaultValue: "default value"
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["elasticbeanstalk-us-west-2-123456789012"]
roleName:
"Fn::GetOptionSetting":
Namespace: "aws:autoscaling:launchconfiguration"
OptionName: "IamInstanceProfile"
DefaultValue: "aws-elasticbeanstalk-ec2-role"
709
AWS Elastic Beanstalk Developer Guide
Custom resources
Subtopics of this page provide some extended examples for adding and configuring custom resources in
an Elastic Beanstalk environment.
Examples
• Example: ElastiCache (p. 710)
• Example: SQS, CloudWatch, and SNS (p. 716)
• Example: DynamoDB, CloudWatch, and SNS (p. 717)
Example: ElastiCache
The following samples add an Amazon ElastiCache cluster to EC2-Classic and EC2-VPC (both default
and custom Amazon Virtual Private Cloud (Amazon VPC)) platforms. For more information about these
platforms and how you can determine which ones EC2 supports for your region and your AWS account,
see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html. Then refer
to the section in this topic that applies to your platform.
EC2-classic platforms
This sample adds an Amazon ElastiCache cluster to an environment with instances launched into the
EC2-Classic platform. All of the properties that are listed in this example are the minimum required
properties that must be set for each resource type. You can download the example at ElastiCache
example.
Note
This example creates AWS resources, which you might be charged for. For more information
about AWS pricing, see https://aws.amazon.com/pricing/. Some services are part of the AWS
Free Usage Tier. If you are a new customer, you can test drive these services for free. See https://
aws.amazon.com/free/ for more information.
1. Create an .ebextensions (p. 683) directory in the top-level directory of your source bundle.
2. Create two configuration files with the .config extension and place them in your .ebextensions
directory. One configuration file defines the resources, and the other configuration file defines the
options.
3. Deploy your application to Elastic Beanstalk.
YAML relies on consistent indentation. Match the indentation level when replacing content in an
example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
Create a configuration file (e.g., elasticache.config) that defines the resources. In this example,
we create the ElastiCache cluster by specifying the name of the ElastiCache cluster resource
(MyElastiCache), declaring its type, and then configuring the properties for the cluster. The example
references the name of the ElastiCache security group resource that gets created and defined in this
configuration file. Next, we create an ElastiCache security group. We define the name for this resource,
declare its type, and add a description for the security group. Finally, we set the ingress rules for the
710
AWS Elastic Beanstalk Developer Guide
Custom resources
ElastiCache security group to allow access only from instances inside the ElastiCache security group
(MyCacheSecurityGroup) and the Elastic Beanstalk security group (AWSEBSecurityGroup). The
parameter name, AWSEBSecurityGroup, is a fixed resource name provided by Elastic Beanstalk. You
must add AWSEBSecurityGroup to your ElastiCache security group ingress rules in order for your
Elastic Beanstalk application to connect to the instances in your ElastiCache cluster.
#This sample requires you to create a separate configuration file that defines the custom
option settings for CacheCluster properties.
Resources:
MyElastiCache:
Type: AWS::ElastiCache::CacheCluster
Properties:
CacheNodeType:
Fn::GetOptionSetting:
OptionName : CacheNodeType
DefaultValue: cache.m1.small
NumCacheNodes:
Fn::GetOptionSetting:
OptionName : NumCacheNodes
DefaultValue: 1
Engine:
Fn::GetOptionSetting:
OptionName : Engine
DefaultValue: memcached
CacheSecurityGroupNames:
- Ref: MyCacheSecurityGroup
MyCacheSecurityGroup:
Type: AWS::ElastiCache::SecurityGroup
Properties:
Description: "Lock cache down to webserver access only"
MyCacheSecurityGroupIngress:
Type: AWS::ElastiCache::SecurityGroupIngress
Properties:
CacheSecurityGroupName:
Ref: MyCacheSecurityGroup
EC2SecurityGroupName:
Ref: AWSEBSecurityGroup
For more information about the resources used in this example configuration file, see the following
references:
• AWS::ElastiCache::CacheCluster
• AWS::ElastiCache::SecurityGroup
• AWS::ElastiCache:SecurityGroupIngress
Create a separate configuration file called options.config and define the custom option settings.
option_settings:
"aws:elasticbeanstalk:customoption":
CacheNodeType : cache.m1.small
NumCacheNodes : 1
Engine : memcached
These lines tell Elastic Beanstalk to get the values for the CacheNodeType, NumCacheNodes,
and Engine properties from the CacheNodeType, NumCacheNodes, and Engine values in a
config file (options.config in our example) that contains an option_settings section with an
aws:elasticbeanstalk:customoption section that contains a name-value pair that contains the actual
value to use. In the example above, this means cache.m1.small, 1, and memcached would be used for the
values. For more information about Fn::GetOptionSetting, see Functions (p. 708).
711
AWS Elastic Beanstalk Developer Guide
Custom resources
EC2-VPC (default)
This sample adds an Amazon ElastiCache cluster to an environment with instances launched into the
EC2-VPC platform. Specifically, the information in this section applies to a scenario where EC2 launches
instances into the default VPC. All of the properties in this example are the minimum required properties
that must be set for each resource type. For more information about default VPCs, see Your Default VPC
and Subnets.
Note
This example creates AWS resources, which you might be charged for. For more information
about AWS pricing, see https://aws.amazon.com/pricing/. Some services are part of the AWS
Free Usage Tier. If you are a new customer, you can test drive these services for free. See https://
aws.amazon.com/free/ for more information.
1. Create an .ebextensions (p. 683) directory in the top-level directory of your source bundle.
2. Create two configuration files with the .config extension and place them in your .ebextensions
directory. One configuration file defines the resources, and the other configuration file defines the
options.
3. Deploy your application to Elastic Beanstalk.
YAML relies on consistent indentation. Match the indentation level when replacing content in an
example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
Now name the resources configuration file elasticache.config. To create the ElastiCache cluster,
this example specifies the name of the ElastiCache cluster resource (MyElastiCache), declares its type,
and then configures the properties for the cluster. The example references the ID of the security group
resource that we create and define in this configuration file.
Next, we create an EC2 security group. We define the name for this resource, declare its type, add
a description, and set the ingress rules for the security group to allow access only from instances
inside the Elastic Beanstalk security group (AWSEBSecurityGroup). (The parameter name,
AWSEBSecurityGroup, is a fixed resource name provided by Elastic Beanstalk. You must add
AWSEBSecurityGroup to your ElastiCache security group ingress rules in order for your Elastic
Beanstalk application to connect to the instances in your ElastiCache cluster.)
The ingress rules for the EC2 security group also define the IP protocol and port numbers on which the
cache nodes can accept connections. For Redis, the default port number is 6379.
#This sample requires you to create a separate configuration file that defines the custom
option settings for CacheCluster properties.
Resources:
MyCacheSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
GroupDescription: "Lock cache down to webserver access only"
SecurityGroupIngress :
- IpProtocol : "tcp"
FromPort :
Fn::GetOptionSetting:
OptionName : "CachePort"
DefaultValue: "6379"
ToPort :
Fn::GetOptionSetting:
OptionName : "CachePort"
DefaultValue: "6379"
SourceSecurityGroupName:
Ref: "AWSEBSecurityGroup"
712
AWS Elastic Beanstalk Developer Guide
Custom resources
MyElastiCache:
Type: "AWS::ElastiCache::CacheCluster"
Properties:
CacheNodeType:
Fn::GetOptionSetting:
OptionName : "CacheNodeType"
DefaultValue : "cache.t2.micro"
NumCacheNodes:
Fn::GetOptionSetting:
OptionName : "NumCacheNodes"
DefaultValue : "1"
Engine:
Fn::GetOptionSetting:
OptionName : "Engine"
DefaultValue : "redis"
VpcSecurityGroupIds:
-
Fn::GetAtt:
- MyCacheSecurityGroup
- GroupId
Outputs:
ElastiCache:
Description : "ID of ElastiCache Cache Cluster with Redis Engine"
Value :
Ref : "MyElastiCache"
For more information about the resources used in this example configuration file, see the following
references:
• AWS::ElastiCache::CacheCluster
• AWS::EC2::SecurityGroup
Next, name the options configuration file options.config and define the custom option settings.
option_settings:
"aws:elasticbeanstalk:customoption":
CacheNodeType : cache.t2.micro
NumCacheNodes : 1
Engine : redis
CachePort : 6379
These lines tell Elastic Beanstalk to get the values for the CacheNodeType, NumCacheNodes,
Engine, and CachePort properties from the CacheNodeType, NumCacheNodes, Engine,
and CachePort values in a config file (options.config in our example). That file includes an
aws:elasticbeanstalk:customoption section (under option_settings) that contains name-
value pairs with the actual values to use. In the preceding example, cache.t2.micro, 1, redis,
and 6379 would be used for the values. For more information about Fn::GetOptionSetting, see
Functions (p. 708).
EC2-VPC (custom)
If you create a custom VPC on the EC2-VPC platform and specify it as the VPC into which EC2 launches
instances, the process of adding an Amazon ElastiCache cluster to your environment differs from that of
a default VPC. The main difference is that you must create a subnet group for the ElastiCache cluster. All
of the properties in this example are the minimum required properties that must be set for each resource
type.
Note
This example creates AWS resources, which you might be charged for. For more information
about AWS pricing, see https://aws.amazon.com/pricing/. Some services are part of the AWS
713
AWS Elastic Beanstalk Developer Guide
Custom resources
Free Usage Tier. If you are a new customer, you can test drive these services for free. See https://
aws.amazon.com/free/ for more information.
1. Create an .ebextensions (p. 683) directory in the top-level directory of your source bundle.
2. Create two configuration files with the .config extension and place them in your .ebextensions
directory. One configuration file defines the resources, and the other configuration file defines the
options.
3. Deploy your application to Elastic Beanstalk.
YAML relies on consistent indentation. Match the indentation level when replacing content in an
example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
Now name the resources configuration file elasticache.config. To create the ElastiCache cluster, this
example specifies the name of the ElastiCache cluster resource (MyElastiCache), declares its type, and
then configures the properties for the cluster. The properties in the example reference the name of the
subnet group for the ElastiCache cluster as well as the ID of security group resource that we create and
define in this configuration file.
Next, we create an EC2 security group. We define the name for this resource, declare its type, add
a description, the VPC ID, and set the ingress rules for the security group to allow access only from
instances inside the Elastic Beanstalk security group (AWSEBSecurityGroup). (The parameter
name, AWSEBSecurityGroup, is a fixed resource name provided by Elastic Beanstalk. You must
add AWSEBSecurityGroup to your ElastiCache security group ingress rules in order for your Elastic
Beanstalk application to connect to the instances in your ElastiCache cluster.)
The ingress rules for the EC2 security group also define the IP protocol and port numbers on which the
cache nodes can accept connections. For Redis, the default port number is 6379. Finally, this example
creates a subnet group for the ElastiCache cluster. We define the name for this resource, declare its type,
and add a description and ID of the subnet in the subnet group.
Note
We recommend that you use private subnets for the ElastiCache cluster. For more information
about a VPC with a private subnet, see https://docs.aws.amazon.com/vpc/latest/userguide/
VPC_Scenario2.html.
#This sample requires you to create a separate configuration file that defines the custom
option settings for CacheCluster properties.
Resources:
MyElastiCache:
Type: "AWS::ElastiCache::CacheCluster"
Properties:
CacheNodeType:
Fn::GetOptionSetting:
OptionName : "CacheNodeType"
DefaultValue : "cache.t2.micro"
NumCacheNodes:
Fn::GetOptionSetting:
OptionName : "NumCacheNodes"
DefaultValue : "1"
Engine:
Fn::GetOptionSetting:
OptionName : "Engine"
DefaultValue : "redis"
CacheSubnetGroupName:
Ref: "MyCacheSubnets"
VpcSecurityGroupIds:
- Ref: "MyCacheSecurityGroup"
714
AWS Elastic Beanstalk Developer Guide
Custom resources
MyCacheSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
GroupDescription: "Lock cache down to webserver access only"
VpcId:
Fn::GetOptionSetting:
OptionName : "VpcId"
SecurityGroupIngress :
- IpProtocol : "tcp"
FromPort :
Fn::GetOptionSetting:
OptionName : "CachePort"
DefaultValue: "6379"
ToPort :
Fn::GetOptionSetting:
OptionName : "CachePort"
DefaultValue: "6379"
SourceSecurityGroupId:
Ref: "AWSEBSecurityGroup"
MyCacheSubnets:
Type: "AWS::ElastiCache::SubnetGroup"
Properties:
Description: "Subnets for ElastiCache"
SubnetIds:
Fn::GetOptionSetting:
OptionName : "CacheSubnets"
Outputs:
ElastiCache:
Description : "ID of ElastiCache Cache Cluster with Redis Engine"
Value :
Ref : "MyElastiCache"
For more information about the resources used in this example configuration file, see the following
references:
• AWS::ElastiCache::CacheCluster
• AWS::EC2::SecurityGroup
• AWS::ElastiCache::SubnetGroup
Next, name the options configuration file options.config and define the custom option settings.
Note
In the following example, replace the example CacheSubnets and VpcId values with your own
subnets and VPC.
option_settings:
"aws:elasticbeanstalk:customoption":
CacheNodeType : cache.t2.micro
NumCacheNodes : 1
Engine : redis
CachePort : 6379
CacheSubnets:
- subnet-1a1a1a1a
- subnet-2b2b2b2b
- subnet-3c3c3c3c
VpcId: vpc-4d4d4d4d
These lines tell Elastic Beanstalk to get the values for the CacheNodeType, NumCacheNodes, Engine,
CachePort, CacheSubnets, and VpcId properties from the CacheNodeType, NumCacheNodes,
Engine, CachePort, CacheSubnets, and VpcId values in a config file (options.config in
our example). That file includes an aws:elasticbeanstalk:customoption section (under
715
AWS Elastic Beanstalk Developer Guide
Custom resources
option_settings) that contains name-value pairs with sample values. In the example above,
cache.t2.micro, 1, redis, 6379, subnet-1a1a1a1a, subnet-2b2b2b2b, subnet-3c3c3c3c, and
vpc-4d4d4d4d would be used for the values. For more information about Fn::GetOptionSetting,
see Functions (p. 708).
1. Create an .ebextensions (p. 683) directory in the top-level directory of your source bundle.
2. Create two configuration files with the .config extension and place them in your .ebextensions
directory. One configuration file defines the resources, and the other configuration file defines the
options.
3. Deploy your application to Elastic Beanstalk.
YAML relies on consistent indentation. Match the indentation level when replacing content in an
example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
Create a configuration file (e.g., sqs.config) that defines the resources. In this example, we create an SQS
queue and define the VisbilityTimeout property in the MySQSQueue resource. Next, we create an
SNS Topic and specify that email gets sent to someone@example.com when the alarm is fired. Finally,
we create a CloudWatch alarm if the queue grows beyond 10 messages. In the Dimensions property,
we specify the name of the dimension and the value representing the dimension measurement. We use
Fn::GetAtt to return the value of QueueName from MySQSQueue.
#This sample requires you to create a separate configuration file to define the custom
options for the SNS topic and SQS queue.
Resources:
MySQSQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout:
Fn::GetOptionSetting:
OptionName: VisibilityTimeout
DefaultValue: 30
AlarmTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint:
Fn::GetOptionSetting:
OptionName: AlarmEmail
DefaultValue: "nobody@amazon.com"
Protocol: email
QueueDepthAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: "Alarm if queue depth grows beyond 10 messages"
Namespace: "AWS/SQS"
MetricName: ApproximateNumberOfMessagesVisible
716
AWS Elastic Beanstalk Developer Guide
Custom resources
Dimensions:
- Name: QueueName
Value : { "Fn::GetAtt" : [ "MySQSQueue", "QueueName"] }
Statistic: Sum
Period: 300
EvaluationPeriods: 1
Threshold: 10
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- Ref: AlarmTopic
InsufficientDataActions:
- Ref: AlarmTopic
Outputs :
QueueURL:
Description : "URL of newly created SQS Queue"
Value : { Ref : "MySQSQueue" }
QueueARN :
Description : "ARN of newly created SQS Queue"
Value : { "Fn::GetAtt" : [ "MySQSQueue", "Arn"]}
QueueName :
Description : "Name newly created SQS Queue"
Value : { "Fn::GetAtt" : [ "MySQSQueue", "QueueName"]}
For more information about the resources used in this example configuration file, see the following
references:
• AWS::SQS::Queue
• AWS::SNS::Topic
• AWS::CloudWatch::Alarm
Create a separate configuration file called options.config and define the custom option settings.
option_settings:
"aws:elasticbeanstalk:customoption":
VisibilityTimeout : 30
AlarmEmail : "nobody@example.com"
These lines tell Elastic Beanstalk to get the values for the VisibilityTimeout and Subscription Endpoint
properties from the VisibilityTimeout and Subscription Endpoint values in a config file (options.config
in our example) that contains an option_settings section with an aws:elasticbeanstalk:customoption
section that contains a name-value pair that contains the actual value to use. In the example above,
this means 30 and "nobody@amazon.com" would be used for the values. For more information about
Fn::GetOptionSetting, see the section called “Functions” (p. 708).
You can download the sample that we'll use in this step at DynamoDB session Support example. The
sample contains the following files:
717
AWS Elastic Beanstalk Developer Guide
Custom resources
• A configuration file, options.config, that overrides the defaults in dynamodb.config with specific
settings for this particular installation
index.php
<?php
use Aws\DynamoDb\DynamoDbClient;
// Grab the session table name and region from the configuration file
list($tableName, $region) = file(__DIR__ . '/../sessiontable');
$tableName = rtrim($tableName);
$region = rtrim($region);
// Create a DynamoDB client and register the table as the session handler
$dynamodb = DynamoDbClient::factory(array('region' => $region));
$handler = $dynamodb->registerSessionHandler(array('table_name' => $tableName, 'hash_key'
=> 'username'));
// Grab the instance ID so we can display the EC2 instance that services the request
$instanceId = file_get_contents("http://169.254.169.254/latest/meta-data/instance-id");
?>
<h1>Elastic Beanstalk PHP Sessions Sample</h1>
<p>This sample application shows the integration of the Elastic Beanstalk PHP
container and the session support for DynamoDB from the AWS SDK for PHP 2.
Using DynamoDB session support, the application can be scaled out across
multiple web servers. For more details, see the
<a href="https://aws.amazon.com/php/">PHP Developer Center</a>.</p>
if (isset($_POST['continue'])) {
session_start();
$_SESSION['visits'] = $_SESSION['visits'] + 1;
echo 'Welcome back ' . $_SESSION['username'] . '<br/>';
echo 'This is visit number ' . $_SESSION['visits'] . '<br/>';
session_write_close();
echo '<br/>';
echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>';
echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>';
} elseif (isset($_POST['killsession'])) {
session_start();
echo 'Goodbye ' . $_SESSION['username'] . '<br/>';
session_destroy();
echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>';
echo '<br/>';
echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>';
} elseif (isset($_POST['newsession'])) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['visits'] = 1;
echo 'Welcome to a new session ' . $_SESSION['username'] . '<br/>';
session_write_close();
echo '<br/>';
echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>';
echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>';
} else {
echo 'To get started, enter a username.<br/>';
718
AWS Elastic Beanstalk Developer Guide
Custom resources
echo '<br/>';
echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>';
echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>';
}
?>
</form>
.ebextensions/dynamodb.config
Resources:
SessionTable:
Type: AWS::DynamoDB::Table
Properties:
KeySchema:
HashKeyElement:
AttributeName:
Fn::GetOptionSetting:
OptionName : SessionHashKeyName
DefaultValue: "username"
AttributeType:
Fn::GetOptionSetting:
OptionName : SessionHashKeyType
DefaultValue: "S"
ProvisionedThroughput:
ReadCapacityUnits:
Fn::GetOptionSetting:
OptionName : SessionReadCapacityUnits
DefaultValue: 1
WriteCapacityUnits:
Fn::GetOptionSetting:
OptionName : SessionWriteCapacityUnits
DefaultValue: 1
SessionWriteCapacityUnitsLimit:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " write
capacity limit on the session table." ]]}
Namespace: "AWS/DynamoDB"
MetricName: ConsumedWriteCapacityUnits
Dimensions:
- Name: TableName
Value: { "Ref" : "SessionTable" }
Statistic: Sum
Period: 300
EvaluationPeriods: 12
Threshold:
Fn::GetOptionSetting:
OptionName : SessionWriteCapacityUnitsAlarmThreshold
DefaultValue: 240
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- Ref: SessionAlarmTopic
InsufficientDataActions:
- Ref: SessionAlarmTopic
SessionReadCapacityUnitsLimit:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " read
capacity limit on the session table." ]]}
Namespace: "AWS/DynamoDB"
MetricName: ConsumedReadCapacityUnits
Dimensions:
- Name: TableName
719
AWS Elastic Beanstalk Developer Guide
Custom resources
SessionThrottledRequestsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, ":
requests are being throttled." ]]}
Namespace: AWS/DynamoDB
MetricName: ThrottledRequests
Dimensions:
- Name: TableName
Value: { "Ref" : "SessionTable" }
Statistic: Sum
Period: 300
EvaluationPeriods: 1
Threshold:
Fn::GetOptionSetting:
OptionName: SessionThrottledRequestsThreshold
DefaultValue: 1
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- Ref: SessionAlarmTopic
InsufficientDataActions:
- Ref: SessionAlarmTopic
SessionAlarmTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint:
Fn::GetOptionSetting:
OptionName: SessionAlarmEmail
DefaultValue: "nobody@amazon.com"
Protocol: email
files:
"/var/app/sessiontable":
mode: "000444"
content: |
`{"Ref" : "SessionTable"}`
`{"Ref" : "AWS::Region"}`
"/var/app/composer.json":
mode: "000744"
content:
{
"require": {
"aws/aws-sdk-php": "*"
}
}
container_commands:
"1-install-composer":
command: "cd /var/app; curl -s http://getcomposer.org/installer | php"
720
AWS Elastic Beanstalk Developer Guide
Saved configurations
"2-install-dependencies":
command: "cd /var/app; php composer.phar install"
"3-cleanup-composer":
command: "rm -Rf /var/app/composer.*"
In the sample configuration file, we first create the DynamoDB table and configure the primary key
structure for the table and the capacity units to allocate sufficient resources to provide the requested
throughput. Next, we create CloudWatch alarms for WriteCapacity and ReadCapacity. We create an
SNS topic that sends email to "nobody@amazon.com" if the alarm thresholds are breached.
After we create and configure our AWS resources for our environment, we need to customize the EC2
instances. We use the files key to pass the details of the DynamoDB table to the EC2 instances in our
environment as well as add a "require" in the composer.json file for the AWS SDK for PHP 2. Finally,
we run container commands to install composer, the required dependencies, and then remove the
installer.
.ebextensions/options.config
option_settings:
"aws:elasticbeanstalk:customoption":
SessionHashKeyName : username
SessionHashKeyType : S
SessionReadCapacityUnits : 1
SessionReadCapacityUnitsAlarmThreshold : 240
SessionWriteCapacityUnits : 1
SessionWriteCapacityUnitsAlarmThreshold : 240
SessionThrottledRequestsThreshold : 1
SessionAlarmEmail : me@example.com
Replace the SessionAlarmEmail value with the email where you want alarm notifications sent. The
options.config file contains the values used for some of the variables defined in dynamodb.config.
For example, dynamodb.config contains the following lines:
Subscription:
- Endpoint:
Fn::GetOptionSetting:
OptionName: SessionAlarmEmail
DefaultValue: "nobody@amazon.com"
These lines that tell Elastic Beanstalk to get the value for the Endpoint property from the
SessionAlarmEmail value in a config file (options.config in our sample application) that contains an
option_settings section with an aws:elasticbeanstalk:customoption section that contains a name-value
pair that contains the actual value to use. In the example above, this means SessionAlarmEmail would
be assigned the value nobody@amazon.com.
For more information about the CloudFormation resources used in this example, see the following
references:
• AWS::DynamoDB::Table
• AWS::CloudWatch::Alarm
• AWS::SNS::Topic
721
AWS Elastic Beanstalk Developer Guide
Saved configurations
environment. Saved configurations are YAML formatted templates that define an environment's platform
version (p. 29), tier (p. 13), configuration option (p. 613) settings, and tags.
You can apply tags to a saved configuration when you create it, and edit tags of existing saved
configurations. For details, see Tagging saved configurations (p. 726).
Note
The tags applied to a saved configuration aren't related to the tags specified in a saved
configuration using the Tags: key. The latter are applied to an environment when you apply the
saved configuration to the environment.
Create a saved configuration from the current state of your environment in the Elastic Beanstalk
management console.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Save configuration.
4. Use the on-screen form to name the saved configuration. Optionally, provide a brief description, and
add tag keys and values.
5. Choose Save.
6. Choose Save.
722
AWS Elastic Beanstalk Developer Guide
Saved configurations
The saved configuration includes any settings that you have applied to the environment with the console
or any other client that uses the Elastic Beanstalk API. You can then apply the saved configuration to
your environment at a later date to restore it to its previous state, or apply it to a new environment
during environment creation (p. 409).
723
AWS Elastic Beanstalk Developer Guide
Saved configurations
You can download a configuration using the EB CLI the section called “eb config” (p. 997) command, as
shown in the following example. NAME is the name of your saved configuration.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Saved configurations.
4. Select the saved configuration you want to apply, and then choose Launch environment.
5. Proceed through the wizard to create your environment.
Saved configurations don't include settings applied with configuration files (p. 683) in your
application's source code. If the same setting is applied in both a configuration file and saved
configuration, the setting in the saved configuration takes precedence. Likewise, options specified
in the Elastic Beanstalk console override options in saved configurations. For more information, see
Precedence (p. 614).
Saved configurations are stored in the Elastic Beanstalk S3 bucket in a folder named after your
application. For example, configurations for an application named my-app in the us-west-2
region for account number 123456789012 can be found at s3://elasticbeanstalk-us-
west-2-123456789012/resources/templates/my-app/.
View the contents of a saved configuration by opening it in a text editor. The following example
configuration shows the configuration of a web server environment launched with the Elastic Beanstalk
management console.
EnvironmentConfigurationMetadata:
Description: Saved configuration from a multicontainer Docker environment created with
the Elastic Beanstalk Management Console
DateCreated: '1520633151000'
DateModified: '1520633151000'
Platform:
PlatformArn: arn:aws:elasticbeanstalk:us-east-2::platform/Java 8 running on 64bit Amazon
Linux/2.5.0
OptionSettings:
aws:elasticbeanstalk:command:
BatchSize: '30'
BatchSizeType: Percentage
aws:elasticbeanstalk:sns:topics:
Notification Endpoint: me@example.com
aws:elb:policies:
ConnectionDrainingEnabled: true
ConnectionDrainingTimeout: '20'
aws:elb:loadbalancer:
CrossZone: true
aws:elasticbeanstalk:environment:
ServiceRole: aws-elasticbeanstalk-service-role
aws:elasticbeanstalk:application:
Application Healthcheck URL: /
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
aws:autoscaling:launchconfiguration:
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
724
AWS Elastic Beanstalk Developer Guide
Saved configurations
InstanceType: t2.micro
EC2KeyName: workstation-uswest2
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateType: Health
RollingUpdateEnabled: true
EnvironmentTier:
Type: Standard
Name: WebServer
AWSConfigurationTemplateVersion: 1.1.0.0
Tags:
Cost Center: WebApp Dev
You can modify the contents of a saved configuration and save it in the same location in Amazon S3. Any
properly formatted saved configuration stored in the right location can be applied to an environment by
using the Elastic Beanstalk management console.
AWSConfigurationTemplateVersion: 1.1.0.0
• Platform – The Amazon Resource Name (ARN) of the environment's platform version. You can specify
the platform by ARN or solution stack name.
Platform:
PlatformArn: arn:aws:elasticbeanstalk:us-east-2::platform/Java 8 running on 64bit
Amazon Linux/2.5.0
• SolutionStack – The full name of the solution stack (p. 29) used to create the environment.
• OptionSettings – Configuration option (p. 613) settings to apply to the environment. For example,
the following entry sets the instance type to t2.micro.
OptionSettings:
aws:autoscaling:launchconfiguration:
InstanceType: t2.micro
Tags:
Cost Center: WebApp Dev
• EnvironmentTier – The type of environment to create. For a web server environment, you can exclude
this section (web server is the default). For a worker environment, use the following.
EnvironmentTier:
Name: Worker
Type: SQS/HTTP
See the following topics for alternate methods of creating and applying saved configurations:
725
AWS Elastic Beanstalk Developer Guide
Tagging saved configurations
You can specify tags when you create a saved configuration. In an existing saved configuration, you can
add or remove tags, and update the values of existing tags. You can add up to 50 tags to each saved
configuration.
If you use the EB CLI to save a configuration, use the --tags option with eb config (p. 997) to add
tags.
With the AWS CLI or other API-based clients, add tags by using the --tags parameter on the create-
configuration-template command.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Applications, and then choose your application's name from the list.
Note
If you have many applications, use the search bar to filter the application list.
3. In the navigation pane, find your application's name and choose Saved configurations.
4. Select the saved configuration you want to manage.
5. Choose Actions, and then choose Manage tags.
6. Use the on-screen form to add, update, or delete tags.
7. Choose Apply.
If you use the EB CLI to update your saved configuration, use eb tags (p. 1040) to add, update, delete, or
list tags.
For example, the following command lists the tags in a saved configuration.
The following command updates the tag mytag1 and deletes the tag mytag2.
726
AWS Elastic Beanstalk Developer Guide
env.yaml
For a complete list of options and more examples, see eb tags (p. 1040).
With the AWS CLI or other API-based clients, use the list-tags-for-resource command to list the tags of a
saved configuration.
Use the update-tags-for-resource command to add, update, or delete tags in a saved configuration.
Specify both tags to add and tags to update in the --tags-to-add parameter of update-tags-for-
resource. A nonexisting tag is added, and an existing tag's value is updated.
Note
To use some of the EB CLI and AWS CLI commands with an Elastic Beanstalk saved
configuration, you need the saved configuration's ARN. To construct the ARN, first use the
following command to retrieve the saved configuration's name.
Look for the ConfigurationTemplates key in the command's output. This element shows the
saved configuration's name. Use this name where my-template is specified in the commands
mentioned on this page.
This file format includes support for environment groups. To use groups, specify the environment name
in the manifest with a + symbol at the end. When you create or update the environment, specify the
group name with --group-name (AWS CLI) or --env-group-suffix (EB CLI). For more information on
groups, see Creating and updating groups of Elastic Beanstalk environments (p. 439).
The following example manifest defines a web server environment with a link to a worker environment
component that it is dependent upon. The manifest uses groups to allow creating multiple environments
with the same source bundle:
~/myapp/frontend/env.yaml
AWSConfigurationTemplateVersion: 1.1.0.0
SolutionStack: 64bit Amazon Linux 2015.09 v2.0.6 running Multi-container Docker 1.7.1
(Generic)
OptionSettings:
aws:elasticbeanstalk:command:
BatchSize: '30'
BatchSizeType: Percentage
727
AWS Elastic Beanstalk Developer Guide
env.yaml
aws:elasticbeanstalk:sns:topics:
Notification Endpoint: me@example.com
aws:elb:policies:
ConnectionDrainingEnabled: true
ConnectionDrainingTimeout: '20'
aws:elb:loadbalancer:
CrossZone: true
aws:elasticbeanstalk:environment:
ServiceRole: aws-elasticbeanstalk-service-role
aws:elasticbeanstalk:application:
Application Healthcheck URL: /
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
aws:autoscaling:launchconfiguration:
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
InstanceType: t2.micro
EC2KeyName: workstation-uswest2
aws:autoscaling:updatepolicy:rollingupdate:
RollingUpdateType: Health
RollingUpdateEnabled: true
Tags:
Cost Center: WebApp Dev
CName: front-A08G28LG+
EnvironmentName: front+
EnvironmentLinks:
"WORKERQUEUE" : "worker+"
AWSConfigurationTemplateVersion: 1.1.0.0
• Platform – The Amazon Resource Name (ARN) of the environment's platform version. You can specify
the platform by ARN or solution stack name.
Platform:
PlatformArn: arn:aws:elasticbeanstalk:us-east-2::platform/Java 8 running on 64bit
Amazon Linux/2.5.0
• SolutionStack – The full name of the solution stack (p. 29) used to create the environment.
• OptionSettings – Configuration option (p. 613) settings to apply to the environment. For example,
the following entry sets the instance type to t2.micro.
OptionSettings:
aws:autoscaling:launchconfiguration:
InstanceType: t2.micro
Tags:
Cost Center: WebApp Dev
• EnvironmentTier – The type of environment to create. For a web server environment, you can exclude
this section (web server is the default). For a worker environment, use the following.
EnvironmentTier:
Name: Worker
728
AWS Elastic Beanstalk Developer Guide
Custom image
Type: SQS/HTTP
• CName – The CNAME for the environment. Include a + character at the end of the name to enable
groups.
CName: front-A08G28LG+
• EnvironmentName – The name of the environment to create. Include a + character at the end of the
name to enable groups.
EnvironmentName: front+
With groups enabled, you must specify a group name when you create the environments. Elastic
Beanstalk appends the group name to the environment name with a hyphen. For example, with the
environment name front+ and the group name dev, Elastic Beanstalk will create the environment
with the name front-dev.
• EnvironmentLinks – A map of variable names and environment names of dependencies. The following
example makes the worker+ environment a dependency and tells Elastic Beanstalk to save the link
information to a variable named WORKERQUEUE.
EnvironmentLinks:
"WORKERQUEUE" : "worker+"
The value of the link variable varies depending on the type of the linked environment. For a web server
environment, the link is the environment's CNAME. For a worker environment, the link is the name of
the environment's Amazon Simple Queue Service (Amazon SQS) queue.
The CName, EnvironmentName and EnvironmentLinks keys can be used to create environment
groups (p. 439) and links to other environments (p. 489). These features are currently supported when
using the EB CLI, AWS CLI or an SDK.
Using configuration files (p. 683) is great for configuring and customizing your environment quickly
and consistently. Applying configurations, however, can start to take a long time during environment
creation and updates. If you do a lot of server configuration in configuration files, you can reduce this
time by making a custom AMI that already has the software and configuration that you need.
A custom AMI also allows you to make changes to low-level components, such as the Linux kernel, that
are difficult to implement or take a long time to apply in configuration files. To create a custom AMI,
launch an Elastic Beanstalk platform AMI in Amazon EC2, customize the software and configuration to
your needs, and then stop the instance and save an AMI from it.
1. In a command window, run a command like the following. For more information, see describe-
platform-version in the AWS CLI Command Reference.
729
AWS Elastic Beanstalk Developer Guide
Creating a custom AMI
Specify the AWS Region where you want to use your custom AMI, and replace the platform ARN and
version number with the Elastic Beanstalk platform that your application is based on.
Example - Windows OS
2. Take note of the ImageId value that looks like ami-020ae06fdda6a0f66 in the result.
The value is the stock Elastic Beanstalk AMI for the platform version, EC2 instance architecture, and
AWS Region that are relevant for your application. If you need to create AMIs for multiple platforms,
architectures or AWS Regions, repeat this process to identify the correct base AMI for each combination.
Notes
• Don't create an AMI from an instance that has been launched in an Elastic Beanstalk
environment. Elastic Beanstalk makes changes to instances during provisioning that can cause
issues in the saved AMI. Saving an image from an instance in an Elastic Beanstalk environment
will also make the version of your application that was deployed to the instance a fixed part
of the image.
• We recommend that you always use the latest platform version. When you update to a new
platform version, we also recommend that you rebase your custom AMI to the new platform
version's AMI. This minimizes deployment failures due to incompatible package or library
versions.
For Linux, it is also possible to create a custom AMI from a community AMI that wasn't published by
Elastic Beanstalk. You can use the latest Amazon Linux AMI as a starting point. When you launch an
environment with a Linux AMI that isn't managed by Elastic Beanstalk, Elastic Beanstalk attempts
730
AWS Elastic Beanstalk Developer Guide
Creating a custom AMI
to install platform software (language, framework, proxy server, etc.) and additional components to
support features such as Enhanced Health Reporting (p. 776).
Note
Custom AMIs based on Windows Server require the stock Elastic Beanstalk AMI returned from
describe-platform-version, as shown earlier in Step 1.
Although Elastic Beanstalk can use an AMI that isn't managed by Elastic Beanstalk, the increase in
provisioning time that results from Elastic Beanstalk installing missing components can reduce or
eliminate the benefits of creating a custom AMI in the first place. Other Linux distributions might work
with some troubleshooting but are not officially supported. If your application requires a specific Linux
distribution, one alternative is to create a Docker image and run it on the Elastic Beanstalk Docker
platform (p. 50) or Multicontainer Docker platform (p. 65).
You can also search the list for another community AMI that suits your needs.
Note
We recommend that you choose an AMI that uses HVM virtualization. These AMIs show
Virtualization type: hvm in their description.
For details about instance virtualization types, see Linux AMI Virtualization Types in the
Amazon EC2 User Guide for Linux Instances or Windows AMI Virtualization Types in the
Amazon EC2 User Guide for Windows Instances.
5. Choose Select to select the AMI.
6. Select an instance type, and then choose Next: Configure Instance Details.
7. (For Linux platforms) Expand the Advanced Details section and paste the following text in the User
Data field.
#cloud-config
repo_releasever: repository version number
repo_upgrade: none
The repository version number is the year and month version in the AMI name. For example, AMIs
based on the March 2015 release of Amazon Linux have a repository version number 2015.03.
For an Elastic Beanstalk image, this matches the date shown in the solution stack name for your
platform version (p. 29) based on Amazon Linux AMI (preceding Amazon Linux 2).
Note
The repo_releasever setting configures the lock-on-launch feature for an Amazon
Linux AMI. This causes the AMI to use a fixed, specific repository version when it launches.
This feature isn't supported on Amazon Linux 2—don't specify it if your environment
uses a current Amazon Linux 2 platform branch. The setting is required if you're using a
731
AWS Elastic Beanstalk Developer Guide
Cleaning up a custom AMI
custom AMI with Elastic Beanstalk only on Amazon Linux AMI platform branches (preceding
Amazon Linux 2).
The repo_upgrade setting disables the automatic installation of security updates. It's
required to use a custom AMI with Elastic Beanstalk.
8. Proceed through the wizard to launch the EC2 instance. When prompted, select a key pair that you
have access to so that you can connect to the instance for the next steps.
9. Connect to the instance with SSH or RDP.
10. Perform any customizations you want.
11. (Windows platforms) Run the EC2Config service Sysprep. For information about EC2Config, see
Configuring a Windows Instance Using the EC2Config Service. Ensure that Sysprep is configured to
generate a random password that can be retrieved from the AWS Management Console.
12. In the Amazon EC2 console, stop the EC2 instance. Then on the Instance Actions menu, choose
Create Image (EBS AMI).
13. To avoid incurring additional AWS charges, terminate the EC2 instance.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Capacity configuration category, choose Edit.
5. For AMI ID, enter your custom AMI ID.
6. Choose Apply.
When you create a new environment with the custom AMI, you should use the same platform
version that you used as a base to create the AMI. If you later apply a platform update (p. 459) to an
environment using a custom AMI, Elastic Beanstalk attempts to apply the library and configuration
updates during the bootstrapping process.
Elastic Beanstalk supports configuring the proxy to serve static files on most platform branches based on
Amazon Linux 2. The one exception is Docker.
732
AWS Elastic Beanstalk Developer Guide
Configure static files using the console
Note
On the Python and Ruby platforms, Elastic Beanstalk configures some static file folders
by default. For details, see the static file configuration sections for Python (p. 336) and
Ruby (p. 360). You can configure additional folders as explained on this page.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Static files section, enter a path for serving static files and the directory of the static files to
serve into the empty row at the bottom of the list.
Note
If you aren't seeing the Static files section, you have to add at least one mapping by using
a configuration file (p. 683). For details, see the section called “Configure static files using
configuration options” (p. 734) on this page.
Start the path with a slash (/). Specify a directory name in the root of your application's source code;
don't start it with a slash.
When you add a mapping, an extra row appears in case you want to add another one. To remove a
mapping, click the Remove icon.
6. Choose Apply.
733
AWS Elastic Beanstalk Developer Guide
Configure static files using configuration options
If your environment uses a platform branch based on Amazon Linux 2, use the
aws:elasticbeanstalk:environment:proxy:staticfiles (p. 655) namespace.
The following example configuration file tells the proxy server to serve files in the statichtml folder at
the path /html, and files in the staticimages folder at the path /images.
Example .ebextensions/static-files.config
option_settings:
aws:elasticbeanstalk:environment:proxy:staticfiles:
/html: statichtml
/images: staticimages
If your Elastic Beanstalk environment uses an Amazon Linux AMI platform version (preceding Amazon
Linux 2), read the following additional information:
The simplest way to use HTTPS with an Elastic Beanstalk environment is to assign a server certificate to
your environment's load balancer (p. 738). When you configure your load balancer to terminate HTTPS,
the connection between the client and the load balancer is secure. Backend connections between the
load balancer and EC2 instances use HTTP, so no additional configuration of the instances is required.
Note
With AWS Certificate Manager (ACM), you can create a trusted certificate for your domain names
for free. ACM certificates can only be used with AWS load balancers and Amazon CloudFront
distributions, and ACM is available only in certain AWS Regions.
To use an ACM certificate with Elastic Beanstalk, see Configuring your Elastic Beanstalk
environment's load balancer to terminate HTTPS (p. 738).
If you run your application in a single instance environment, or need to secure the connection all the
way to the EC2 instances behind the load balancer, you can configure the proxy server that runs on the
734
AWS Elastic Beanstalk Developer Guide
Create a certificate
instance to terminate HTTPS (p. 741). Configuring your instances to terminate HTTPS connections
requires the use of configuration files (p. 683) to modify the software running on the instances, and to
modify security groups to allow secure connections.
For end-to-end HTTPS in a load-balanced environment, you can combine instance and load balancer
termination (p. 763) to encrypt both connections. By default, if you configure the load balancer to
forward traffic using HTTPS, it will trust any certificate presented to it by the backend instances. For
maximum security, you can attach policies to the load balancer that prevent it from connecting to
instances that don't present a public certificate that it trusts.
Note
You can also configure the load balancer to relay HTTPS traffic without decrypting it (p. 766).
The down side to this method is that the load balancer cannot see the requests and thus cannot
optimize routing or report response metrics.
If ACM is not available in your region, you can purchase a trusted certificate from a third party. A third-
party certificate can be used to decrypt HTTPS traffic at your load balancer, on the backend instances, or
both.
For development and testing, you can create and sign a certificate (p. 735) yourself with open source
tools. Self-signed certificates are free and easy to create, but cannot be used for front-end decryption on
public sites. If you attempt to use a self-signed certificate for an HTTPS connection to a client, the user's
browser displays an error message indicating that your web site is unsafe. You can, however, use a self-
signed certificate to secure backend connections without issue.
ACM is the preferred tool to provision, manage, and deploy your server certificates programmatically
or using the AWS CLI. If ACM is not available in your AWS Region, you can upload a third-party or self-
signed certificate and private key (p. 737) to AWS Identity and Access Management (IAM) by using the
AWS CLI. Certificates stored in IAM can be used with load balancers and CloudFront distributions.
Note
The Does it have Snakes? sample application on GitHub includes configuration files and
instructions for each method of configuring HTTPS with a Tomcat web application. See the
readme file and HTTPS instructions for details.
Topics
• Create and sign an X509 certificate (p. 735)
• Upload a certificate to IAM (p. 737)
• Configuring your Elastic Beanstalk environment's load balancer to terminate HTTPS (p. 738)
• Configuring your application to terminate HTTPS connections at the instance (p. 741)
• Configuring end-to-end encryption in a load-balanced Elastic Beanstalk environment (p. 763)
• Configuring your environment's load balancer for TCP Passthrough (p. 766)
• Storing private keys securely in Amazon S3 (p. 767)
• Configuring HTTP to HTTPS redirection (p. 768)
735
AWS Elastic Beanstalk Developer Guide
Create a certificate
Run openssl version at the command line to see if you already have OpenSSL installed. If you don't,
you can build and install the source code using the instructions at the public GitHub repository, or use
your favorite package manager. OpenSSL is also installed on Elastic Beanstalk's Linux images, so a quick
alternative is to connect to an EC2 instance in a running environment by using the EB CLI (p. 956)'s eb
ssh command:
~/eb$ eb ssh
[ec2-user@ip-255-55-55-255 ~]$ openssl version
OpenSSL 1.0.1k-fips 8 Jan 2015
You need to create an RSA private key to create your certificate signing request (CSR). To create your
private key, use the openssl genrsa command:
privatekey.pem
The name of the file where you want to save the private key. Normally, the openssl genrsa
command prints the private key contents to the screen, but this command pipes the output to a file.
Choose any file name, and store the file in a secure place so that you can retrieve it later. If you lose
your private key, you won't be able to use your certificate.
A CSR is a file you send to a certificate authority (CA) to apply for a digital server certificate. To create a
CSR, use the openssl req command:
Enter the information requested and press Enter. The following table describes and shows examples for
each field.
Country Name The two-letter ISO abbreviation for your US = United States
country.
State or Province The name of the state or province where your Washington
organization is located. You cannot abbreviate
this name.
Locality Name The name of the city where your organization is Seattle
located.
Organization Name The full legal name of your organization. Do not Example Corporation
abbreviate your organization name.
736
AWS Elastic Beanstalk Developer Guide
Upload a certificate
Common Name The fully qualified domain name for your web www.example.com
site. This must match the domain name that
users see when they visit your site, otherwise
certificate errors will be shown.
You can submit the signing request to a third party for signing, or sign it yourself for development and
testing. Self-signed certificates can also be used for backend HTTPS between a load balancer and EC2
instances.
To sign the certificate, use the openssl x509 command. The following example uses the private key from
the previous step (privatekey.pem) and the signing request (csr.pem) to create a public certificate
named public.crt that is valid for 365 days.
$ openssl x509 -req -days 365 -in csr.pem -signkey privatekey.pem -out public.crt
Signature ok
subject=/C=us/ST=washington/L=seattle/O=example corporation/OU=marketing/
CN=www.example.com/emailAddress=someone@example.com
Getting Private key
Keep the private key and public certificate for later use. You can discard the signing request. Always store
the private key in a secure location (p. 767) and avoid adding it to your source code.
To use the certificate with the Windows Server platform, you must convert it to a PFX format. Use the
following command to create a PFX certificate from the private key and public certificate files:
Now that you have a certificate, you can upload it to IAM (p. 737) for use with a load balancer, or
configure the instances in your environment to terminate HTTPS (p. 741).
You can use the AWS Command Line Interface (p. 954) (AWS CLI) to upload your certificate. The
following command uploads a self-signed certificate named https-cert.crt with a private key named
private-key.pem:
737
AWS Elastic Beanstalk Developer Guide
Terminate at the load balancer
"ServerCertificateId": "AS5YBEIONO2Q7CAIHKNGC",
"ServerCertificateName": "elastic-beanstalk-x509",
"Expiration": "2017-01-31T23:06:22Z",
"Path": "/",
"Arn": "arn:aws:iam::123456789012:server-certificate/elastic-beanstalk-x509",
"UploadDate": "2016-02-01T23:10:34.167Z"
}
}
The file:// prefix tells the AWS CLI to load the contents of a file in the current directory. elastic-
beanstalk-x509 specifies the name to call the certificate in IAM.
If you purchased a certificate from a certificate authority and received a certificate chain file, upload that
as well by including the --certificate-chain option:
Make note of the Amazon Resource Name (ARN) for your certificate. You'll use it when you update your
load balancer configuration settings to use HTTPS.
Note
A certificate uploaded to IAM stays stored even after it's no longer used in any environment's
load balancer. It contains sensitive data. When you no longer need the certificate for any
environment, be sure to delete it. For details about deleting a certificate from IAM, see https://
docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html#delete-server-
certificate.
For more information about server certificates in IAM, see Working with Server Certificates in the IAM
User Guide.
You can use the Elastic Beanstalk console or a configuration file to configure a secure listener and assign
the certificate.
Note
Single-instance environments don't have a load balancer and don't support HTTPS termination
at the load balancer.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Load balancer configuration category, choose Edit.
738
AWS Elastic Beanstalk Developer Guide
Terminate at the load balancer
Note
If the Load balancer configuration category doesn't have an Edit button, your environment
doesn't have a load balancer (p. 481).
5. On the Modify load balancer page, the procedure varies depending on the type of load balancer
associated with your environment.
• Classic Load Balancer
• For Listener port, type the incoming traffic port, typically 443.
• For Listener protocol, choose HTTPS.
• For Instance port, type 80.
• For Instance protocol, choose HTTP.
• For SSL certificate, choose your certificate.
c. Choose Add.
• Application Load Balancer
Note
For Classic Load Balancer and Application Load Balancer, if the drop-down menu
doesn't show any certificates, you should create or upload a certificate for your custom
domain name (p. 612) in AWS Certificate Manager (ACM) (preferred). Alternatively,
upload a certificate to IAM with the AWS CLI.
• Network Load Balancer
Example .ebextensions/securelistener-clb.config
Use this example when your environment has a Classic Load Balancer. The example uses options in
the aws:elb:listener namespace to configure an HTTPS listener on port 443 with the specified
certificate, and to forward the decrypted traffic to the instances in your environment on port 80.
option_settings:
aws:elb:listener:443:
739
AWS Elastic Beanstalk Developer Guide
Terminate at the load balancer
SSLCertificateId: arn:aws:acm:us-east-2:1234567890123:certificate/
####################################
ListenerProtocol: HTTPS
InstancePort: 80
Replace the highlighted text with the ARN of your certificate. The certificate can be one that you created
or uploaded in AWS Certificate Manager (ACM) (preferred), or one that you uploaded to IAM with the
AWS CLI.
For more information about Classic Load Balancer configuration options, see Classic Load Balancer
configuration namespaces (p. 536).
Example .ebextensions/securelistener-alb.config
Use this example when your environment has an Application Load Balancer. The example uses options
in the aws:elbv2:listener namespace to configure an HTTPS listener on port 443 with the specified
certificate. The listener routes traffic to the default process.
option_settings:
aws:elbv2:listener:443:
ListenerEnabled: 'true'
Protocol: HTTPS
SSLCertificateArns: arn:aws:acm:us-east-2:1234567890123:certificate/
####################################
Example .ebextensions/securelistener-nlb.config
Use this example when your environment has a Network Load Balancer. The example uses options in the
aws:elbv2:listener namespace to configure a listener on port 443. The listener routes traffic to the
default process.
option_settings:
aws:elbv2:listener:443:
ListenerEnabled: 'true'
You add this rule by adding a Resources key to a configuration file (p. 683) in the .ebextensions
directory for your application.
The following example configuration file adds an ingress rule to the AWSEBSecurityGroup security
group. This allows traffic on port 1000 from the load balancer's security group.
Example .ebextensions/sg-ingressfromlb.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 1000
FromPort: 1000
SourceSecurityGroupName: {"Fn::GetAtt" : ["AWSEBLoadBalancer" ,
"SourceSecurityGroup.GroupName"]}
740
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
To enable HTTPS, you must allow incoming traffic on port 443 to the EC2 instance that your Elastic
Beanstalk application is running on. You do this by using the Resources key in the configuration file to
add a rule for port 443 to the ingress rules for the AWSEBSecurityGroup security group.
The following snippet adds an ingress rule to the AWSEBSecurityGroup security group that opens port
443 to all traffic for a single instance environment:
.ebextensions/https-instance-securitygroup.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
In a load-balanced environment in a default Amazon Virtual Private Cloud (Amazon VPC), you can
modify this policy to only accept traffic from the load balancer. See Configuring end-to-end encryption
in a load-balanced Elastic Beanstalk environment (p. 763) for an example.
Platforms
• Terminating HTTPS on EC2 instances running Docker (p. 741)
• Terminating HTTPS on EC2 instances running Go (p. 743)
• Terminating HTTPS on EC2 instances running Java SE (p. 745)
• Terminating HTTPS on EC2 instances running Node.js (p. 747)
• Terminating HTTPS on EC2 instances running PHP (p. 749)
• Terminating HTTPS on EC2 instances running Python (p. 751)
• Terminating HTTPS on EC2 instances running Ruby (p. 754)
• Terminating HTTPS on EC2 instances running Tomcat (p. 758)
• Terminating HTTPS on Amazon EC2 instances running .NET Core on Linux (p. 760)
• Terminating HTTPS on Amazon EC2 instances running .NET (p. 762)
Add the following snippet to your configuration file, replacing the certificate and private key material as
instructed, and save it in your source bundle's .ebextensions directory. The configuration file performs
the following tasks:
741
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
/etc/nginx/conf.d/https.conf
Configures the nginx server. This file is loaded when the nginx service starts.
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
Example .ebextensions/https-instance.config
files:
/etc/nginx/conf.d/https.conf:
mode: "000644"
owner: root
group: root
content: |
# HTTPS Server
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://docker;
proxy_http_version 1.1;
742
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
/etc/pki/tls/certs/server.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file, replacing the certificate and private key
placeholders as instructed, and save it in your source bundle's .ebextensions directory. The
configuration file performs the following tasks:
• The Resources key enables port 443 on the security group used by your environment's instance.
• The files key creates the following files on the instance:
743
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
• The container_commands key restarts the nginx server after everything is configured so that the
server loads the nginx configuration file.
Example .ebextensions/https-instance.config
files:
/etc/pki/tls/certs/server.crt:
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
container_commands:
01restart_nginx:
command: "service nginx restart"
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
Place the following in a file with the .conf extension in the .ebextensions/nginx/conf.d/
directory of your source bundle (e.g., .ebextensions/nginx/conf.d/https.conf). Replace
app_port with the port number that your application listens on. This example configures the nginx
server to listen on port 443 using SSL. For more information about these configuration files on the Go
platform, see Configuring the reverse proxy (p. 104).
744
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Example .ebextensions/nginx/conf.d/https.conf
# HTTPS server
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://localhost:app_port;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file, replacing the certificate and private key
placeholders as instructed, and save it in the .ebextensions directory. The configuration file performs
the following tasks:
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
745
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
• The container_commands key restarts the nginx server after everything is configured so that the
server loads the nginx configuration file.
Example .ebextensions/https-instance.config
files:
/etc/pki/tls/certs/server.crt:
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
container_commands:
01restart_nginx:
command: "service nginx restart"
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
Place the following in a file with the .conf extension in the .ebextensions/nginx/conf.d/
directory of your source bundle (e.g., .ebextensions/nginx/conf.d/https.conf). Replace
app_port with the port number that your application listens on. This example configures the nginx
server to listen on port 443 using SSL. For more information about these configuration files on the Java
SE platform, see Configuring the reverse proxy (p. 130).
Example .ebextensions/nginx/conf.d/https.conf
# HTTPS server
746
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://localhost:app_port;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
If you configured your environment for enhanced health reporting (p. 776), you need to configure
nginx to generate access logs. To do that, uncomment the block of lines under the comment that reads #
For enhanced health... by removing the leading # characters.
Example .ebextensions/https-instance.config
files:
/etc/nginx/conf.d/https.conf:
mode: "000644"
owner: root
group: root
content: |
# HTTPS server
747
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://nodejs;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
/etc/pki/tls/certs/server.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
/etc/nginx/conf.d/https.conf
Configures the nginx server. This file is loaded when the nginx service starts.
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
748
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Note
YAML relies on consistent indentation. Match the indentation level when replacing content
in an example configuration file and ensure that your text editor uses spaces, not tab
characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents of
the private key used to create the certificate request or self-signed certificate.
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file, replacing the certificate and private key material as
instructed, and save it in your source bundle's .ebextensions directory.
749
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Configures the Apache server. This file loads when the Apache service starts.
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
Example .ebextensions/https-instance.config
packages:
yum:
mod24_ssl : []
files:
/etc/httpd/conf.d/ssl.conf:
mode: "000644"
owner: root
group: root
content: |
LoadModule ssl_module modules/mod_ssl.so
Listen 443
<VirtualHost *:443>
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
SSLEngine on
SSLCertificateFile "/etc/pki/tls/certs/server.crt"
SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3
SSLHonorCipherOrder On
SSLSessionTickets Off
750
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
</VirtualHost>
/etc/pki/tls/certs/server.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file (p. 683), replacing the certificate and private key
material as instructed, and save it in your source bundle's .ebextensions directory. The configuration
file performs the following tasks:
751
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Configures the Apache server. If your application is not named application.py, replace the
highlighted text in the value for WSGIScriptAlias with the local path to your application. For
example, a django application's may be at django/wsgi.py. The location should match the value
of the WSGIPath option that you set for your environment.
Depending on your application requirements, you may also need to add other directories to the
python-path parameter.
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
• The container_commands key stops the httpd service after everything has been configured so that
the service uses the new https.conf file and certificate.
Note
The example works only in environments using the Python (p. 334) platform.
Example .ebextensions/https-instance.config
packages:
yum:
mod24_ssl : []
files:
/etc/httpd/conf.d/ssl.conf:
mode: "000644"
owner: root
group: root
content: |
LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonHome /opt/python/run/baselinenv
WSGISocketPrefix run/wsgi
WSGIRestrictEmbedded On
752
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Listen 443
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile "/etc/pki/tls/certs/server.crt"
SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
WSGIScriptAlias / /opt/python/current/app/application.py
<Directory /opt/python/current/app>
Require all granted
</Directory>
</VirtualHost>
/etc/pki/tls/certs/server.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
container_commands:
01killhttpd:
command: "killall httpd"
02waitforhttpddeath:
command: "sleep 3"
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
753
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Topics
• Configure HTTPS for Ruby with Puma (p. 754)
• Configure HTTPS for Ruby with Passenger (p. 756)
Add the following snippet to your configuration file, replacing the certificate and private key material as
instructed, and save it in your source bundle's .ebextensions directory. The configuration file performs
the following tasks:
Configures the nginx server. This file is loaded when the nginx service starts.
/etc/pki/tls/certs/server.crt
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
754
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
• The container_commands key restarts the nginx server after everything is configured so that the
server uses the new https.conf file.
Example .ebextensions/https-instance.config
files:
/etc/nginx/conf.d/https.conf:
content: |
# HTTPS server
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://my_app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location /assets {
alias /var/app/current/public/assets;
gzip_static on;
gzip on;
expires max;
add_header Cache-Control public;
}
location /public {
alias /var/app/current/public;
gzip_static on;
gzip on;
expires max;
add_header Cache-Control public;
}
}
/etc/pki/tls/certs/server.crt:
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
755
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
container_commands:
01restart_nginx:
command: "service nginx restart"
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
1. Add the following snippet to your configuration file, replacing the certificate and private key
material as instructed, and save it in your source bundle's .ebextensions directory. The
configuration file performs the following tasks:
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces,
not tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
756
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the
contents of the private key used to create the certificate request or self-signed certificate.
Example .Ebextensions snippet for configuring HTTPS for Ruby with Passenger
files:
/etc/pki/tls/certs/server.crt:
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
Note
Avoid committing a configuration file that contains your private key to source control.
After you have tested the configuration and confirmed that it works, store your private
key in Amazon S3 and modify the configuration to download it during deployment. For
instructions, see Storing private keys securely in Amazon S3 (p. 767).
2. Create a text file and add the following JSON to the file. Save it in your source bundle's root
directory with the name passenger-standalone.json. This JSON file configures Passenger to
use HTTPS.
Important
This JSON file must not contain a byte order mark (BOM). If it does, the Passenger JSON
library will not read the file correctly and the Passenger service will not start.
Example passenger-standalone.json
{
"ssl" : true,
"ssl_port" : 443,
"ssl_certificate" : "/etc/pki/tls/certs/server.crt",
"ssl_certificate_key" : "/etc/pki/tls/certs/server.key"
}
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
757
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file, replacing the certificate and private key material as
instructed, and save it in your source bundle's .ebextensions directory. The configuration file performs
the following tasks:
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
/opt/elasticbeanstalk/hooks/appdeploy/post/99_start_httpd.sh
Example .ebextensions/https-instance.config
files:
/etc/pki/tls/certs/server.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
/opt/elasticbeanstalk/hooks/appdeploy/post/99_start_httpd.sh:
mode: "000755"
owner: root
758
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
group: root
content: |
#!/usr/bin/env bash
sudo service httpd restart
You must also configure your environment's proxy server to listen on port 443. The following Apache
2.4 configuration adds a listener on port 443. To learn more, see Configuring your Tomcat environment's
proxy server (p. 122).
Example .ebextensions/httpd/conf.d/ssl.conf
Listen 443
<VirtualHost *:443>
ServerName server-name
SSLEngine on
SSLCertificateFile "/etc/pki/tls/certs/server.crt"
SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
<Proxy *>
Require all granted
</Proxy>
ProxyPass / http://localhost:8080/ retry=0
ProxyPassReverse / http://localhost:8080/
ProxyPreserveHost on
ErrorLog /var/log/httpd/elasticbeanstalk-ssl-error_log
</VirtualHost>
Your certificate vendor may include intermediate certificates that you can install for better compatibility
with mobile clients. Configure Apache with an intermediate certificate authority (CA) bundle by
adding the following to your SSL configuration file (see Extending and overriding the default Apache
configuration (p. 124) for the location):
SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
SSLCertificateChainFile "/etc/pki/tls/certs/gd_bundle.crt"
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
• Add a new entry to the files key with the contents of the intermediate certificates:
files:
/etc/pki/tls/certs/gd_bundle.crt:
mode: "000400"
owner: root
group: root
content: |
-----BEGIN CERTIFICATE-----
First intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Second intermediate certificate
-----END CERTIFICATE-----
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
759
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Add the following snippet to your configuration file, replacing the certificate and private key
placeholders as instructed, and save it in the .ebextensions directory. The configuration file performs
the following tasks:
Creates the certificate file on the instance. Replace certificate file contents with the
contents of your certificate.
Note
YAML relies on consistent indentation. Match the indentation level when replacing
content in an example configuration file and ensure that your text editor uses spaces, not
tab characters, to indent.
If you have intermediate certificates, include them in server.crt after your site certificate.
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
first intermediate certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
second intermediate certificate
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key
Creates the private key file on the instance. Replace private key contents with the contents
of the private key used to create the certificate request or self-signed certificate.
760
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
• The container_commands key restarts the nginx server after everything is configured so that the
server loads the nginx configuration file.
Example .ebextensions/https-instance.config
files:
/etc/pki/tls/certs/server.crt:
content: |
-----BEGIN CERTIFICATE-----
certificate file contents
-----END CERTIFICATE-----
/etc/pki/tls/certs/server.key:
content: |
-----BEGIN RSA PRIVATE KEY-----
private key contents # See note below.
-----END RSA PRIVATE KEY-----
container_commands:
01restart_nginx:
command: "systemctl restart nginx"
Note
Avoid committing a configuration file that contains your private key to source control. After you
have tested the configuration and confirmed that it works, store your private key in Amazon S3
and modify the configuration to download it during deployment. For instructions, see Storing
private keys securely in Amazon S3 (p. 767).
Place the following in a file with the .conf extension in the .platform/nginx/conf.d/ directory
of your source bundle (for example, .platform/nginx/conf.d/https.conf). Replace app_port
with the port number that your application listens on. This example configures the nginx server to listen
on port 443 using SSL. For more information about these configuration files on the .NET Core on Linux
platform, see the section called “Proxy server” (p. 158).
Example .platform/nginx/conf.d/https.conf
# HTTPS server
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /etc/pki/tls/certs/server.crt;
ssl_certificate_key /etc/pki/tls/certs/server.key;
ssl_session_timeout 5m;
location / {
proxy_pass http://localhost:app_port;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
761
AWS Elastic Beanstalk Developer Guide
Terminate at the instance
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
Example .ebextensions/https-instance-dotnet.config
files:
"C:\\certs\\install-cert.ps1":
content: |
import-module webadministration
## Settings - replace the following values with your own
$bucket = "DOC-EXAMPLE-BUCKET" ## S3 bucket name
$certkey = "example.com.pfx" ## S3 object key for your PFX certificate
$pwdkey = "password.txt" ## S3 object key for a text file containing the
certificate's password
##
# Set variables
$certfile = "C:\cert.pfx"
$pwdfile = "C:\certs\pwdcontent"
Read-S3Object -BucketName $bucket -Key $pwdkey -File $pwdfile
$pwd = Get-Content $pwdfile -Raw
762
AWS Elastic Beanstalk Developer Guide
End-to-end encryption
# Install certificate
Echo "Installing cert..."
$securepwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
$cert = Import-PfxCertificate -FilePath $certfile cert:\localMachine\my -Password
$securepwd
# Update firewall
netsh advfirewall firewall add rule name="Open port 443" protocol=TCP localport=443
action=allow dir=OUT
commands:
00_install_ssl:
command: powershell -NoProfile -ExecutionPolicy Bypass -file C:\\certs\\install-
cert.ps1
In a single instance environment, you must also modify the instance's security group to allow traffic on
port 443. The following configuration file retrieves the security group's ID using an AWS CloudFormation
function (p. 708) and adds a rule to it.
Example .ebextensions/https-instance-single.config
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
CidrIp: 0.0.0.0/0
For a load-balanced environment, you configure the load balancer to either pass secure traffic through
untouched (p. 766), or decrypt and re-encrypt (p. 763) for end-to-end encryption.
763
AWS Elastic Beanstalk Developer Guide
End-to-end encryption
However, if you are developing an application that needs to comply with strict external regulations,
you might be required to secure all network connections. You can use the Elastic Beanstalk console
or configuration files (p. 683) to make your Elastic Beanstalk environment's load balancer connect
to backend instances securely to meet these requirements. The following procedure focuses on
configuration files.
First, add a secure listener to your load balancer (p. 738), if you haven't already.
You must also configure the instances in your environment to listen on the secure port and terminate
HTTPS connections. The configuration varies per platform. See Configuring your application to
terminate HTTPS connections at the instance (p. 741) for instructions. You can use a self-signed
certificate (p. 735) for the EC2 instances without issue.
Next, configure the listener to forward traffic using HTTPS on the secure port used by your application.
Use one of the following configuration files, based on the type of load balancer that your environment
uses.
.ebextensions/https-reencrypt-clb.config
Use this configuration file with a Classic Load Balancer. In addition to configuring the load balancer, the
configuration file also changes the default health check to use port 443 and HTTPS, to ensure that the
load balancer can connect securely.
option_settings:
aws:elb:listener:443:
InstancePort: 443
InstanceProtocol: HTTPS
aws:elasticbeanstalk:application:
Application Healthcheck URL: HTTPS:443/
.ebextensions/https-reencrypt-alb.config
option_settings:
aws:elbv2:listener:443:
DefaultProcess: https
ListenerEnabled: 'true'
Protocol: HTTPS
aws:elasticbeanstalk:environment:process:https:
Port: '443'
Protocol: HTTPS
.ebextensions/https-reencrypt-nlb.config
option_settings:
aws:elbv2:listener:443:
DefaultProcess: https
ListenerEnabled: 'true'
aws:elasticbeanstalk:environment:process:https:
Port: '443'
The DefaultProcess option is named this way because of Application Load Balancers, which can have
nondefault listeners on the same port for traffic to specific paths (see Application Load Balancer (p. 536)
for details). For a Network Load Balancer the option specifies the only target process for this listener.
In this example, we named the process https because it listens to secure (HTTPS) traffic. The listener
sends traffic to the process on the designated port using the TCP protocol, because a Network Load
764
AWS Elastic Beanstalk Developer Guide
End-to-end encryption
Balancer works only with TCP. This is okay, because network traffic for HTTP and HTTPS is implemented
on top of TCP.
Note
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options.
You must remove these settings if you want to use configuration files to configure the same. See
Recommended values (p. 614) for details.
In the next task, you need to modify the load balancer's security group to allow traffic. Depending on the
Amazon Virtual Private Cloud (Amazon VPC) in which you launch your environment—the default VPC
or a custom VPC—the load balancer's security group will vary. In a default VPC, Elastic Load Balancing
provides a default security group that all load balancers can use. In an Amazon VPC that you create,
Elastic Beanstalk creates a security group for the load balancer to use.
To support both scenarios, you can create a security group and tell Elastic Beanstalk to use it. The
following configuration file creates a security group and attaches it to the load balancer.
.ebextensions/https-lbsecuritygroup.config
option_settings:
# Use the custom security group for the load balancer
aws:elb:loadbalancer:
SecurityGroups: '`{ "Ref" : "loadbalancersg" }`'
ManagedSecurityGroup: '`{ "Ref" : "loadbalancersg" }`'
Resources:
loadbalancersg:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: load balancer security group
VpcId: vpc-########
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
SecurityGroupEgress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
Replace the highlighted text with your default or custom VPC ID. The previous example includes ingress
and egress over port 80 to allow HTTP connections. You can remove those properties if you want to
allow only secure connections.
Finally, add ingress and egress rules that allow communication over port 443 between the load
balancer's security group and the instances' security group.
.ebextensions/https-backendsecurity.config
Resources:
# Add 443-inbound to instance security group (AWSEBSecurityGroup)
httpsFromLoadBalancerSG:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
765
AWS Elastic Beanstalk Developer Guide
TCP Passthrough
ToPort: 443
FromPort: 443
SourceSecurityGroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]}
# Add 443-outbound to load balancer security group (loadbalancersg)
httpsToBackendInstances:
Type: AWS::EC2::SecurityGroupEgress
Properties:
GroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
DestinationSecurityGroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
Doing this separately from security group creation enables you to restrict the source and destination
security groups without creating a circular dependency.
After you have completed all the previous tasks, the load balancer connects to your backend instances
securely using HTTPS. The load balancer doesn't care if your instance's certificate is self-signed or issued
by a trusted certificate authority, and will accept any certificate presented to it.
You can change this behavior by adding policies to the load balancer that tell it to trust only a specific
certificate. The following configuration file creates two policies. One policy specifies a public certificate,
and the other tells the load balancer to only trust that certificate for connections to instance port 443.
.ebextensions/https-backendauth.config
option_settings:
# Backend Encryption Policy
aws:elb:policies:backendencryption:
PublicKeyPolicyNames: backendkey
InstancePorts: 443
# Public Key Policy
aws:elb:policies:backendkey:
PublicKey: |
-----BEGIN CERTIFICATE-----
################################################################
################################################################
################################################################
################################################################
################################################
-----END CERTIFICATE-----
Replace the highlighted text with the contents of your EC2 instance's public certificate.
First configure your environment's EC2 instances to terminate HTTPS (p. 741). Test the configuration on
a single instance environment to make sure everything works before adding a load balancer to the mix.
Add a configuration file (p. 683) to your project to configure a listener on port 443 that passes TCP
packets as-is to port 443 on backend instances:
.ebextensions/https-lb-passthrough.config
option_settings:
766
AWS Elastic Beanstalk Developer Guide
Store keys securely
aws:elb:listener:443:
ListenerProtocol: TCP
InstancePort: 443
InstanceProtocol: TCP
In a default Amazon Virtual Private Cloud (Amazon VPC), you also need to add a rule to the instances'
security group to allow inbound traffic on 443 from the load balancer:
.ebextensions/https-instance-securitygroup.config
Resources:
443inboundfromloadbalancer:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443
FromPort: 443
SourceSecurityGroupName: { "Fn::GetAtt": ["AWSEBLoadBalancer",
"SourceSecurityGroup.GroupName"] }
In a custom VPC, Elastic Beanstalk updates the security group configuration for you.
The following example shows the Resources (p. 703) and files (p. 689) sections of a configuration
file (p. 683) downloads a private key file from an Amazon S3 bucket.
Example .ebextensions/privatekey.config
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["elasticbeanstalk-us-west-2-123456789012"]
roleName:
"Fn::GetOptionSetting":
Namespace: "aws:autoscaling:launchconfiguration"
OptionName: "IamInstanceProfile"
DefaultValue: "aws-elasticbeanstalk-ec2-role"
files:
# Private key
"/etc/pki/tls/certs/server.key":
mode: "000400"
owner: root
group: root
authentication: "S3Auth"
source: https://elasticbeanstalk-us-west-2-123456789012.s3.us-west-2.amazonaws.com/
server.key
Replace the bucket name and URL in the example with your own. The first entry in this file adds an
authentication method named S3Auth to the environment's Auto Scaling group's metadata. If you
have configured a custom instance profile (p. 21) for your environment, that will be used, otherwise
the default value of aws-elasticbeanstalk-ec2-role is applied. The default instance profile
767
AWS Elastic Beanstalk Developer Guide
HTTP to HTTPS redirection
has permission to read from the Elastic Beanstalk storage bucket. If you use a different bucket, add
permissions to the instance profile (p. 859).
The second entry uses the S3Auth authentication method to download the private key from the
specified URL and save it to /etc/pki/tls/certs/server.key. The proxy server can then read the
private key from this location to terminate HTTPS connections at the instance (p. 741).
The instance profile assigned to your environment's EC2 instances must have permission to read the key
object from the specified bucket. Verify that the instance profile has permission (p. 858) to read the
object in IAM, and that the permissions on the bucket and object do not prohibit the instance profile.
To configure redirection, you first configure your environment to handle HTTPS traffic. Then you redirect
HTTP traffic to HTTPS. These two steps are discussed in the following subsections.
• Load-balanced environment – Configure your load balancer to terminate HTTPS (p. 738).
• Single-instance environment – Configure your application to terminate HTTPS connections at the
instance (p. 741). This configuration depends on your environment's platform.
• Configure instance web servers – This method works on any web server environment. Configure web
servers on your Amazon Elastic Compute Cloud (Amazon EC2) instances to respond to HTTP traffic
with an HTTP redirection response status. This configuration depends on your environment's platform.
Find the folder for your platform in the https-redirect collection on GitHub, and use the example
configuration file in that folder.
If your environment uses Elastic Load Balancing health checks (p. 774), the load balancer expects
a healthy instance to respond to the HTTP health check messages with HTTP 200 (OK) responses.
Therefore, your web server shouldn't redirect these messages to HTTPS. The example configuration
files in https-redirect handle this requirement correctly.
• Configure load balancer – This method works if you have a load-balanced environment that uses an
Application Load Balancer (p. 536). Application Load Balancer can send redirection responses as HTTP
768
AWS Elastic Beanstalk Developer Guide
HTTP to HTTPS redirection
traffic comes in. In this case, you don't need to configure redirection on your environment's instances.
We have two example configuration files on GitHub that show how to configure Application Load
Balancer for redirection. The alb-http-to-https-redirection-full.config configuration file
creates an HTTPS listener on port 443, and modifies the default port 80 listener to redirect incoming
HTTP traffic to HTTPS. The alb-http-to-https-redirection.config configuration file expects
the 443 listener to be defined (you can use standard Elastic Beanstalk configuration namespaces, or
the Elastic Beanstalk console). Then it takes care of modifying the port 80 listener for redirection.
769
AWS Elastic Beanstalk Developer Guide
Monitoring console
Monitoring an environment
When you are running a production website, it is important to know that your application is available
and responding to requests. To assist with monitoring your application’s responsiveness, Elastic
Beanstalk provides features that monitor statistics about your application and create alerts that trigger
when thresholds are exceeded.
Topics
• Monitoring environment health in the AWS management console (p. 770)
• Basic health reporting (p. 773)
• Enhanced health reporting and monitoring (p. 776)
• Manage alarms (p. 811)
• Viewing an Elastic Beanstalk environment's change history (p. 814)
• Viewing an Elastic Beanstalk environment's event stream (p. 816)
• Listing and connecting to server instances (p. 818)
• Viewing logs from Amazon EC2 instances in your Elastic Beanstalk environment (p. 820)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Monitoring.
The Monitoring page shows you overall statistics about your environment, such as CPU utilization and
average latency. In addition to the overall statistics, you can view monitoring graphs that show resource
usage over time. You can click any of the graphs to view more detailed information.
Note
By default, only basic CloudWatch metrics are enabled, which return data in five-minute periods.
You can enable more granular one-minute CloudWatch metrics by editing your environment's
configuration settings.
Overview
An overview of the environment's health is shown near the top of the screen.
770
AWS Elastic Beanstalk Developer Guide
Monitoring graphs
The overview section shows a customizable summary of the activity in your environment over period of
time. Choose the Period drop-down and select a length of time to view information for a period between
one minute and one day.
Monitoring graphs
Below the overview are graphs that show data about overall environment health over a period of time.
Choose the Period drop-down and select a length of time to set the time between each two plot points
to a period between one minute and one day. Choose the Time Range drop-down and select a length of
time to set the graph time axis to a period between three hours and two weeks.
771
AWS Elastic Beanstalk Developer Guide
Customizing the monitoring console
To remove any of the existing items, choose the in the top right corner.
772
AWS Elastic Beanstalk Developer Guide
Basic health reporting
For more information about metrics and dimensions for each resource, see Amazon CloudWatch Metrics,
Namespaces, and Dimensions Reference in the Amazon CloudWatch User Guide.
Elastic Load Balancing and Amazon EC2 metrics are enabled for all environments.
With enhanced health (p. 776), the EnvironmentHealth metric is enabled and a graph is added to
the monitoring console automatically. Additional metrics become available for use in the monitoring
console when you enabled them in the environment configuration. Enhanced health also adds the Health
page (p. 788) to the management console.
Note
When you enable additional CloudWatch metrics for your environment, it takes a few minutes
for them to start being reported and appear in the list of metrics that you use to add graphs and
overview stats.
See Publishing Amazon CloudWatch custom metrics for an environment (p. 800) for a list of available
enhanced health metrics.
Prior to version 2 Linux platform versions, the only health reporting system was basic health. The
basic health reporting system provides information about the health of instances in an Elastic
Beanstalk environment based on health checks performed by Elastic Load Balancing for load-balanced
environments, or Amazon Elastic Compute Cloud for single-instance environments.
In addition to checking the health of your EC2 instances, Elastic Beanstalk also monitors the other
resources in your environment and reports missing or incorrectly configured resources that can cause
your environment to become unavailable to users.
Metrics gathered by the resources in your environment is published to Amazon CloudWatch in five
minute intervals. This includes operating system metrics from EC2, request metrics from Elastic Load
Balancing. You can view graphs based on these CloudWatch metrics on the Monitoring page (p. 770)
of the environment console. For basic health, these metrics are not used to determine an environment's
health.
Topics
• Health colors (p. 773)
• Elastic Load Balancing health checks (p. 774)
• Single instance and worker tier environment health checks (p. 774)
• Additional checks (p. 775)
• Amazon CloudWatch metrics (p. 775)
Health colors
Elastic Beanstalk reports the health of a web server environment depending on how the application
running in it responds to the health check. Elastic Beanstalk uses one of four colors to describe status, as
shown in the following table:
773
AWS Elastic Beanstalk Developer Guide
Elastic Load Balancing health checks
Color Description
Green Your environment has passed the most recent health check. At least one
instance in your environment is available and taking requests.
Yellow Your environment has failed one or more health checks. Some requests to
your environment are failing.
Red Your environment has failed three or more health checks, or an environment
resource has become unavailable. Requests are consistently failing.
These descriptions only apply to environments using basic health reporting. See Health colors and
statuses (p. 792) for details related to enhanced health.
You can choose to override this setting by specifying an existing resource in your application. If you
specify a path, such as /health, the health check URL is set to HTTP:80/health. The health check
URL should be set to a path that is always served by your application. If it is set to a static page that is
served or cached by the web server in front of your application, health checks will not reveal issues with
the application server or web container. For instructions on modifying your health check URL, see Health
check (p. 534).
If a health check URL is configured, Elastic Load Balancing expects a GET request that it sends to return
a response of 200 OK. The application fails the health check if it fails to respond within 5 seconds or
if it responds with any other HTTP status code. After 5 consecutive health check failures, Elastic Load
Balancing takes the instance out of service.
For more information about Elastic Load Balancing health checks, see Health Check in the Elastic Load
Balancing User Guide.
Note
Configuring a health check URL does not change the health check behavior of an environment's
Auto Scaling group. An unhealthy instance is removed from the load balancer, but is not
automatically replaced by Amazon EC2 Auto Scaling unless you configure Amazon EC2 Auto
Scaling to use the Elastic Load Balancing health check as a basis for replacing instances. To
configure Amazon EC2 Auto Scaling to replace instances that fail an Elastic Load Balancing
health check, see Auto Scaling health check setting (p. 525).
For more information on Amazon EC2 instance status checks, see Monitoring Instances with Status
Checks in the Amazon EC2 User Guide for Linux Instances.
774
AWS Elastic Beanstalk Developer Guide
Additional checks
Additional checks
In addition to Elastic Load Balancing health checks, Elastic Beanstalk monitors resources in your
environment and changes health status to red if they fail to deploy, are not configured correctly, or
become unavailable. These checks confirm that:
• The environment's Auto Scaling group is available and has a minimum of at least one instance.
• The environment's security group is available and is configured to allow incoming traffic on port 80.
• The environment CNAME exists and is pointing to the right load balancer.
• In a worker environment, the Amazon Simple Queue Service (Amazon SQS) queue is being polled at
least once every three minutes.
For example, EC2 publishes the following metrics for the instances in your environment's Auto Scaling
group:
CPUUtilization
Number of bytes read and written, and number of read and write operations.
NetworkIn, NetworkOut
Elastic Load Balancing publishes the following metrics for your environment's load balancer:
BackendConnectionErrors
Number of connection failures between the load balancer and environment instances.
HTTPCode_Backend_2XX, HTTPCode_Backend_4XX
Number of successful (2XX) and client error (4XX) response codes generated by instances in your
environment.
Latency
Number of seconds between when the load balancer relays a request to an instance and when the
response is received.
RequestCount
These lists are not comprehensive. For a full list of metrics that can be reported for these resources, see
the following topics in the Amazon CloudWatch Developer Guide:
775
AWS Elastic Beanstalk Developer Guide
Enhanced health reporting and monitoring
Metrics
Namespace Topic
To enable the daemon to publish metrics, the environment's instance profile must have permission to
call cloudwatch:PutMetricData. This permission is included in the default instance profile. For more
information, see Managing Elastic Beanstalk instance profiles (p. 855).
In addition to changes in how health color works, enhanced health adds a status descriptor that provides
an indicator of the severity of issues observed when an environment is yellow or red. When more
information is available about the current status, you can choose the Causes button to view detailed
health information on the health page (p. 787).
776
AWS Elastic Beanstalk Developer Guide
Enhanced health reporting and monitoring
To provide detailed health information about the Amazon EC2 instances running in your environment,
Elastic Beanstalk includes a health agent (p. 779) in the Amazon Machine Image (AMI) for each
platform version that supports enhanced health. The health agent monitors web server logs and system
metrics and relays them to the Elastic Beanstalk service. Elastic Beanstalk analyzes these metrics and
data from Elastic Load Balancing and Amazon EC2 Auto Scaling to provide an overall picture of an
environment's health.
In addition to collecting and presenting information about your environment's resources, Elastic
Beanstalk monitors the resources in your environment for several error conditions and provides
notifications to help you avoid failures and resolve configuration issues. Factors that influence your
environment's health (p. 779) include the results of each request served by your application, metrics
from your instances' operating system, and the status of the most recent deployment.
You can view health status in real time by using the environment overview (p. 787) page of the
Elastic Beanstalk console or the eb health (p. 979) command in the Elastic Beanstalk command line
interface (p. 956) (EB CLI). To record and track environment and instance health over time, you can
configure your environment to publish the information gathered by Elastic Beanstalk for enhanced
777
AWS Elastic Beanstalk Developer Guide
Enhanced health reporting and monitoring
health reporting to Amazon CloudWatch as custom metrics. CloudWatch charges for custom metrics
apply to all metrics other than EnvironmentHealth, which is free of charge.
Enhanced health reporting requires a version 2 or newer platform version (p. 29). To monitor resources
and publish metrics, your environment must have both an instance profile and service (p. 776) role. The
Multicontainer Docker platform doesn't include a web server by default, but can be used with enhanced
health reporting if you configure your web server to provide logs in the proper format (p. 807).
Windows platform notes
• This feature isn't available on Windows Server platform versions earlier than version 2 (v2).
• When you enable enhanced health reporting on a Windows Server environment, don't change
IIS logging configuration. For enhanced health monitoring to work correctly, IIS logging must
be configured with the W3C format and the ETW event only or Both log file and ETW event
log event destinations.
In addition, don't disable or stop the Elastic Beanstalk health agent (p. 779) Windows service
on any of your environment's instances. To collect and report enhanced health information on
an instance, this service should be enabled and running.
Enhanced health requires the environment to have an instance profile. The instance profile should
have roles that provide permissions for your environment instances to collect and report enhanced
health information. The first time you create an environment with a v2 platform version in the Elastic
Beanstalk console, Elastic Beanstalk prompts you to create the required roles and enables enhanced
health reporting by default. Continue reading for details on how enhanced health reporting works, or see
Enabling Elastic Beanstalk enhanced health reporting (p. 784) to get started using it right away.
Amazon Linux 2 platforms require instance profiles, so they can support enhanced health
unconditionally. When you create an environment using an Amazon Linux 2 platform, Elastic Beanstalk
always enables enhanced health. This is true regardless of how you create the environment—using the
Elastic Beanstalk console, the EB CLI, the AWS CLI, or the API.
Topics
• The Elastic Beanstalk health agent (p. 779)
• Factors in determining instance and environment health (p. 779)
• Health check rule customization (p. 781)
• Enhanced health roles (p. 781)
• Enhanced health authorization (p. 782)
• Enhanced health events (p. 782)
• Enhanced health reporting behavior during updates, deployments, and scaling (p. 783)
• Enabling Elastic Beanstalk enhanced health reporting (p. 784)
• Enhanced health monitoring with the environment management console (p. 787)
• Health colors and statuses (p. 792)
• Instance metrics (p. 794)
• Configuring enhanced health rules for an environment (p. 796)
• Publishing Amazon CloudWatch custom metrics for an environment (p. 800)
• Using enhanced health reporting with the Elastic Beanstalk API (p. 805)
• Enhanced health log format (p. 807)
• Notifications and troubleshooting (p. 809)
778
AWS Elastic Beanstalk Developer Guide
The Elastic Beanstalk health agent
The health agent reports similar metrics to those published to CloudWatch (p. 775) by Amazon EC2
Auto Scaling and Elastic Load Balancing as part of basic health reporting (p. 773), including CPU load,
HTTP codes, and latency. The health agent, however, reports directly to Elastic Beanstalk, with greater
granularity and frequency than basic health reporting.
For basic health, these metrics are published every five minutes and can be monitored with graphs in the
environment management console. With enhanced health, the Elastic Beanstalk health agent reports
metrics to Elastic Beanstalk every 10 seconds. Elastic Beanstalk uses the metrics provided by the health
agent to determine the health status of each instance in the environment and, combined with other
factors (p. 779), to determine the overall health of the environment.
The overall health of the environment can be viewed in real time in the environment overview page of
the Elastic Beanstalk console, and is published to CloudWatch by Elastic Beanstalk every 60 seconds.
You can view detailed metrics reported by the health agent in real time with the eb health (p. 979)
command in the EB CLI (p. 956).
For an additional charge, you can choose to publish individual instance and environment-level metrics to
CloudWatch every 60 seconds. Metrics published to CloudWatch can then be used to create monitoring
graphs (p. 772) in the environment management console (p. 396).
Enhanced health reporting only incurs a charge if you choose to publish enhanced health metrics to
CloudWatch. When you use enhanced health, you still get the basic health metrics published for free,
even if you don't choose to publish enhanced health metrics.
See Instance metrics (p. 794) for details on the metrics reported by the health agent. For details on
publishing enhanced health metrics to CloudWatch, see Publishing Amazon CloudWatch custom metrics
for an environment (p. 800).
For example, when you deploy a new version of an application to an environment that is running
multiple instances, you might see messages similar to the following as you monitor the environment's
health with the EB CLI (p. 979).
id status cause
Overall Info Command is executing on 3 out of 5 instances
779
AWS Elastic Beanstalk Developer Guide
Factors in determining instance and environment health
In this example, the overall status of the environment is Ok and the cause of this status is that the
Command is executing on 3 out of 5 instances. Three of the instances in the environment have the status
Pending, indicating that an operation is in progress.
When an operation completes, Elastic Beanstalk reports additional information about the operation. For
the example, Elastic Beanstalk displays the following information about an instance that has already
been updated with the new version of the application:
Instance health information also includes details about the most recent deployment to each instance
in your environment. Each instance reports a deployment ID and status. The deployment ID is an
integer that increases by one each time you deploy a new version of your application or change settings
for on-instance configuration options, such as environment variables. You can use the deployment
information to identify instances that are running the wrong version of your application after a failed
rolling deployment (p. 444).
In the cause column, Elastic Beanstalk includes informational messages about successful operations
and other healthy states across multiple health checks, but they don't persist indefinitely. Causes for
unhealthy environment statuses persist until the environment returns to a healthy status.
Command timeout
Elastic Beanstalk applies a command timeout from the time an operation begins to allow an instance
to transition into a healthy state. This command timeout is set in your environment's update and
deployment configuration (in the aws:elasticbeanstalk:command (p. 649) namespace) and defaults to 10
minutes.
During rolling updates, Elastic Beanstalk applies a separate timeout to each batch in the
operation. This timeout is set as part of the environment's rolling update configuration (in the
aws:autoscaling:updatepolicy:rollingupdate (p. 642) namespace). If all instances in the batch are healthy
within the command timeout, the operation continues to the next batch. If not, the operation fails.
Note
If your application does not pass health checks with an OK status but is stable at
a different level, you can set the HealthCheckSuccessThreshold option in the
aws:elasticbeanstalk:command namespace (p. 649) to change the level at which Elastic
Beanstalk considers an instance to be healthy.
For a web server environment to be considered healthy, each instance in the environment or batch must
pass 12 consecutive health checks over the course of two minutes. For a worker tier environment, each
instance must pass 18 health checks. Before the command times out, Elastic Beanstalk doesn't lower an
environment's health status when health checks fail. If the instances in the environment become healthy
within the command timeout, the operation succeeds.
HTTP requests
When no operation is in progress on an environment, the primary source of information about instance
and environment health is the web server logs for each instance. To determine the health of an instance
780
AWS Elastic Beanstalk Developer Guide
Health check rule customization
and the overall health of the environment, Elastic Beanstalk considers the number of requests, the result
of each request, and the speed at which each request was resolved.
On Linux-based platforms, Elastic Beanstalk reads and parses web server logs to get information about
HTTP requests. On the Windows Server platform, Elastic Beanstalk receives this information directly
from the IIS web server (p. 796).
Your environment might not have an active web server. For example, the Multicontainer Docker platform
doesn't include a web server. Other platforms include a web server, and your application might disable it.
In these cases, your environment requires additional configuration to provide the Elastic Beanstalk health
agent (p. 779) with logs in the format that it needs to relay health information to the Elastic Beanstalk
service. See Enhanced health log format (p. 807) for details.
See Instance metrics (p. 794) for details on the metrics reported by the health agent.
When you create an Elastic Beanstalk environment using the Elastic Beanstalk console or the EB CLI,
Elastic Beanstalk creates a default service role and attaches required managed policies to a default
instance profile for your environment.
If you use the API, an SDK, or the AWS CLI to create environments, you must create these roles in
advance, and specify them during environment creation to use enhanced health. For instructions
on creating appropriate roles for your environments, see Service roles, instance profiles, and user
policies (p. 20).
We recommend that you use managed policies for your instance profile and service role. Managed
policies are AWS Identity and Access Management (IAM) policies that Elastic Beanstalk maintains. Using
managed policies guarantees that your environment has all permissions it needs to function properly.
781
AWS Elastic Beanstalk Developer Guide
Enhanced health authorization
To authorize the action, include the following statement in your instance profile.
{
"Sid": "ElasticBeanstalkHealthAccess",
"Action": [
"elasticbeanstalk:PutInstanceStatistics"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:*:*:application/*",
"arn:aws:elasticbeanstalk:*:*:environment/*"
]
}
If you don’t want to use enhanced health authorization at this time, disable it by
setting set the EnhancedHealthAuthEnabled option in the the section called
“aws:elasticbeanstalk:healthreporting:system” (p. 656) namespace to false. If this option is disabled,
the permissions described previously aren’t required. You can remove them from the instance profile for
least privilege access (p. 1058) to your applications and environments.
Note
Previously the default setting for EnhancedHealthAuthEnabled was false, which
resulted in authorization for the elasticbeanstalk:PutInstanceStatistics
action also being disabled by default. To enable this action for an existing
environment, set the EnhancedHealthAuthEnabled option in the the section called
“aws:elasticbeanstalk:healthreporting:system” (p. 656) namespace to true. You can configure
this option by using an option setting (p. 684) in a configuration file (p. 683).
782
AWS Elastic Beanstalk Developer Guide
Enhanced health reporting behavior
during updates, deployments, and scaling
When transitioning to a worse state, the enhanced health event includes a message indicating the
transition cause.
Not all changes in status at an instance level cause Elastic Beanstalk to emit an event. To prevent false
alarms, Elastic Beanstalk generates a health-related event only if an issue persists across multiple checks.
Real-time environment-level health information, including status, color, and cause, is available in the
environment overview (p. 398) page of the Elastic Beanstalk console and the EB CLI (p. 956). By
attaching the EB CLI to your environment and running the eb health (p. 979) command, you can also
view real-time statuses from each of the instances in your environment.
Enhanced health reporting can also highlight the need to set a proper health check URL (p. 534) for
Elastic Load Balancing. When your environment scales up to meet demand, new instances will start
taking requests as soon as they pass enough ELB health checks. If a health check URL is not configured,
this can be as little as 20 seconds after a new instance is able to accept a TCP connection.
If your application hasn't finished starting up by the time the load balancer declares it healthy enough
to receive traffic, you will see a flood of failed requests, and your environment will start to fail health
checks. A health check URL that hits a path served by your application can prevent this issue. ELB health
checks won't pass until a GET request to the health check URL returns a 200 status code.
783
AWS Elastic Beanstalk Developer Guide
Enable enhanced health
Enhanced health reporting requires an instance profile (p. 21) and service role (p. 20) with the standard
set of permissions. When you create an environment in the Elastic Beanstalk console, Elastic Beanstalk
creates the required roles automatically. See Getting started using Elastic Beanstalk (p. 3) for instructions
on creating your first environment.
Topics
• Enabling enhanced health reporting using the Elastic Beanstalk console (p. 784)
• Enabling enhanced health reporting using the EB CLI (p. 786)
• Enabling enhanced health reporting using a configuration file (p. 787)
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Monitoring configuration category, choose Edit.
5. Under Health reporting, for System, choose Enhanced.
784
AWS Elastic Beanstalk Developer Guide
Enable enhanced health
Note
The options for enhanced health reporting don't appear if you are using an unsupported
platform or version (p. 776).
6. Choose Apply.
The Elastic Beanstalk console defaults to enhanced health reporting when you create a new environment
with a version 2 (v2) platform version. You can disable enhanced health reporting by changing the health
reporting option during environment creation.
To disable enhanced health reporting when creating an environment using the Elastic
Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. Create an application (p. 377) or select an existing one.
3. Create an environment (p. 407). On the Create a new environment page, before choosing Create
environment, choose Configure more options.
4. In the Monitoring configuration category, choose Edit.
5. Under Health reporting, for System, choose Basic.
785
AWS Elastic Beanstalk Developer Guide
Enable enhanced health
6. Choose Save.
You can specify a different service role by name by using the --service-role option.
If you have an environment running with basic health reporting on a v2 platform version and you want
to switch to enhanced health, follow these steps.
To enable enhanced health on a running environment using the EB CLI (p. 956)
1. Use the eb config command to open the configuration file in the default text editor.
~/project$ eb config
aws:elasticbeanstalk:environment:
EnvironmentType: LoadBalanced
ServiceRole: aws-elasticbeanstalk-service-role
aws:elasticbeanstalk:healthreporting:system:
786
AWS Elastic Beanstalk Developer Guide
Health console
SystemType: enhanced
~/project$ eb config
Printing Status:
INFO: Environment update is starting.
INFO: Health reporting type changed to ENHANCED.
INFO: Updating environment no-role-test's configuration settings.
Example .ebextensions/enhanced-health.config
option_settings:
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
aws:autoscaling:launchconfiguration:
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
aws:elasticbeanstalk:environment:
ServiceRole: aws-elasticbeanstalk-service-role
If you created your own instance profile or service role, replace the highlighted text with the names of
those roles.
Topics
• Environment overview (p. 787)
• Environment health page (p. 788)
• Monitoring page (p. 792)
Environment overview
The environment overview (p. 398) displays the health status (p. 792) of the environment and lists
events that provide information about recent changes in health status.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
787
AWS Elastic Beanstalk Developer Guide
Health console
Note
If you have many environments, use the search bar to filter the environment list.
For detailed information about the current environment's health, open the Health page by choosing
Causes. Alternatively, in the navigation pane, choose Health.
The following image shows the Health page for a Linux environment.
788
AWS Elastic Beanstalk Developer Guide
Health console
The following image shows the Health page for a Windows environment. Notice that CPU metrics are
different from those on a Linux environment.
At the top of the page you can see the total number of environment instances, as well as the number of
instances per status. To display only instances that have a particular status, chooseFilter By, and then
select a status (p. 792).
789
AWS Elastic Beanstalk Developer Guide
Health console
To reboot or terminate an unhealthy instance, choose Instance Actions, and then choose Reboot or
Terminate.
Elastic Beanstalk updates the Health page every 10 seconds. It reports information about environment
and instance health.
For each Amazon EC2 instance in the environment, the page displays the instance's ID and
status (p. 792), the amount of time since the instance was launched, the ID of the most recent
deployment executed on the instance, the responses and latency of requests that the instance served,
and load and CPU utilization information. The Overall row displays average response and latency
information for the entire environment.
The page displays many details in a very wide table. To hide some of the columns, choose
(Preferences). Select or clear column names, and then choose Confirm.
Choose the Instance ID of any instance to view more information about the instance, including its
Availability Zone and instance type.
790
AWS Elastic Beanstalk Developer Guide
Health console
Choose the Deployment ID of any instance to view information about the last deployment (p. 441) to
the instance.
791
AWS Elastic Beanstalk Developer Guide
Health colors and statuses
• Deployment ID—The unique identifier for the deployment (p. 441). Deployment IDs starts at 1 and
increase by one each time you deploy a new application version or change configuration settings that
affect the software or operating system running on the instances in your environment.
• Version—The version label of the application source code used in the deployment.
• Status—The status of the deployment, which can be In Progress, Deployed, or Failed.
• Time— For in-progress deployments, the time that the deployment started. For completed
deployments, the time that the deployment ended.
If you enable X-Ray integration (p. 595) on your environment and instrument your application with the
AWS X-Ray SDK, the Health page adds links to the AWS X-Ray console in the overview row.
Choose a link to view traces related to the highlighted statistic in the AWS X-Ray console.
Monitoring page
The Monitoring page displays summary statistics and graphs for the custom Amazon CloudWatch
metrics generated by the enhanced health reporting system. See Monitoring environment health in the
AWS management console (p. 770) for instructions on adding graphs and statistics to this page.
Elastic Beanstalk displays the health information for the overall environment (color, status, and cause) in
the environment management console (p. 396). This information is also available in the EB CLI. Health
status and cause messages for individual instances are updated every 10 seconds and are available from
the EB CLI (p. 956) when you view health status with eb health (p. 979).
Elastic Beanstalk uses changes in instance health to evaluate environment health, but does not
immediately change environment health status. When an instance fails health checks at least three times
in any one-minute period, Elastic Beanstalk may downgrade the health of the environment. Depending
on the number of instances in the environment and the issue identified, one unhealthy instance can
cause Elastic Beanstalk to display an informational message or to change the environment's health status
from green (OK) to yellow (Warning) or red (Degraded or Severe).
792
AWS Elastic Beanstalk Developer Guide
Health colors and statuses
OK (green)
This status is displayed when:
• An instance is passing health checks and the health agent is not reporting any problems.
• Most instances in the environment are passing health checks and the health agent is not reporting
major issues.
• An instance is passing health checks and is completing requests normally.
Example: Your environment was recently deployed and is taking requests normally. Five percent of
requests are returning 400 series errors. Deployment completed normally on each instance.
Message (instance): Application deployment completed 23 seconds ago and took 26 seconds.
Warning (yellow)
This status is displayed when:
• The health agent is reporting a moderate number of request failures or other issues for an instance or
environment.
• An operation is in progress on an instance and is taking a very long time.
Degraded (red)
This status is displayed when the health agent is reporting a high number of request failures or other
issues for an instance or environment.
Message (environment): 4 active instances is below Auto Scaling group minimum size 5.
Severe (red)
This status is displayed when the health agent is reporting a very high number of request failures or
other issues for an instance or environment.
Example: Elastic Beanstalk is unable to contact the load balancer to get instance health.
Message (environment): ELB health is failing or not available for all instances. None of the instances are
sending data. Unable to assume role "arn:aws:iam::123456789012:role/aws-elasticbeanstalk-service-
role". Verify that the role exists and is configured correctly.
Message (Instances): Instance ELB health has not been available for 37 minutes. No data. Last seen 37
minutes ago.
Info (green)
This status is displayed when:
793
AWS Elastic Beanstalk Developer Guide
Instance metrics
Pending (grey)
This status is displayed when an operation is in progress on an instance within the command
timeout (p. 780).
Example: You have recently created the environment and instances are being bootstrapped.
Unknown (grey)
This status is displayed when Elastic Beanstalk and the health agent are reporting an insufficient amount
of data on an instance.
Suspended (grey)
This status is displayed when Elastic Beanstalk stopped monitoring the environment's health. The
environment might not work correctly. Some severe health conditions, if they last a long time, cause
Elastic Beanstalk to transition the environment to the Suspended status.
Example: Elastic Beanstalk can't access the environment's service role (p. 860).
Example: The Auto Scaling group (p. 511) that Elastic Beanstalk created for the environment has been
deleted.
Message: Environment health has transitioned from OK to Severe. There are no instances. Auto Scaling
group desired capacity is set to 1.
Instance metrics
Instance metrics provide information about the health of instances in your environment. The Elastic
Beanstalk health agent (p. 779) runs on each instance. It gathers and relays metrics about instances
to Elastic Beanstalk, which analyzes the metrics to determine the health of the instances in your
environments.
The on-instance Elastic Beanstalk health agent gathers metrics about instances from web servers and
the operating system. To get web server information on Linux-based platforms, Elastic Beanstalk reads
and parses web server logs. On the Windows Server platform, Elastic Beanstalk receives this information
directly from the IIS web server. Web servers provide information about incoming HTTP requests: how
many requests came in, how many resulted in errors, and how long they took to resolve. The operating
system provides snapshot information about the state of the instances' resources: the CPU load and
distribution of time spent on each process type.
The health agent gathers web server and operating system metrics and relays them to Elastic Beanstalk
every 10 seconds. Elastic Beanstalk analyzes the data and uses the results to update the health status for
each instance and the environment.
Topics
• Web server metrics (p. 795)
794
AWS Elastic Beanstalk Developer Guide
Instance metrics
For more information on the log format used by Elastic Beanstalk, see Enhanced health log
format (p. 807).
On the Windows Server platform, Elastic Beanstalk adds a module to the IIS web server's request
pipeline and captures metrics about HTTP request times and response codes. The module sends these
metrics to the on-instance health agent using a high-performance interprocess communication (IPC)
channel. For implementation details, see Web server metrics capture in IIS on Windows server (p. 796).
RequestCount
Number of requests handled by the web server per second over the last 10 seconds. Shown as an
average r/sec (requests per second) in the EB CLI and Environment health page (p. 788).
Status2xx, Status3xx, Status4xx, Status5xx
Number of requests that resulted in each type of status code over the last 10 seconds. For example,
successful requests return a 200 OK, redirects are a 301, and a 404 is returned if the URL entered
doesn't match any resources in the application.
The EB CLI and Environment health page (p. 788) show these metrics both as a raw number of
requests for instances, and as a percentage of overall requests for environments.
p99.9, p99, p95, p90, p85, p75, p50, p10
Average latency for the slowest x percent of requests over the last 10 seconds, where x is the
difference between the number and 100. For example, p99 1.403 indicates the slowest 1% of
requests over the last 10 seconds had an average latency of 1.403 seconds.
Running
The amount of time that has passed since the instance was launched.
Load 1, Load 5
Load average in the last one-minute and five-minute periods. Shown as a decimal value indicating
the average number of processes running during that time. If the number shown is higher than the
number of vCPUs (threads) available, then the remainder is the average number of processes that
were waiting.
795
AWS Elastic Beanstalk Developer Guide
Enhanced health rules
For example, if your instance type has four vCPUs, and the load is 4.5, there was an average of .5
processes in wait during that time period, equivalent to one process waiting 50 percent of the time.
User %, Nice %, System %, Idle %, I/O Wait %
Percentage of time that the CPU has spent in each state over the last 10 seconds.
Running
The amount of time that has passed since the instance was launched.
% User Time, % Privileged Time, % Idle Time
Percentage of time that the CPU has spent in each state over the last 10 seconds.
Implementation details
To capture metrics from IIS, Elastic Beanstalk implements a managed IHttpModule, and subscribes to
the BeginRequest and EndRequest events. This enables the module to report HTTP request latency
and response codes for all web requests handled by IIS. To add the module to the IIS request pipeline,
Elastic Beanstalk registers the module in the <modules> section of the IIS configuration file, %windir%
\System32\inetsrv\config\applicationHost.config.
The Elastic Beanstalk module in IIS sends the captured web request metrics to the on-instance
health agent, which is a Windows service named HealthD. To send this data, the module uses
NetNamedPipeBinding, which provides a secure and reliable binding that is optimized for on-machine
communication.
• You use client-side test tools. In this case, frequent HTTP client (4xx) errors are expected.
• You use AWS WAF in conjunction with your environment's Application Load Balancer to block
unwanted incoming traffic. In this case, Application Load Balancer returns HTTP 403 for each rejected
incoming message.
By default, Elastic Beanstalk includes all application HTTP 4xx errors when determining the
environment's health. It changes your environment health status from OK to Warning, Degraded, or
Severe, depending on the error rate. To correctly handle cases such as the examples we mentioned,
Elastic Beanstalk enables you to configure some enhanced health rules. You can choose to ignore
application HTTP 4xx errors on the environment's instances, or to ignore HTTP 4xx errors returned by the
environment's load balancer. This topic describes how to make these configuration changes.
796
AWS Elastic Beanstalk Developer Guide
Enhanced health rules
Note
Currently, these are the only available enhanced heath rule customizations. You can't configure
enhanced health to ignore other HTTP errors in addition to 4xx.
To configure HTTP 4xx status code checking using the Elastic Beanstalk console
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Monitoring configuration category, choose Edit.
5. Under Health monitoring rule customization, enable or disable the desired Ignore options.
6. Choose Apply.
To configure HTTP 4xx status code checking using the EB CLI and saved configurations
797
AWS Elastic Beanstalk Developer Guide
Enhanced health rules
OptionSettings:
...
aws:elasticbeanstalk:healthreporting:system:
ConfigDocument:
Rules:
Environment:
Application:
ApplicationRequests4xx:
Enabled: false
ELB:
ELBRequests4xx:
Enabled: true
Version: 1
SystemType: enhanced
...
Note
You can combine Rules and CloudWatchMetrics in the same ConfigDocument option
setting. CloudWatchMetrics are described in Publishing Amazon CloudWatch custom
metrics for an environment (p. 800).
If you previously enabled CloudWatchMetrics, the configuration file that you
retrieve using the eb config save command already has a ConfigDocument key with
a CloudWatchMetrics section. Do not delete it—add a Rules section into the same
ConfigDocument option value.
6. Save the configuration file and close the text editor. In this example, the updated configuration file
is saved with a name (02-cloudwatch-enabled.cfg.yml) that's different from the downloaded
configuration file. This creates a separate saved configuration when the file is uploaded. You can use
the same name as the downloaded file to overwrite the existing configuration without creating a
new one.
7. Use the eb config put command to upload the updated configuration file to Elastic Beanstalk.
When using the eb config get and put commands with saved configurations, don't include the file
name extension.
8. Apply the saved configuration to your running environment.
The --cfg option specifies a named configuration file that is applied to the environment. You can
save the configuration file locally or in Elastic Beanstalk. If a configuration file with the specified
name exists in both locations, the EB CLI uses the local file.
798
AWS Elastic Beanstalk Developer Guide
Enhanced health rules
The following example shows a config document that disables the checking of application HTTP 4xx
status codes and enables the checking of load balancer HTTP 4xx status codes.
{
"Rules": {
"Environment": {
"Application": {
"ApplicationRequests4xx": {
"Enabled": false
}
},
"ELB": {
"ELBRequests4xx": {
"Enabled": true
}
}
}
},
"Version": 1
}
For the AWS CLI, you pass the document as a value for the Value key in an option settings argument,
which itself is a JSON object. In this case, you must escape quotation marks in the embedded document.
The following command checks if the configuration settings are valid.
For an .ebextensions configuration file in YAML, you can provide the JSON document as is.
option_settings:
- namespace: aws:elasticbeanstalk:healthreporting:system
option_name: ConfigDocument
value: {
"Rules": {
"Environment": {
"Application": {
"ApplicationRequests4xx": {
"Enabled": false
}
},
"ELB": {
"ELBRequests4xx": {
"Enabled": true
}
}
}
},
"Version": 1
}
799
AWS Elastic Beanstalk Developer Guide
CloudWatch
By publishing metrics to CloudWatch, you also make them available for use with monitoring
graphs (p. 771) and alarms (p. 811). One free metric, EnvironmentHealth, is enabled automatically
when you use enhanced health reporting. Custom metrics other than EnvironmentHealth incur standard
CloudWatch charges.
To publish CloudWatch custom metrics for an environment, you must first enable enhanced health
reporting on the environment. See Enabling Elastic Beanstalk enhanced health reporting (p. 784) for
instructions.
Topics
• Enhanced health reporting metrics (p. 800)
• Configuring CloudWatch metrics using the Elastic Beanstalk console (p. 801)
• Configuring CloudWatch custom metrics using the EB CLI (p. 802)
• Providing custom metric config documents (p. 803)
You can publish the following enhanced health metrics from your environment to CloudWatch.
EnvironmentHealth
Environment only. This is the only CloudWatch metric that the enhanced health reporting system
publishes, unless you configure additional metrics. Environment health is represented by one of
seven statuses (p. 792). In the CloudWatch console, these statuses map to the following values:
• 0 – OK
• 1 – Info
• 5 – Unknown
• 10 – No data
• 15 – Warning
• 20 – Degraded
• 25 – Severe
InstancesSevere, InstancesDegraded, InstancesWarning, InstancesInfo, InstancesOk,
InstancesPending, InstancesUnknown, InstancesNoData
Environment only. These metrics indicate the number of instances in the environment with each
health status. InstancesNoData indicates the number of instances for which no data is being
received.
800
AWS Elastic Beanstalk Developer Guide
CloudWatch
Instance and environment. Indicates the total number of requests completed by the instance or
environment, and the number of requests that completed with each status code category.
ApplicationLatencyP10, ApplicationLatencyP50, ApplicationLatencyP75,
ApplicationLatencyP85, ApplicationLatencyP90, ApplicationLatencyP95,
ApplicationLatencyP99, ApplicationLatencyP99.9
Instance and environment. Indicates the average amount of time, in seconds, it takes to complete the
fastest x percent of requests.
InstanceHealth
Instance only. Indicates the current health status of the instance. Instance health is represented by
one of seven statuses (p. 792). In the CloudWatch console, these statuses map to the following
values:
• 0 – OK
• 1 – Info
• 5 – Unknown
• 10 – No data
• 15 – Warning
• 20 – Degraded
• 25 – Severe
Available metrics—Linux
Instance only. Indicates the percentage of time that the CPU has spent in each state over the last
minute.
LoadAverage1min
Instance only. The average CPU load of the instance over the last minute.
RootFilesystemUtil
Available metrics—Windows
Instance only. Indicates the percentage of time that the CPU has spent in each state over the last
minute.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
801
AWS Elastic Beanstalk Developer Guide
CloudWatch
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Monitoring configuration category, choose Edit.
5. Under Health reporting, select the instance and environment metrics to publish to CloudWatch. To
select multiple metrics, press the Ctrl key while choosing.
6. Choose Apply.
Enabling CloudWatch custom metrics adds them to the list of metrics available on the Monitoring
page (p. 770).
To configure CloudWatch custom metrics with the EB CLI and saved configurations
OptionSettings:
...
aws:elasticbeanstalk:healthreporting:system:
ConfigDocument:
CloudWatchMetrics:
Environment:
ApplicationRequests5xx: 60
ApplicationRequests4xx: 60
Instance:
ApplicationRequestsTotal: 60
Version: 1
SystemType: enhanced
...
In the example, 60 indicates the number of seconds between measurements. Currently, this is the
only supported value.
802
AWS Elastic Beanstalk Developer Guide
CloudWatch
Note
You can combine CloudWatchMetrics and Rules in the same ConfigDocument
option setting. Rules are described in Configuring enhanced health rules for an
environment (p. 796).
If you previously used Rules to configure enhanced health rules, then the configuration file
that you retrieve using the eb config save command already has a ConfigDocument key
with a Rules section. Do not delete it—add a CloudWatchMetrics section into the same
ConfigDocument option value.
6. Save the configuration file and close the text editor. In this example, the updated configuration file
is saved with a name (02-cloudwatch-enabled.cfg.yml) that is different from the downloaded
configuration file. This creates a separate saved configuration when the file is uploaded. You can use
the same name as the downloaded file to overwrite the existing configuration without creating a
new one.
7. Use the eb config put command to upload the updated configuration file to Elastic Beanstalk.
When using the eb config get and put commands with saved configurations, don't include the file
extension.
8. Apply the saved configuration to your running environment.
The --cfg option specifies a named configuration file that is applied to the environment. You can
save the configuration file locally or in Elastic Beanstalk. If a configuration file with the specified
name exists in both locations, the EB CLI uses the local file.
{
"CloudWatchMetrics": {
"Environment": {
"ApplicationLatencyP99.9": 60,
"InstancesSevere": 60,
"ApplicationLatencyP90": 60,
"ApplicationLatencyP99": 60,
"ApplicationLatencyP95": 60,
"InstancesUnknown": 60,
"ApplicationLatencyP85": 60,
"InstancesInfo": 60,
"ApplicationRequests2xx": 60,
"InstancesDegraded": 60,
"InstancesWarning": 60,
"ApplicationLatencyP50": 60,
"ApplicationRequestsTotal": 60,
"InstancesNoData": 60,
"InstancesPending": 60,
"ApplicationLatencyP10": 60,
"ApplicationRequests5xx": 60,
"ApplicationLatencyP75": 60,
"InstancesOk": 60,
803
AWS Elastic Beanstalk Developer Guide
CloudWatch
"ApplicationRequests3xx": 60,
"ApplicationRequests4xx": 60
},
"Instance": {
"ApplicationLatencyP99.9": 60,
"ApplicationLatencyP90": 60,
"ApplicationLatencyP99": 60,
"ApplicationLatencyP95": 60,
"ApplicationLatencyP85": 60,
"CPUUser": 60,
"ApplicationRequests2xx": 60,
"CPUIdle": 60,
"ApplicationLatencyP50": 60,
"ApplicationRequestsTotal": 60,
"RootFilesystemUtil": 60,
"LoadAverage1min": 60,
"CPUIrq": 60,
"CPUNice": 60,
"CPUIowait": 60,
"ApplicationLatencyP10": 60,
"LoadAverage5min": 60,
"ApplicationRequests5xx": 60,
"ApplicationLatencyP75": 60,
"CPUSystem": 60,
"ApplicationRequests3xx": 60,
"ApplicationRequests4xx": 60,
"InstanceHealth": 60,
"CPUSoftirq": 60
}
},
"Version": 1
}
For the AWS CLI, you pass the document as a value for the Value key in an option settings argument,
which itself is a JSON object. In this case, you must escape quotation marks in the embedded document.
For an .ebextensions configuration file in YAML, you can provide the JSON document as is.
option_settings:
804
AWS Elastic Beanstalk Developer Guide
API users
- namespace: aws:elasticbeanstalk:healthreporting:system
option_name: ConfigDocument
value: {
"CloudWatchMetrics": {
"Environment": {
"ApplicationLatencyP99.9": 60,
"InstancesSevere": 60,
"ApplicationLatencyP90": 60,
"ApplicationLatencyP99": 60,
"ApplicationLatencyP95": 60,
"InstancesUnknown": 60,
"ApplicationLatencyP85": 60,
"InstancesInfo": 60,
"ApplicationRequests2xx": 60,
"InstancesDegraded": 60,
"InstancesWarning": 60,
"ApplicationLatencyP50": 60,
"ApplicationRequestsTotal": 60,
"InstancesNoData": 60,
"InstancesPending": 60,
"ApplicationLatencyP10": 60,
"ApplicationRequests5xx": 60,
"ApplicationLatencyP75": 60,
"InstancesOk": 60,
"ApplicationRequests3xx": 60,
"ApplicationRequests4xx": 60
},
"Instance": {
"ApplicationLatencyP99.9": 60,
"ApplicationLatencyP90": 60,
"ApplicationLatencyP99": 60,
"ApplicationLatencyP95": 60,
"ApplicationLatencyP85": 60,
"CPUUser": 60,
"ApplicationRequests2xx": 60,
"CPUIdle": 60,
"ApplicationLatencyP50": 60,
"ApplicationRequestsTotal": 60,
"RootFilesystemUtil": 60,
"LoadAverage1min": 60,
"CPUIrq": 60,
"CPUNice": 60,
"CPUIowait": 60,
"ApplicationLatencyP10": 60,
"LoadAverage5min": 60,
"ApplicationRequests5xx": 60,
"ApplicationLatencyP75": 60,
"CPUSystem": 60,
"ApplicationRequests3xx": 60,
"ApplicationRequests4xx": 60,
"InstanceHealth": 60,
"CPUSoftirq": 60
}
},
"Version": 1
}
805
AWS Elastic Beanstalk Developer Guide
API users
you can use it. To maintain backward compatibility, enhanced health reporting is not enabled by default
when you create an environment using the Elastic Beanstalk API.
You configure enhanced health reporting by setting the service role, the instance profile, and Amazon
CloudWatch configuration options for your environment. You can do this in three ways: by setting the
configuration options in the .ebextensions folder, with saved configurations, or by configuring them
directly in the create-environment call's option-settings parameter.
To use the API, SDKs, or AWS command line interface (CLI) to create an environment that supports
enhanced health, you must:
• Create a service role and instance profile with the appropriate permissions (p. 20)
• Create a new environment with a new platform version (p. 29)
• Set the health system type, instance profile, and service role configuration options (p. 613)
Namespace: aws:elasticbeanstalk:healthreporting:system
IamInstanceProfile
Namespace: aws:autoscaling:launchconfiguration
Set to the name of an instance profile configured for use with Elastic Beanstalk.
ServiceRole
Namespace: aws:elasticbeanstalk:environment
Set to the name of a service role configured for use with Elastic Beanstalk.
ConfigDocument (optional)
Namespace: aws:elasticbeanstalk:healthreporting:system
A JSON document that defines the and instance and environment metrics to publish to CloudWatch. For
example:
{
"CloudWatchMetrics":
{
"Environment":
{
"ApplicationLatencyP99.9":60,
"InstancesSevere":60
}
"Instance":
{
"ApplicationLatencyP85":60,
"CPUUser": 60
}
}
"Version":1
806
AWS Elastic Beanstalk Developer Guide
Enhanced health log format
Note
Config documents may require special formatting, such as escaping quotes, depending on how
you provide them to Elastic Beanstalk. See Providing custom metric config documents (p. 803)
for examples.
/var/log/nginx/access.log
The following example is from an nginx proxy running on a Ruby web server environment, but the
format is similar for Apache.
The second log is in terse format. It includes information relevant only to enhanced health reporting.
This log is output to a subfolder named healthd and rotates hourly. Old logs are deleted immediately
after rotating out.
/var/log/nginx/healthd/application.log.2015-07-23-00
1437609879.311"/"200"0.083"0.083"177.72.242.17
1437609879.874"/"200"0.347"0.347"177.72.242.17
807
AWS Elastic Beanstalk Developer Guide
Enhanced health log format
1437609880.006"/bad/path"404"0.001"0.001"177.72.242.17
1437609880.058"/"200"0.530"0.530"177.72.242.17
1437609880.928"/bad/path"404"0.001"0.001"177.72.242.17
For nginx proxies, times are printed in floating-point seconds, with three decimal places. For Apache,
whole microseconds are used.
Note
If you see a warning similar to the following in a log file, where DATE-TIME is a date and time,
and you are using a custom proxy, such as in a multi-container Docker environment, you must
use an .ebextension to configure your environment so that healthd can read your log files:
You can start with the .ebextension in the Multicontainer Docker sample.
/etc/nginx/conf.d/webapp_healthd.conf
The following example shows the log configuration for nginx with the healthd log format highlighted.
upstream my_app {
server unix:///var/run/puma/my_app.sock;
}
server {
listen 80;
server_name _ localhost; # need to listen to localhost for worker tier
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
set $hour $4;
}
location / {
proxy_pass http://my_app; # match the name of upstream directive which is defined above
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /assets {
alias /var/app/current/public/assets;
808
AWS Elastic Beanstalk Developer Guide
Notifications and troubleshooting
gzip_static on;
gzip on;
expires max;
add_header Cache-Control public;
}
location /public {
alias /var/app/current/public;
gzip_static on;
gzip on;
expires max;
add_header Cache-Control public;
}
}
/etc/httpd/conf.d/healthd.conf
Deployments
Elastic Beanstalk monitors your environment for consistency following deployments. If a rolling
deployment fails, the version of your application running on the instances in your environment may vary.
This can occur if a deployment succeeds on one or more batches but fails prior to all batches completing.
Incorrect application version found on 2 out of 5 instances. Expected version "v1" (deployment 1).
Incorrect application version on environment instances. Expected version "v1" (deployment 1).
The expected application version is not running on some or all instances in an environment.
Incorrect application version "v2" (deployment 2). Expected version "v1" (deployment 1).
The application deployed to an instance differs from the expected version. If a deployment fails, the
expected version is reset to the version from the most recent successful deployment. In the above
example, the first deployment (version "v1") succeeded, but the second deployment (version "v2") failed.
Any instances running "v2" are considered unhealthy.
809
AWS Elastic Beanstalk Developer Guide
Notifications and troubleshooting
To solve this issue, start another deployment. You can redeploy a previous version (p. 441) that you know
works, or configure your environment to ignore health checks (p. 445) during deployment and redeploy
the new version to force the deployment to complete.
You can also identify and terminate the instances that are running the wrong application version. Elastic
Beanstalk will launch instances with the correct version to replace any instances that you terminate.
Use the EB CLI health command (p. 979) to identify instances that are running the wrong application
version.
Application server
15% of requests are erroring with HTTP 4xx
20% of the requests to the ELB are erroring with HTTP 4xx.
A high percentage of HTTP requests to an instance or environment are failing with 4xx errors.
A 400 series status code indicates that the user made a bad request, such as requesting a page that
doesn't exist (404 File Not Found) or that the user doesn't have access to (403 Forbidden). A low number
of 404s is not unusual but a large number could mean that there are internal or external links to
unavailable pages. These issues can be resolved by fixing bad internal links and adding redirects for bad
external links.
A high percentage of HTTP requests to an instance or environment are failing with 500 series status
codes.
A 500 series status code indicates that the application server encountered an internal error. These issues
indicate that there is an error in your application code and should be identified and fixed quickly.
On an instance, the health agent is reporting an extremely high percentage of CPU usage and sets the
instance health to Warning or Degraded.
Worker instance
20 messages waiting in the queue (25 seconds ago)
Requests are being added to your worker environment's queue faster than they can be processed. Scale
your environment to increase capacity.
Worker requests are failing repeatedly and being added to the the section called “Dead-letter
queues” (p. 485). Check the requests in the dead-letter queue to see why they are failing.
Other resources
4 active instances is below Auto Scaling group minimum size 5
The number of instances running in your environment is fewer than the minimum configured for the
Auto Scaling group.
The notifications configured for your Auto Scaling group have been modified outside of Elastic
Beanstalk.
810
AWS Elastic Beanstalk Developer Guide
Manage alarms
Manage alarms
You can create alarms for metrics that you are monitoring by using the Elastic Beanstalk console.
Alarms help you monitor changes to your AWS Elastic Beanstalk environment so that you can easily
identify and mitigate problems before they occur. For example, you can set an alarm that notifies you
when CPU utilization in an environment exceeds a certain threshold, ensuring that you are notified
before a potential problem occurs. For more information, see Using Elastic Beanstalk with Amazon
CloudWatch (p. 830).
Note
Elastic Beanstalk uses CloudWatch for monitoring and alarms, meaning CloudWatch costs are
applied to your AWS account for any alarms that you use.
For more information about monitoring specific metrics, see Basic health reporting (p. 773).
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Alarms.
The page displays a list of existing alarms. If any alarms are in the alarm state, they are flagged with
(warning).
4. To filter alarms, choose the drop-down menu, and then select a filter.
5.
To edit or delete an alarm, choose (edit) or (delete), respectively.
811
AWS Elastic Beanstalk Developer Guide
Manage alarms
To create an alarm
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Monitoring.
4.
Locate the metric for which you want to create an alarm, and then choose (alarm). The Add
alarm page is displayed.
812
AWS Elastic Beanstalk Developer Guide
Manage alarms
813
AWS Elastic Beanstalk Developer Guide
View change history
• Change state after: The amount a time after a threshold has been exceed that triggers a change
in state of the alarm.
• Notify: The Amazon SNS topic that is notified when an alarm changes state.
• Notify when state changes to:
• OK: The metric is within the defined threshold.
• Alarm: The metric exceeded the defined threshold.
• Insufficient data: The alarm has just started, the metric is not available, or not enough data is
available for the metric to determine the alarm state.
6. Choose Add. The environment status changes to gray while the environment updates. You can view
the alarm that you created by choosing Alarms in the navigation pane.
The Change History panel displays the following information for changes made to your environments:
Any sensitive data that is part of the change, such as the names of database users affected by the
change, aren't displayed in the panel.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Change history.
814
AWS Elastic Beanstalk Developer Guide
View change history
The Change History page shows a list of configuration changes that were made to your Elastic
Beanstalk environments. You can page through the list by choosing < (previous) or > (next), or by
choosing a specific page number. Under the Configuration changes column, select the arrow icon to
toggle between expanding and collapsing the list of changes under the Changes made heading. Use
815
AWS Elastic Beanstalk Developer Guide
View events
the search bar to filter your results from the change history list. You can enter any string to narrow
down the list of changes that are displayed.
The following examples demonstrate how the data shown on the earlier screen can be filtered:
• Enter GettingStartedApp-env in the search box to narrow down the results to only include the
changes that were made to the environment named GettingStartedApp-env.
• Enter example3 in the search box to narrow down the results to only include changes that were made
by IAM users whose username contains the string example3.
• Enter 2020-10 in the search box to narrow down the results to only include changes that were made
during the month of October 2020. Change the search value to 2020-10-16 to filter further the
displayed results to only include changes that were made on the day of October 16, 2020.
• Enter proxy:staticfiles in the search box to narrow down the results to only include the changes
that were made to the namespace named aws:elasticbeanstalk:environment:proxy:staticfiles. The rows
that are displayed are the result of the filter. This is true even for results that are collapsed under
Changes made.
To view events
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Events.
816
AWS Elastic Beanstalk Developer Guide
View events
The Events page shows a list of all events that have been recorded for the environment. You can
page through the list choosing < (previous), > (next), or page numbers. You can filter the type of
events shown by using the Severity drop-down list.
The EB CLI (p. 956) and AWS CLI both provide commands for retrieving events. If you are managing
your environment using the EB CLI, use eb events (p. 1014) to print a list of events. This command also
has a --follow option that continues to show new events until you press Ctrl+C to stop output.
To pull events using the AWS CLI, use the describe-events command and specify the environment by
name or ID:
817
AWS Elastic Beanstalk Developer Guide
Monitor instances
"EventDate": "2015-07-01T22:52:12.639Z"
},
...
For more information on the command line tools, see Tools (p. 956).
• For more information about listing and connecting to server instances using the AWS Toolkit for
Eclipse, see Listing and connecting to server instances (p. 150).
• For more information about listing and connecting to server instances using the AWS Toolkit for Visual
Studio, see Listing and connecting to server instances (p. 234).
Important
Before you can access your Elastic Beanstalk–provisioned Amazon EC2 instances, you must
create an Amazon EC2 key pair and configure your Elastic Beanstalk–provisioned Amazon
EC2instances to use the Amazon EC2 key pair. You can set up your Amazon EC2 key pairs using
the AWS Management Console. For instructions on creating a key pair for Amazon EC2, see the
Amazon EC2 Getting Started Guide. For more information on how to configure your Amazon EC2
instances to use an Amazon EC2 key pair, see EC2 key pair (p. 586).
By default, Elastic Beanstalk does not enable remote connections to EC2 instances in a Windows
container except for those in legacy Windows containers. (Elastic Beanstalk configures EC2
instances in legacy Windows containers to use port 3389 for RDP connections.) You can enable
remote connections to your EC2 instances running Windows by adding a rule to a security group
that authorizes inbound traffic to the instances. We strongly recommend that you remove
the rule when you end your remote connection. You can add the rule again the next time you
need to log in remotely. For more information, see Adding a Rule for Inbound RDP Traffic to a
Windows Instance and Connect to Your Windows Instance in the Amazon Elastic Compute Cloud
User Guide for Microsoft Windows.
818
AWS Elastic Beanstalk Developer Guide
Monitor instances
3. Load balancers created by Elastic Beanstalk have awseb in the name. Find the load balancer for your
environment and click it.
819
AWS Elastic Beanstalk Developer Guide
View instance logs
A list of the instances that the load balancer for your Elastic Beanstalk environment uses is
displayed. Make a note of an instance ID that you want to connect to.
5. In the navigation pane of the Amazon EC2 console, choose Instances, and find your instance ID in
the list.
6. Right-click the instance ID for the Amazon EC2 instance running in your environment's load balancer,
and then select Connect from the context menu.
7. Make a note of the instance's public DNS address on the Description tab.
8. Connect to an instance running Linux by using the SSH client of your choice, and then type ssh -
i .ec2/mykeypair.pem ec2-user@<public-DNS-of-the-instance> .
For more information on connecting to an Amazon EC2 Linux instance, see Getting Started with Amazon
EC2 Linux Instances in the Amazon EC2 User Guide for Linux Instances.
If your Elastic Beanstalk environment uses the .NET on Windows Server platform (p. 186), see Getting
Started with Amazon EC2 Windows Instances in the Amazon EC2 User Guide for Windows Instances.
820
AWS Elastic Beanstalk Developer Guide
View instance logs
application server, Elastic Beanstalk platform scripts, and AWS CloudFormation are stored locally
on individual instances. You can easily retrieve them by using the environment management
console (p. 396) or the EB CLI. You can also configure your environment to stream logs to Amazon
CloudWatch Logs in real time.
Tail logs are the last 100 lines of the most commonly used log files—Elastic Beanstalk operational
logs and logs from the web server or application server. When you request tail logs in the environment
management console or with eb logs, an instance in your environment concatenates the most recent log
entries into a single text file and uploads it to Amazon S3.
Bundle logs are full logs for a wider range of log files, including logs from yum and cron and several logs
from AWS CloudFormation. When you request bundle logs, an instance in your environment packages
the full log files into a ZIP archive and uploads it to Amazon S3.
Note
Elastic Beanstalk Windows Server platforms do not support bundle logs.
To upload rotated logs to Amazon S3, the instances in your environment must have an instance
profile (p. 21) with permission to write to your Elastic Beanstalk Amazon S3 bucket. These permissions
are included in the default instance profile that Elastic Beanstalk prompts you to create when you launch
an environment in the Elastic Beanstalk console for the first time.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Logs.
4. Choose Request Logs, and then choose the type of logs to retrieve. To get tail logs, choose Last 100
Lines. To get bundle logs, choose Full Logs.
Elastic Beanstalk stores tail and bundle logs in an Amazon S3 bucket, and generates a presigned Amazon
S3 URL that you can use to access your logs. Elastic Beanstalk deletes the files from Amazon S3 after a
duration of 15 minutes.
Warning
Anyone in possession of the presigned Amazon S3 URL can access the files before they are
deleted. Make the URL available only to trusted parties.
821
AWS Elastic Beanstalk Developer Guide
Log location on Amazon EC2 instances
Note
Your user policy must have the s3:DeleteObject permission. Elastic Beanstalk uses your user
permissions to delete the logs from Amazon S3.
To persist logs, you can configure your environment to publish logs to Amazon S3 automatically after
they are rotated. To enable log rotation to Amazon S3, follow the procedure in Configuring instance log
viewing (p. 598). Instances in your environment will attempt to upload logs that have been rotated once
per hour.
If your application generates logs in a location that isn't part of the default configuration for your
environment's platform, you can extend the default configuration by using configuration files
(.ebextensions (p. 683)). You can add your application's log files to tail logs, bundle logs, or log
rotation.
For real-time log streaming and long-term storage, configure your environment to stream logs to
Amazon CloudWatch Logs (p. 825).
Sections
• Log location on Amazon EC2 instances (p. 822)
• Log location in Amazon S3 (p. 823)
• Log rotation settings on Linux (p. 823)
• Extending the default log task configuration (p. 823)
• Streaming log files to Amazon CloudWatch Logs (p. 825)
Linux
• /var/log/eb-activity.log
• /var/log/eb-commandprocessor.log
Windows Server
• C:\Program Files\Amazon\ElasticBeanstalk\logs\
• C:\cfn\logs\cfn-init.log
These logs contain messages about deployment activities, including messages related to configuration
files (.ebextensions (p. 683)).
Each application and web server stores logs in its own folder:
• Apache – /var/log/httpd/
• IIS – C:\inetpub\wwwroot\
• Node.js – /var/log/nodejs/
• nginx – /var/log/nginx/
• Passenger – /var/app/support/logs/
• Puma – /var/log/puma/
• Python – /opt/python/log/
• Tomcat – /var/log/tomcat8/
822
AWS Elastic Beanstalk Developer Guide
Log location in Amazon S3
For example, logs from instance i-0a1fd158, in Elastic Beanstalk environment e-mpcwnwheky in AWS
Region us-west-2 in account 123456789012, are stored in the following locations:
• Tail Logs –
s3://elasticbeanstalk-us-west-2-123456789012/resources/environments/logs/
tail/e-mpcwnwheky/i-0a1fd158
• Bundle Logs –
s3://elasticbeanstalk-us-west-2-123456789012/resources/environments/logs/
bundle/e-mpcwnwheky/i-0a1fd158
• Rotated Logs –
s3://elasticbeanstalk-us-west-2-123456789012/resources/environments/logs/
publish/e-mpcwnwheky/i-0a1fd158
Note
You can find your environment ID in the environment management console.
Elastic Beanstalk deletes tail and bundle logs from Amazon S3 automatically 15 minutes after they are
created. Rotated logs persist until you delete them or move them to S3 Glacier.
You can find Elastic Beanstalk configuration files for logrotate in /etc/
logrotate.elasticbeanstalk.hourly/. These rotation settings are specific to the platform, and
might change in future versions of the platform. For more information about the available settings and
example configurations, run man logrotate.
The configuration files are invoked by cron jobs in /etc/cron.hourly/. For more information about
cron, run man cron.
On Linux:
• Tail Logs –
/opt/elasticbeanstalk/tasks/taillogs.d/
• Bundle Logs –
823
AWS Elastic Beanstalk Developer Guide
Extending the default log task configuration
/opt/elasticbeanstalk/tasks/bundlelogs.d/
• Rotated Logs –
/opt/elasticbeanstalk/tasks/publishlogs.d/
On Windows Server:
• Tail Logs –
c:\Program Files\Amazon\ElasticBeanstalk\config\taillogs.d\
• Rotated Logs –
c:\Program Files\Amazon\ElasticBeanstalk\config\publogs.d\
For example, the eb-activity.conf file on Linux adds two log files to the tail logs task.
/opt/elasticbeanstalk/tasks/taillogs.d/eb-activity.conf
/var/log/eb-commandprocessor.log
/var/log/eb-activity.log
You can use environment configuration files (.ebextensions (p. 683)) to add your own .conf files
to these folders. A .conf file lists log files specific to your application, which Elastic Beanstalk adds to
the log file tasks.
Use the files (p. 689) section to add configuration files to the tasks that you want to modify.
For example, the following configuration text adds a log configuration file to each instance in your
environment. This log configuration file, cloud-init.conf, adds /var/log/cloud-init.log to tail
logs.
files:
"/opt/elasticbeanstalk/tasks/taillogs.d/cloud-init.conf" :
mode: "000755"
owner: root
group: root
content: |
/var/log/cloud-init.log
Add this text to a file with the .config file name extension to your source bundle under a folder named
.ebextensions.
~/workspace/my-app
|-- .ebextensions
| `-- tail-logs.config
|-- index.php
`-- styles.css
On Linux platforms, you can also use wildcard characters in log task configurations. This configuration
file adds all files with the .log file name extension from the log folder in the application root to bundle
logs.
files:
"/opt/elasticbeanstalk/tasks/bundlelogs.d/applogs.conf" :
mode: "000755"
owner: root
824
AWS Elastic Beanstalk Developer Guide
Streaming log files to Amazon CloudWatch Logs
group: root
content: |
/var/app/current/log/*.log
For more information about using configuration files, see Advanced environment customization with
configuration files (.ebextensions) (p. 683).
Much like extending tail logs and bundle logs, you can extend log rotation using a configuration file.
Whenever Elastic Beanstalk rotates its own logs and uploads them to Amazon S3, it also rotates and
uploads your additional logs. Log rotation extension behaves differently depending on the platform's
operating system. The following sections describe the two cases.
Elastic Beanstalk uploads all versions of a base log file except for the newest one, because it considers
that one to be the active application log file, which can potentially be locked. Your application can,
therefore, keep the active log file locked between rotations.
For example, your application writes to a log file named my_log.log, and you specify this name
in your .conf file. The application periodically rotates the file. During the Elastic Beanstalk
rotation cycle, it finds the following files in the log file's folder: my_log.log, my_log.0800.log,
my_log.0830.log. Elastic Beanstalk considers all of them to be versions of the base name my_log. The
file my_log.log has the latest modification time, so Elastic Beanstalk uploads only the other two files,
my_log.0800.log and my_log.0830.log.
The set of logs streamed varies per environment, but always includes eb-activity.log and access
logs from the nginx or Apache proxy server that runs in front of your application.
825
AWS Elastic Beanstalk Developer Guide
Streaming log files to Amazon CloudWatch Logs
You can configure log streaming in the Elastic Beanstalk console either during environment
creation (p. 415) or for an existing environment (p. 598). In the following example, logs are saved for up
to seven days, even when the environment is terminated.
The following configuration file (p. 683) enables log streaming with 180 days retention, even if the
environment is terminated.
Example .ebextensions/log-streaming.config
option_settings:
aws:elasticbeanstalk:cloudwatch:logs:
StreamLogs: true
DeleteOnTerminate: false
RetentionInDays: 180
826
AWS Elastic Beanstalk Developer Guide
Architectural overview
Topics
• Architectural overview (p. 827)
• Using Elastic Beanstalk with Amazon CloudFront (p. 828)
• Logging Elastic Beanstalk API calls with AWS CloudTrail (p. 829)
• Using Elastic Beanstalk with Amazon CloudWatch (p. 830)
• Using Elastic Beanstalk with Amazon CloudWatch Logs (p. 831)
• Using Elastic Beanstalk with Amazon EventBridge (p. 841)
• Finding and tracking Elastic Beanstalk resources with AWS Config (p. 847)
• Using Elastic Beanstalk with Amazon DynamoDB (p. 851)
• Using Elastic Beanstalk with Amazon ElastiCache (p. 852)
• Using Elastic Beanstalk with Amazon Elastic File System (p. 853)
• Using Elastic Beanstalk with AWS Identity and Access Management (p. 854)
• Using Elastic Beanstalk with Amazon RDS (p. 923)
• Using Elastic Beanstalk with Amazon S3 (p. 935)
• Using Elastic Beanstalk with Amazon VPC (p. 938)
Architectural overview
The following diagram illustrates an example architecture of Elastic Beanstalk across multiple Availability
Zones working with other AWS products such as Amazon CloudFront, Amazon Simple Storage Service
(Amazon S3), and Amazon Relational Database Service (Amazon RDS).
827
AWS Elastic Beanstalk Developer Guide
CloudFront
To plan for fault-tolerance, it is advisable to have N+1 Amazon EC2 instances and spread your instances
across multiple Availability Zones. In the unlikely case that one Availability Zone goes down, you will
still have your other Amazon EC2 instances running in another Availability Zone. You can adjust Amazon
EC2 Auto Scaling to allow for a minimum number of instances as well as multiple Availability Zones. For
instructions on how to do this, see Auto Scaling group for your Elastic Beanstalk environment (p. 511).
For more information about building fault-tolerant applications, go to Building Fault-Tolerant
Applications on AWS.
The following sections discuss in more detail integration with Amazon CloudFront, Amazon CloudWatch,
Amazon DynamoDB Amazon ElastiCache, Amazon RDS, Amazon Route 53, Amazon Simple Storage
Service, Amazon VPC , and IAM.
After you have created and deployed your Elastic Beanstalk application you can sign up for CloudFront
and start using CloudFront to distribute your content. Learn more about CloudFront from the Amazon
CloudFront Developer Guide.
828
AWS Elastic Beanstalk Developer Guide
CloudTrail
To learn more about CloudTrail, see the AWS CloudTrail User Guide.
For an ongoing record of events in your AWS account, including events for Elastic Beanstalk, create a
trail. A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create
a trail in the console, the trail applies to all regions. The trail logs events from all regions in the AWS
partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can
configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs.
For more information, see:
All Elastic Beanstalk actions are logged by CloudTrail and are documented in the AWS Elastic Beanstalk
API Reference. For example, calls to the DescribeApplications, UpdateEnvironment, and
ListTagsForResource actions generate entries in the CloudTrail log files.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
829
AWS Elastic Beanstalk Developer Guide
CloudWatch
any source and includes information about the requested action, the date and time of the action, request
parameters, and so on. CloudTrail log files are not an ordered stack trace of the public API calls, so they
do not appear in any specific order.
The following example shows a CloudTrail log entry that demonstrates the UpdateEnvironment action
called by an IAM user named intern, for the sample-env environment in the sample-app application.
{
"Records": [{
"eventVersion": "1.05",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIXDAYQEXAMPLEUMLYNGL",
"arn": "arn:aws:iam::123456789012:user/intern",
"accountId": "123456789012",
"accessKeyId": "ASXIAGXEXAMPLEQULKNXV",
"userName": "intern",
"sessionContext": {
"attributes": {
"mfaAuthenticated": "false",
"creationDate": "2016-04-22T00:23:24Z"
}
},
"invokedBy": "signin.amazonaws.com"
},
"eventTime": "2016-04-22T00:24:14Z",
"eventSource": "elasticbeanstalk.amazonaws.com",
"eventName": "UpdateEnvironment",
"awsRegion": "us-west-2",
"sourceIPAddress": "255.255.255.54",
"userAgent": "signin.amazonaws.com",
"requestParameters": {
"applicationName": "sample-app",
"environmentName": "sample-env",
"optionSettings": []
},
"responseElements": null,
"requestID": "84ae9ecf-0280-17ce-8612-705c7b132321",
"eventID": "e48b6a08-c6be-4a22-99e1-c53139cbfb18",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
}]
}
You can use Amazon CloudWatch to collect metrics about your Amazon Web Services (AWS) resources—
such as the performance of your Amazon EC2 instances. You can also publish your own metrics directly
to Amazon CloudWatch. Amazon CloudWatch alarms help you implement decisions more easily by
enabling you to send notifications or automatically make changes to the resources you are monitoring,
based on rules that you define. For example, you can create alarms that initiate Amazon EC2 Auto
Scaling and Amazon Simple Notification Service (Amazon SNS) actions on your behalf.
Elastic Beanstalk automatically uses Amazon CloudWatch to help you monitor your application and
environment status. You can navigate to the Amazon CloudWatch console to see your dashboard and get
830
AWS Elastic Beanstalk Developer Guide
CloudWatch Logs
an overview of all of your resources as well as your alarms. You can also choose to view more metrics or
add custom metrics.
For more information about Amazon CloudWatch, go to the Amazon CloudWatch Developer Guide. For
an example of how to use Amazon CloudWatch with Elastic Beanstalk, see the section called “Example:
Using custom Amazon CloudWatch metrics” (p. 695).
In addition to instance logs, if you enable enhanced health (p. 776) for your environment, you can
configure the environment to stream health information to CloudWatch Logs. See Streaming Elastic
Beanstalk environment health information to Amazon CloudWatch Logs (p. 839).
The following figure shows the Monitoring page and graphs for an environment that is configured with
CloudWatch Logs integration. The example metrics in this environment are named CWLHttp4xx and
CWLHttp5xx. One of the graphs shows that the CWLHttp4xx metric has triggered an alarm based on
conditions specified in the configuration files.
831
AWS Elastic Beanstalk Developer Guide
CloudWatch Logs
The following figure shows the Alarms page and graphs for the example alarms named
AWSEBCWLHttp4xxPercentAlarm and AWSEBCWLHttp5xxCountAlarm that correspond to the
CWLHttp4xx and CWLHttp5xx metrics, respectively.
832
AWS Elastic Beanstalk Developer Guide
Prerequisites to instance log streaming to CloudWatch Logs
Topics
• Prerequisites to instance log streaming to CloudWatch Logs (p. 833)
• How Elastic Beanstalk sets up CloudWatch Logs (p. 834)
• Streaming instance logs to CloudWatch Logs (p. 837)
• Troubleshooting CloudWatch Logs integration (p. 839)
• Streaming Elastic Beanstalk environment health information to Amazon CloudWatch Logs (p. 839)
• Platform – Because this feature is only available in platform versions released on or after this release, if
you are using an earlier platform version, update your environment to a current one.
• If you don't have the AWSElasticBeanstalkWebTier or AWSElasticBeanstalkWorkerTier Elastic Beanstalk
managed policy in your Elastic Beanstalk instance profile (p. 21), you must add the following to your
profile to enable this feature.
833
AWS Elastic Beanstalk Developer Guide
How Elastic Beanstalk sets up CloudWatch Logs
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:PutLogEvents",
"logs:CreateLogStream"
],
"Resource": [
"*"
]
}
]
}
When you enable instance log streaming to CloudWatch Logs, Elastic Beanstalk sends log files from your
environment's instances to CloudWatch Logs. Different platforms stream different logs. The following
table lists the logs, by platform.
Docker / • /var/log/eb-engine.log
• /var/log/eb-hooks.log
Platform Branch: Docker
Running on 64bit Amazon Linux • /var/log/docker
2 • /var/log/docker-events.log
• /var/log/eb-docker/containers/eb-current-app/stdouterr.log
• /var/log/nginx/access.log
• /var/log/nginx/error.log
Docker / • /var/log/docker-events.log
• /var/log/eb-ecs-mgr.log
Platform Branch: ECS Running
on 64bit Amazon Linux 2 • /var/log/eb-engine.log
• /var/log/eb-hooks.log
• /var/log/ecs/ecs-agent.log
• /var/log/ecs/ecs-init.log
Go • /var/log/eb-engine.log
• /var/log/eb-hooks.log
.NET Core on Linux
• /var/log/web.stdout.log
Java / Platform Branch: Corretto • /var/log/nginx/access.log
running on 64bit Amazon Linux • /var/log/nginx/error.log
2
Node.js • /var/log/eb-engine.log
• /var/log/eb-hooks.log
Python
• /var/log/web.stdout.log
834
AWS Elastic Beanstalk Developer Guide
How Elastic Beanstalk sets up CloudWatch Logs
Tomcat • /var/log/eb-engine.log
• /var/log/eb-hooks.log
PHP
• /var/log/httpd/access_log
• /var/log/httpd/error_log
• /var/log/nginx/access.log
• /var/log/nginx/error.log
Ruby • /var/log/eb-engine.log
• /var/log/eb-hooks.log
• /var/log/puma/puma.log
• /var/log/web.stdout.log
• /var/log/nginx/access.log
• /var/log/nginx/error.log
Docker / • /var/log/eb-activity.log
• /var/log/nginx/error.log
Platform Branch: Docker
Running on 64bit Amazon Linux • /var/log/docker-events.log
• /var/log/docker
• /var/log/nginx/access.log
• /var/log/eb-docker/containers/eb-current-app/stdouterr.log
Docker / • /var/log/eb-activity.log
• /var/log/ecs/ecs-init.log
Platform Branch: Multicontainer
Docker Running on 64bit • /var/log/eb-ecs-mgr.log
Amazon Linux • /var/log/ecs/ecs-agent.log
• /var/log/docker-events.log
835
AWS Elastic Beanstalk Developer Guide
How Elastic Beanstalk sets up CloudWatch Logs
Go • /var/log/eb-activity.log
• /var/log/nginx/error.log
• /var/log/nginx/access.log
Java / • /var/log/eb-activity.log
• /var/log/nginx/access.log
Platform Branch: Java 8 running
on 64bit Amazon Linux • /var/log/nginx/error.log
• /var/log/web-1.error.log
Platform Branch: Java 7 running • /var/log/web-1.log
on 64bit Amazon Linux
Tomcat • /var/log/eb-activity.log
• /var/log/httpd/error_log
• /var/log/httpd/access_log
• /var/log/nginx/error_log
• /var/log/nginx/access_log
Node.js • /var/log/eb-activity.log
• /var/log/nodejs/nodejs.log
• /var/log/nginx/error.log
• /var/log/nginx/access.log
• /var/log/httpd/error.log
• /var/log/httpd/access.log
PHP • /var/log/eb-activity.log
• /var/log/httpd/error_log
• /var/log/httpd/access_log
Python • /var/log/eb-activity.log
• /var/log/httpd/error_log
• /var/log/httpd/access_log
• /opt/python/log/supervisord.log
Ruby / • /var/log/eb-activity.log
• /var/log/nginx/error.log
Platform Branch: Puma with
Ruby running on 64bit Amazon • /var/log/puma/puma.log
Linux • /var/log/nginx/access.log
Ruby / • /var/log/eb-activity.log
• /var/app/support/logs/passenger.log
Platform Branch: Passenger with
Ruby running on 64bit Amazon • /var/app/support/logs/access.log
Linux • /var/app/support/logs/error.log
Elastic Beanstalk configures log groups in CloudWatch Logs for the various log files that it streams. To
retrieve specific log files from CloudWatch Logs, you have to know the name of the corresponding log
group. The log group naming scheme depends on the platform's operating system.
836
AWS Elastic Beanstalk Developer Guide
Streaming instance logs to CloudWatch Logs
For Linux platforms, prefix the on-instance log file location with /aws/
elasticbeanstalk/environment_name to get the log group name. For example, to retrieve the file /
var/log/nginx/error.log, specify the log group /aws/elasticbeanstalk/environment_name/
var/log/nginx/error.log.
For Windows platforms, see the following table for the log group corresponding to each log file.
Before you enable it, set up IAM permissions to use with the CloudWatch Logs agent. You can attach the
following custom policy to the instance profile (p. 21) that you assign to your environment.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams"
],
"Resource": [
"*"
]
}
]
}
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
837
AWS Elastic Beanstalk Developer Guide
Streaming instance logs to CloudWatch Logs
After you enable log streaming, you can return to the Software configuration category or page and find
the Log Groups link. Click this link to see your logs in the CloudWatch console.
You can also use eb logs to retrieve logs from CloudWatch Logs. You can retrieve all the environment's
instance logs, or use the command's many options to specify subsets of logs to retrieve. For example, the
following command retrieves the complete set of instance logs for your environment, and saves them to
a directory under .elasticbeanstalk/logs.
$ eb logs --all
In particular, the --log-group option enables you to retrieve instance logs of a specific log group,
corresponding to a specific on-instance log file. To do that, you need to know the name of the log
group that corresponds to the log file you want to retrieve. You can find this information in How Elastic
Beanstalk sets up CloudWatch Logs (p. 834).
option_settings:
- namespace: aws:elasticbeanstalk:cloudwatch:logs
option_name: StreamLogs
value: true
838
AWS Elastic Beanstalk Developer Guide
Troubleshooting CloudWatch Logs integration
For more information about configuring CloudWatch Logs, see the CloudWatch Logs Agent Reference in
the Amazon CloudWatch Logs User Guide.
When you configure environment health streaming, Elastic Beanstalk creates a CloudWatch Logs log
group for environment health. The log group's name is /aws/elasticbeanstalk/environment-
name/environment-health.log. Within this log group, Elastic Beanstalk creates log streams named
YYYY-MM-DD#<hash-suffix> (there might be more than one log stream per date).
When the environment's health status changes, Elastic Beanstalk adds a record to the health log stream.
The record represents the health status transition—the new status and a description of the cause of
change. For example, an environment's status might change to Severe because the load balancer is
failing. For a description of enhanced health statuses, see Health colors and statuses (p. 792).
• Platform – You must be using a platform version that supports enhanced health reporting.
• Permissions – You must grant certain logging-related permissions to Elastic Beanstalk so that it can act
on your behalf to stream health information for your environment. If your environment isn't using a
service role that Elastic Beanstalk created for it, aws-elasticbeanstalk-service-role, or your
account's service-linked role, AWSServiceRoleForElasticBeanstalk, be sure to add the following
permissions to your custom service role.
{
"Effect": "Allow",
"Action": [
"logs:DescribeLogStreams",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk/*:log-stream:*"
}
839
AWS Elastic Beanstalk Developer Guide
Streaming environment health
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Monitoring configuration category, choose Edit.
5. Under Health reporting, make sure that the reporting System is set to Enhanced.
6. Under Health event streaming to CloudWatch Logs
After you enable log streaming, you can return to the Monitoring configuration category or page and
find the Log Group link. Click this link to see your environment health logs in the CloudWatch console.
You can also use eb logs to retrieve logs from CloudWatch Logs. For example, the following
command retrieves all the health logs for your environment, and saves them to a directory under
.elasticbeanstalk/logs.
############################################################################
## Sets up Elastic Beanstalk to stream environment health information
840
AWS Elastic Beanstalk Developer Guide
EventBridge
option_settings:
aws:elasticbeanstalk:cloudwatch:logs:health:
HealthStreamingEnabled: true
### Settings below this line are optional.
# DeleteOnTerminate: Delete the log group when the environment is
# terminated. Default is false. If false, the health data is kept
# RetentionInDays days.
DeleteOnTerminate: false
# RetentionInDays: The number of days to keep the archived health data
# before it expires, if DeleteOnTerminate isn't set. Default is 7 days.
RetentionInDays: 30
You can create rules in Amazon EventBridge to act on any of the following Elastic Beanstalk events:
• State changes for environment operations (including create, update, and terminate operations). The
event specifies if the state change has started, succeeded, or failed.
• State changes for other resources. Besides environments, other resources that are monitored include
load balancers, auto scaling groups, and instances.
• Health transition for environments. The event states where the environment health has transitioned
from one health status to another one.
• State change for managed updates. The event specifies if the state change has started, succeeded, or
failed.
To capture specific Elastic Beanstalk events that you're interested in, define event-specific patterns that
EventBridge can use to detect the events. Event patterns have the same structure as the events they
match. The pattern quotes the fields that you want to match and provides the values that you're looking
for. Events are emitted on a best effort basis. They're delivered from Elastic Beanstalk to EventBridge in
near real-time under normal operational circumstances. However, situations can arise that may delay or
prevent delivery of an event.
For a list of fields that are contained in Elastic Beanstalk events and their possible string values, see
Elastic Beanstalk event field mapping (p. 845). For information about how EventBridge rules work with
event patterns, see Events and Event Patterns in EventBridge.
841
AWS Elastic Beanstalk Developer Guide
Monitor an Elastic Beanstalk resource with EventBridge
The EventBridge console has a Pre-defined pattern option for building Elastic Beanstalk event patterns.
If you select this option in the EventBridge console when you create a rule, you can build an Elastic
Beanstalk event pattern quickly. You only need to select the event fields and values. As you make
selections, the console builds and displays the event pattern. Alternatively, you can manually edit the
event pattern that you build and can save it as a custom pattern. The console also displays a detailed
Sample Event that you can copy and paste to the event pattern that you're building.
If you prefer to type or copy and paste an event pattern into the EventBridge console, you can select to
use the Custom pattern option in the console. By doing this, you don't need to go through the steps of
selecting fields and values described earlier. This topic offers examples of both event-matching patterns
(p. 843) and Elastic Beanstalk events (p. 845) that you can use.
1. Log in to AWS using an account that has permissions to use EventBridge and Elastic Beanstalk.
2. Open the Amazon EventBridge console at https://console.aws.amazon.com/events/.
3. Choose Create rule.
4. Enter a Name for the rule, and, optionally, a description.
5. Under Define pattern choose Event pattern.
6. Under Event matching pattern, choose Pre-defined pattern by service.
Note
If you already have text for an event pattern and don't need the EventBridge console to
build it for you, you can select Customer pattern. You can then either manually enter or
copy and paste text into the Event Pattern box. Select Save and then skip to Step 12.
7. Select AWS for Service provider.
8. For Service name select Elastic Beanstalk.
9. For Event type select Status Change.
10. This step covers how you can work with the detail type, status, and severity event fields for Elastic
Beanstalk. As you choose these fields and the values you want to match, the console builds and
displays the event pattern. Your choices also determine how the console displays the subsequent
event fields, based on the hierarchy of the fields and the grouping of their values. For more
information, see the Elastic Beanstalk event field mapping (p. 845) table.
• If you select only one specific value for a given field, the next field in the hierarchy is displayed in
the console. You can choose one or more values with the displayed field. For example, if you select
the radio button for Specific detail type(s), then the detail types drop-down list is displayed. If
you select only one value from this list, options for you to work with the next field are displayed in
the console. In this example, it's the status field that follows. For this field, you can choose either
Any status or Specific status(es).
• If you choose more than one value for a given field, or if you select the Any radio button for that
field (for example Any status), the console doesn't provide you with options for the subsequent
fields. More specifically, it doesn't provide you with the option to choose specific values for
the subsequent fields in the hierarchy. In this example, the severity field follows status in the
hierarchy. It defaults to Any severity if more than one status is chosen prior. If you choose Specific
severity(s), then No items are listed in the list of values. The console is designed in this manner to
prevent ambiguous matching logic across fields in your event pattern.
The environment event field isn't affected by this hierarchy, so it displays as described in the next
step.
11. For Environment, select Any environment or Specific environment(s).
• If you select Specific environment(s), you can choose one or more environments from the drop-
down list. EventBridge adds all of environments that you select inside the EnvironmentName[ ]
842
AWS Elastic Beanstalk Developer Guide
Example Elastic Beanstalk event patterns
list in the detail section of the event pattern. Then, your rule filters all events to include only the
specific environments that you choose.
• If you select Any environment, then no environments are added to your event pattern. Because of
this, your rule doesn't filter any of the Elastic Beanstalk events based on environment.
12. The Select event bus section defaults to AWS default event bus. Leave the default selected and
confirm that Enable the rule on the selected event bus is toggled on.
13. Under Select targets, choose the target action to take when a resource state change event is
received from Elastic Beanstalk.
For example, you can use an Amazon Simple Notification Service (SNS) topic to send an email or
text message when an event occurs. To do this, you need to create an Amazon SNS topic using the
Amazon SNS console. To learn more, see Using Amazon SNS for user notifications.
Important
Some target actions might require the use of other services and incur additional charges,
such as the Amazon SNS or Lambda service. For more information about AWS pricing, see
https://aws.amazon.com/pricing/. Some services are part of the AWS Free Usage Tier. If you
are a new customer, you can test drive these services for free. See https://aws.amazon.com/
free/ for more information.
14. (Optional) Choose Add target to specify an additional target action for the event rule.
15. Choose Create.
{
"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Health status change"
]
}
• Health status change for the following environments: myEnvironment1 and myEnvironment2. This
event pattern filters for these two specific environments, whereas the previous Health status change
example that doesn't filter sends events for all environments.
{"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Health status change"
],
"detail": {
"EnvironmentName": [
"myEnvironment1",
"myEnvironment2"
]
}
}
843
AWS Elastic Beanstalk Developer Guide
Example Elastic Beanstalk event patterns
{
"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Elastic Beanstalk resource status change"
]
}
• Elastic Beanstalk resource status change with Status Environment update failed and Severity
ERROR for the following environments: myEnvironment1 and myEnvironment2
{"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Elastic Beanstalk resource status change"
],
"detail": {
"Status": [
"Environment update failed"
],
"Severity": [
"ERROR"
],
"EnvironmentName": [
"myEnvironment1",
"myEnvironment2"
]
}
}
• Other resource status change for load balancers, auto scaling groups, and instances
{
"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Other resource status change"
]
}
{
"source": [
"aws.elasticbeanstalk"
],
"detail-type": [
"Managed update status change"
]
}
• To capture all events from Elastic Beanstalk (exclude the detail-type section)
{
"source": [
"aws.elasticbeanstalk"
]
}
844
AWS Elastic Beanstalk Developer Guide
Example Elastic Beanstalk events
{
"version":"0",
"id":"1234a678-1b23-c123-12fd3f456e78",
"detail-type":"Elastic Beanstalk resource status change",
"source":"aws.elasticbeanstalk",
"account":"111122223333",
"time":"2020-11-03T00:31:54Z",
"region":"us-east-1",
"resources":[
"arn:was:elasticbeanstalk:us-east-1:111122223333:environment/myApplication/
myEnvironment"
],
"detail":{
"Status":"Environment creation started",
"EventDate":1604363513951,
"ApplicationName":"myApplication",
"Message":"createEnvironment is starting.",
"EnvironmentName":"myEnvironment",
"Severity":"INFO"
}
}
The following is an example Elastic Beanstalk event for a health status change:
{
"version":"0",
"id":"1234a678-1b23-c123-12fd3f456e78",
"detail-type":"Health status change",
"source":"aws.elasticbeanstalk",
"account":"111122223333",
"time":"2020-11-03T00:34:48Z",
"region":"us-east-1",
"resources":[
"arn:was:elasticbeanstalk:us-east-1:111122223333:environment/myApplication/
myEnvironment"
],
"detail":{
"Status":"Environment health changed",
"EventDate":1604363687870,
"ApplicationName":"myApplication",
"Message":"Environment health has transitioned from Pending to Ok. Initialization
completed 1 second ago and took 2 minutes.",
"EnvironmentName":"myEnvironment",
"Severity":"INFO"
}
}
845
AWS Elastic Beanstalk Developer Guide
Elastic Beanstalk event field mapping
846
AWS Elastic Beanstalk Developer Guide
AWS Config
Several Elastic Beanstalk resource types are integrated with AWS Config:
• Applications
• Application Versions
• Environments
The following section shows how to configure AWS Config to record resources of these types.
For more information about AWS Config, see the AWS Config Developer Guide. For pricing information,
see the AWS Config pricing information page.
847
AWS Elastic Beanstalk Developer Guide
Configuring AWS Config to
record Elastic Beanstalk resources
For example, you can configure AWS Config to record changes for Elastic Beanstalk resources and a
subset of other AWS resources that Elastic Beanstalk starts for you. Using the AWS Config Console,
you can select Elastic Beanstalk as a resource in the AWS Config Settings page from the Specific Types
field. From there you can choose to record any of the Elastic Beanstalk resource types: Application,
ApplicationVersion, and Environment.
The following figure shows the AWS Config Settings page, with Elastic Beanstalk resource types that you
can choose to record: Application, ApplicationVersion, and Environment.
After you select a few resource types, this is how the Specific types list appears.
To learn about regional vs. global resources, and for the full customization procedure, see Selecting
which Resources AWS Config Records.
848
AWS Elastic Beanstalk Developer Guide
Viewing Elastic Beanstalk configuration
details in the AWS Config console
849
AWS Elastic Beanstalk Developer Guide
Viewing Elastic Beanstalk configuration
details in the AWS Config console
AWS Config displays configuration details and other information about the resource you selected.
To see the full details of the recorded configuration, choose View Details.
850
AWS Elastic Beanstalk Developer Guide
Evaluating Elastic Beanstalk
resources using AWS Config rules
To learn more ways to find a resource and view information on this page, see Viewing AWS Resource
Configurations and History in the AWS Config Developer Guide.
If a resource violates a rule and is flagged as noncompliant, AWS Config can alert you using an Amazon
Simple Notification Service (Amazon SNS) topic. To programmatically consume the data in these AWS
Config alerts, use an Amazon Simple Queue Service (Amazon SQS) queue as the notification endpoint for
the Amazon SNS topic. For example, you might want to write code that starts a workflow when someone
modifies your environment's Auto Scaling group configuration.
To learn more about setting up and using rules, see Evaluating Resources with AWS Config Rules in the
AWS Config Developer Guide.
851
AWS Elastic Beanstalk Developer Guide
ElastiCache
are automatically replicated across multiple Availability Zones in an AWS Region to provide built-in high
availability and data durability.
If you use periodic tasks (p. 485) in a worker environment, Elastic Beanstalk creates a DynamoDB
table and uses it to perform leader election and store information about the task. Each instance in the
environment attempts to write to the table every few seconds to become leader and perform the task
when scheduled.
You can use configuration files (p. 683) to create a DynamoDB table for your application. See eb-node-
express-sample on GitHub for a sample Node.js application that creates a table with a configuration
file and connects to it with the AWS SDK for JavaScript in Node.js. For an example walkthrough using
DynamoDB with PHP, see Example: DynamoDB, CloudWatch, and SNS (p. 717). For an example that
uses the AWS SDK for Java, see Manage Tomcat Session State with DynamoDB in the AWS SDK for Java
documentation.
When you create a DynamoDB table using configuration files, the table isn't tied to your environment's
lifecycle, and isn't deleted when you terminate your environment. To ensure that personal information
isn't unnecessarily retained, delete any records that you don't need anymore, or delete the table.
For more information about DynamoDB, see the DynamoDB Developer Guide.
• For instructions on how to create an ElastiCache cluster with Redis, go to Getting Started with
Amazon ElastiCache for Redis in the ElastiCache for Redis User Guide.
• For instructions on how to create an ElastiCache cluster with Memcached, go to Getting Started
with Amazon ElastiCache for Memcached in the ElastiCache for Memcached User Guide.
2. Configure your ElastiCache Security Group to allow access from the Amazon EC2 security group used
by your Elastic Beanstalk application. For instructions on how to find the name of your EC2 security
group using the AWS Management Console, see Security groups (p. 503) on the EC2 Instances
document page.
• For more information on Redis, go to Authorize Access in the ElastiCache for Redis User Guide.
• For more information on Memcached, go to Authorize Access in the ElastiCache for Memcached
User Guide.
You can use configuration files to customize your Elastic Beanstalk environment to use ElastiCache.
For configuration file examples that integrate ElastiCache with Elastic Beanstalk, see Example:
ElastiCache (p. 710).
852
AWS Elastic Beanstalk Developer Guide
Amazon EFS
In an Elastic Beanstalk environment, you can use Amazon EFS to create a shared directory that stores
files for your application that users upload and modify. Your application can treat a mounted Amazon
EFS volume such as local storage. That way, you don't have to change your application code to scale up
to multiple instances.
For more information about Amazon EFS, see the Amazon Elastic File System User Guide.
Note
Elastic Beanstalk creates a webapp user that you can set up as the owner for application
directories on Amazon EC2 instances. For more information, see Persistent Storage (p. 17) in the
Design considerations topic of this guide.
Sections
• Configuration files (p. 853)
• Encrypted file systems (p. 854)
• Sample applications (p. 854)
• Cleaning up file systems (p. 854)
Configuration files
Elastic Beanstalk provides configuration files (p. 683) that you can use to create and mount Amazon EFS
file systems. You can create an Amazon EFS volume as part of your environment, or mount an Amazon
EFS volume that you created independently of Elastic Beanstalk.
• storage-efs-createfilesystem.config – Uses the Resources key to create a new file system and mount
points in Amazon EFS. All instances in your environment can connect to the same file system for
shared, scalable storage. Use storage-efs-mountfilesystem.config to mount the file system on
each instance.
Internal resources
Any resources that you create with configuration files are tied to the lifecycle of your
environment. If you terminate your environment or remove the configuration file, these
resources are lost.
• storage-efs-mountfilesystem.config – Mount an Amazon EFS file system to a local path on the
instances in your environment. You can create the volume as part of the environment with storage-
efs-createfilesystem.config. Or, you can mount it to your environment using the Amazon EFS
console, AWS CLI, or AWS SDK.
To use the configuration files, start by creating your Amazon EFS file system with storage-efs-
createfilesystem.config. Follow the instructions in the configuration file and add it to the
.ebextensions (p. 683) directory in your source code to create the file system in your VPC.
Deploy your updated source code to your Elastic Beanstalk environment. This is to confirm that the file
system was created successfully. Then, add the storage-efs-mountfilesystem.config to mount
the file system to the instances in your environment. Doing this in two separate deployments ensures
853
AWS Elastic Beanstalk Developer Guide
Encrypted file systems
that, if the mount operation fails, the file system is kept intact. If you do both in the same deployment,
an issue with either step will cause the file system to terminate when the deployment fails.
Sample applications
Elastic Beanstalk also provides sample applications that use Amazon EFS for shared storage. The two
projects have configuration files that you can use with a standard WordPress or Drupal installer to run
a blog or other content management system in a load-balanced environment. When a user uploads a
photo or other media, the file is stored on an Amazon EFS file system. This avoids having to use the
alternative, which is using a plugin to store uploaded files in Amazon S3.
• Load-balanced WordPress – This includes the configuration files to install WordPress securely and run
it in a load-balanced Elastic Beanstalk environment.
• Load-balanced Drupal – This includes the configuration files and instructions for installing Drupal
securely and running it in a load-balanced Elastic Beanstalk environment.
For an overview of permissions, see Service roles, instance profiles, and user policies (p. 20). For most
environments, the service role and instance profile that the Elastic Beanstalk console prompts you to
create when you launch your first environment have all of the permissions that you need. Likewise, the
managed policies (p. 879) provided by Elastic Beanstalk for full access and read-only access contain all
of the user permissions required for daily use.
Topics
854
AWS Elastic Beanstalk Developer Guide
Instance profiles
Elastic Beanstalk provides three managed policies: one for the web server tier, one for the worker tier,
and one with additional permissions required for multicontainer Docker environments. The console
assigns all of these policies to the role attached to the default instance profile. The policies follow.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BucketAccess",
"Action": [
"s3:Get*",
"s3:List*",
"s3:PutObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::elasticbeanstalk-*",
"arn:aws:s3:::elasticbeanstalk-*/*"
]
},
{
"Sid": "XRayAccess",
"Action":[
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets",
"xray:GetSamplingStatisticSummaries"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "CloudWatchLogsAccess",
"Action": [
855
AWS Elastic Beanstalk Developer Guide
Instance profiles
"logs:PutLogEvents",
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:DescribeLogGroups"
],
"Effect": "Allow",
"Resource": [
"arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
]
},
{
"Sid": "ElasticBeanstalkHealthAccess",
"Action": [
"elasticbeanstalk:PutInstanceStatistics"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:*:*:application/*",
"arn:aws:elasticbeanstalk:*:*:environment/*"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MetricsAccess",
"Action": [
"cloudwatch:PutMetricData"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "XRayAccess",
"Action":[
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets",
"xray:GetSamplingStatisticSummaries"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "QueueAccess",
"Action": [
"sqs:ChangeMessageVisibility",
"sqs:DeleteMessage",
"sqs:ReceiveMessage",
"sqs:SendMessage"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "BucketAccess",
"Action": [
"s3:Get*",
856
AWS Elastic Beanstalk Developer Guide
Instance profiles
"s3:List*",
"s3:PutObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::elasticbeanstalk-*",
"arn:aws:s3:::elasticbeanstalk-*/*"
]
},
{
"Sid": "DynamoPeriodicTasks",
"Action": [
"dynamodb:BatchGetItem",
"dynamodb:BatchWriteItem",
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:UpdateItem"
],
"Effect": "Allow",
"Resource": [
"arn:aws:dynamodb:*:*:table/*-stack-AWSEBWorkerCronLeaderRegistry*"
]
},
{
"Sid": "CloudWatchLogsAccess",
"Action": [
"logs:PutLogEvents",
"logs:CreateLogStream"
],
"Effect": "Allow",
"Resource": [
"arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk*"
]
},
{
"Sid": "ElasticBeanstalkHealthAccess",
"Action": [
"elasticbeanstalk:PutInstanceStatistics"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:*:*:application/*",
"arn:aws:elasticbeanstalk:*:*:environment/*"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ECSAccess",
"Effect": "Allow",
"Action": [
"ecs:Poll",
"ecs:StartTask",
"ecs:StopTask",
"ecs:DiscoverPollEndpoint",
857
AWS Elastic Beanstalk Developer Guide
Instance profiles
"ecs:StartTelemetrySession",
"ecs:RegisterContainerInstance",
"ecs:DeregisterContainerInstance",
"ecs:DescribeContainerInstances",
"ecs:Submit*"
],
"Resource": "*"
}
]
}
{
"Version": "2008-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
To customize permissions, you can add policies to the role attached to the default instance profile or
create your own instance profile with a restricted set of permissions.
Sections
• Verifying the permissions assigned to the default instance profile (p. 858)
• Updating an out-of-date default instance profile (p. 859)
• Adding permissions to the default instance profile (p. 859)
• Creating an instance profile (p. 859)
• Instance profiles with Amazon Linux 2 platforms (p. 860)
858
AWS Elastic Beanstalk Developer Guide
Instance profiles
Alternatively, you can add the managed policies to the role attached to the default instance profile
manually.
To add managed policies to the role attached to the default instance profile
• AWSElasticBeanstalkWebTier
• AWSElasticBeanstalkWorkerTier
• AWSElasticBeanstalkMulticontainerDocker
859
AWS Elastic Beanstalk Developer Guide
Service roles
Elastic Beanstalk needs to use temporary security credentials whenever it assumes a service role. To
get these credentials, Elastic Beanstalk sends a request to AWS Security Token Service (AWS STS) on
a Region specific endpoint. For more information, see Temporary Security Credentials in the IAM User
Guide.
Note
If the AWS STS endpoint for the Region where your environment is located is deactivated,
Elastic Beanstalk sends the request on an alternative endpoint that can't be deactivated. This
endpoint is associated with a different Region. Therefore, the request is a cross-Region request.
For more information, see Activating and Deactivating AWS STS in an AWS Region in the IAM
User Guide.
AWSElasticBeanstalkEnhancedHealth
This policy grants permissions for Elastic Beanstalk to monitor instance and environment health.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticloadbalancing:DescribeInstanceHealth",
"elasticloadbalancing:DescribeLoadBalancers",
860
AWS Elastic Beanstalk Developer Guide
Service roles
"elasticloadbalancing:DescribeTargetHealth",
"ec2:DescribeInstances",
"ec2:DescribeInstanceStatus",
"ec2:GetConsoleOutput",
"ec2:AssociateAddress",
"ec2:DescribeAddresses",
"ec2:DescribeSecurityGroups",
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"autoscaling:DescribeScalingActivities",
"autoscaling:DescribeNotificationConfigurations",
"sns:Publish"
],
"Resource": [
"*"
]
}
]
}
AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
This policy grants permissions for Elastic Beanstalk to update environments on your behalf to perform
managed platform updates.
This policy is grouped into statements based on the set of permissions provided.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ElasticBeanstalkPermissions",
"Effect": "Allow",
"Action": [
"elasticbeanstalk:*"
],
"Resource": "*"
},
{
"Sid": "AllowPassRoleToElasticBeanstalkAndDownstreamServices",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/*",
861
AWS Elastic Beanstalk Developer Guide
Service roles
"Condition": {
"StringEquals": {
"iam:PassedToService": [
"elasticbeanstalk.amazonaws.com",
"ec2.amazonaws.com",
"ec2.amazonaws.com.cn",
"autoscaling.amazonaws.com",
"elasticloadbalancing.amazonaws.com",
"ecs.amazonaws.com",
"cloudformation.amazonaws.com"
]
}
}
},
{
"Sid": "ReadOnlyPermissions",
"Effect": "Allow",
"Action": [
"autoscaling:DescribeAccountLimits",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"autoscaling:DescribeLaunchConfigurations",
"autoscaling:DescribeLoadBalancers",
"autoscaling:DescribeNotificationConfigurations",
"autoscaling:DescribeScalingActivities",
"autoscaling:DescribeScheduledActions",
"ec2:DescribeAccountAttributes",
"ec2:DescribeAddresses",
"ec2:DescribeAvailabilityZones",
"ec2:DescribeImages",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstances",
"ec2:DescribeKeyPairs",
"ec2:DescribeLaunchTemplates",
"ec2:DescribeLaunchTemplateVersions",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSnapshots",
"ec2:DescribeSpotInstanceRequests",
"ec2:DescribeSubnets",
"ec2:DescribeVpcClassicLink",
"ec2:DescribeVpcs",
"elasticloadbalancing:DescribeInstanceHealth",
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeTargetGroups",
"elasticloadbalancing:DescribeTargetHealth",
"logs:DescribeLogGroups",
"rds:DescribeDBEngineVersions",
"rds:DescribeDBInstances",
"rds:DescribeOrderableDBInstanceOptions",
"sns:ListSubscriptionsByTopic"
],
"Resource": [
"*"
]
},
{
"Sid": "EC2BroadOperationPermissions",
"Effect": "Allow",
"Action": [
"ec2:AllocateAddress",
"ec2:AssociateAddress",
"ec2:AuthorizeSecurityGroupEgress",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:CreateLaunchTemplate",
"ec2:CreateLaunchTemplateVersion",
"ec2:CreateSecurityGroup",
862
AWS Elastic Beanstalk Developer Guide
Service roles
"ec2:DeleteLaunchTemplate",
"ec2:DeleteLaunchTemplateVersions",
"ec2:DeleteSecurityGroup",
"ec2:DisassociateAddress",
"ec2:ReleaseAddress",
"ec2:RevokeSecurityGroupEgress",
"ec2:RevokeSecurityGroupIngress"
],
"Resource": "*"
},
{
"Sid": "EC2RunInstancesOperationPermissions",
"Effect": "Allow",
"Action": "ec2:RunInstances",
"Resource": "*",
"Condition": {
"ArnLike": {
"ec2:LaunchTemplate": "arn:aws:ec2:*:*:launch-template/*"
}
}
},
{
"Sid": "EC2TerminateInstancesOperationPermissions",
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances"
],
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"StringLike": {
"ec2:ResourceTag/aws:cloudformation:stack-id": [
"arn:aws:cloudformation:*:*:stack/awseb-e-*",
"arn:aws:cloudformation:*:*:stack/eb-*"
]
}
}
},
{
"Sid": "ECSBroadOperationPermissions",
"Effect": "Allow",
"Action": [
"ecs:CreateCluster",
"ecs:DescribeClusters",
"ecs:RegisterTaskDefinition"
],
"Resource": "*"
},
{
"Sid": "ECSDeleteClusterOperationPermissions",
"Effect": "Allow",
"Action": "ecs:DeleteCluster",
"Resource": "arn:aws:ecs:*:*:cluster/awseb-*"
},
{
"Sid": "ASGOperationPermissions",
"Effect": "Allow",
"Action": [
"autoscaling:AttachInstances",
"autoscaling:CreateAutoScalingGroup",
"autoscaling:CreateLaunchConfiguration",
"autoscaling:DeleteLaunchConfiguration",
"autoscaling:DeleteAutoScalingGroup",
"autoscaling:DeleteScheduledAction",
"autoscaling:DetachInstances",
"autoscaling:DeletePolicy",
"autoscaling:PutScalingPolicy",
863
AWS Elastic Beanstalk Developer Guide
Service roles
"autoscaling:PutScheduledUpdateGroupAction",
"autoscaling:PutNotificationConfiguration",
"autoscaling:ResumeProcesses",
"autoscaling:SetDesiredCapacity",
"autoscaling:SuspendProcesses",
"autoscaling:TerminateInstanceInAutoScalingGroup",
"autoscaling:UpdateAutoScalingGroup"
],
"Resource": [
"arn:aws:autoscaling:*:*:launchConfiguration:*:launchConfigurationName/
awseb-e-*",
"arn:aws:autoscaling:*:*:launchConfiguration:*:launchConfigurationName/eb-
*",
"arn:aws:autoscaling:*:*:autoScalingGroup:*:autoScalingGroupName/awseb-e-
*",
"arn:aws:autoscaling:*:*:autoScalingGroup:*:autoScalingGroupName/eb-*"
]
},
{
"Sid": "CFNOperationPermissions",
"Effect": "Allow",
"Action": [
"cloudformation:*"
],
"Resource": [
"arn:aws:cloudformation:*:*:stack/awseb-*",
"arn:aws:cloudformation:*:*:stack/eb-*"
]
},
{
"Sid": "ELBOperationPermissions",
"Effect": "Allow",
"Action": [
"elasticloadbalancing:ApplySecurityGroupsToLoadBalancer",
"elasticloadbalancing:ConfigureHealthCheck",
"elasticloadbalancing:CreateLoadBalancer",
"elasticloadbalancing:DeleteLoadBalancer",
"elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
"elasticloadbalancing:DeregisterTargets",
"elasticloadbalancing:RegisterInstancesWithLoadBalancer",
"elasticloadbalancing:RegisterTargets"
],
"Resource": [
"arn:aws:elasticloadbalancing:*:*:targetgroup/awseb-*",
"arn:aws:elasticloadbalancing:*:*:targetgroup/eb-*",
"arn:aws:elasticloadbalancing:*:*:loadbalancer/awseb-*",
"arn:aws:elasticloadbalancing:*:*:loadbalancer/eb-*",
"arn:aws:elasticloadbalancing:*:*:loadbalancer/*/awseb-*/*",
"arn:aws:elasticloadbalancing:*:*:loadbalancer/*/eb-*/*"
]
},
{
"Sid": "CWLogsOperationPermissions",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:DeleteLogGroup",
"logs:PutRetentionPolicy"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk/*"
},
{
"Sid": "S3ObjectOperationPermissions",
"Effect": "Allow",
"Action": [
"s3:DeleteObject",
864
AWS Elastic Beanstalk Developer Guide
Service roles
"s3:GetObject",
"s3:GetObjectAcl",
"s3:GetObjectVersion",
"s3:GetObjectVersionAcl",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutObjectVersionAcl"
],
"Resource": "arn:aws:s3:::elasticbeanstalk-*/*"
},
{
"Sid": "S3BucketOperationPermissions",
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:GetBucketPolicy",
"s3:ListBucket",
"s3:PutBucketPolicy"
],
"Resource": "arn:aws:s3:::elasticbeanstalk-*"
},
{
"Sid": "SNSOperationPermissions",
"Effect": "Allow",
"Action": [
"sns:CreateTopic",
"sns:GetTopicAttributes",
"sns:SetTopicAttributes",
"sns:Subscribe"
],
"Resource": "arn:aws:sns:*:*:ElasticBeanstalkNotifications-*"
},
{
"Sid": "SQSOperationPermissions",
"Effect": "Allow",
"Action": [
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl"
],
"Resource": [
"arn:aws:sqs:*:*:awseb-e-*",
"arn:aws:sqs:*:*:eb-*"
]
},
{
"Sid": "CWPutMetricAlarmOperationPermissions",
"Effect": "Allow",
"Action": [
"cloudwatch:PutMetricAlarm"
],
"Resource": [
"arn:aws:cloudwatch:*:*:alarm:awseb-*",
"arn:aws:cloudwatch:*:*:alarm:eb-*"
]
}
]
}
To view the content of a managed policy, you can also use the Policies page in the IAM console.
Note
In the past, Elastic Beanstalk supported the AWSElasticBeanstalkService
managed service role policy. This policy has been replaced by
AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy. You might still be able to see and
use the earlier policy in the IAM console. However, we recommend that you transition to using
865
AWS Elastic Beanstalk Developer Guide
Service roles
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "elasticbeanstalk.amazonaws.com"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "elasticbeanstalk"
}
}
}
]
}
When you enable managed platform updates (p. 464) for your environment, Elastic Beanstalk
assumes a separate managed-updates service role to perform managed updates. By default,
the Elastic Beanstalk console uses the same generated service role, aws-elasticbeanstalk-
service-role, for the managed-updates service role. If you change your default service role, the
console sets the managed-updates service role to use the managed-updates service-linked role,
AWSServiceRoleForElasticBeanstalkManagedUpdates. For more information about service-
linked roles, see the section called “Using service-linked roles” (p. 867).
Note
Because of permission issues, the Elastic Beanstalk service doesn't always successfully create
this service-linked role for you. Therefore, the console tries to explicitly create it. To ensure your
account has this service-linked role, create an environment at least once using the console, and
configure managed updates to be enabled before you create the environment.
Unlike in the console, you can't specify a managed-updates service role when using an EB CLI command
option. If you enable managed updates for your environment, you must set the managed-updates
service role though configuration options. The following example enables managed updates and uses
the default service role as a managed-updates service role.
Example .ebextensions/managed-platform-update.config
option_settings:
866
AWS Elastic Beanstalk Developer Guide
Service roles
aws:elasticbeanstalk:managedactions:
ManagedActionsEnabled: true
PreferredStartTime: "Tue:09:00"
ServiceRoleForManagedUpdates: "aws-elasticbeanstalk-service-role"
aws:elasticbeanstalk:managedactions:platformupdate:
UpdateLevel: patch
InstanceRefreshEnabled: true
In addition, if you enable managed platform updates (p. 464) for your environment, you can specify
a managed-updates service role using the ServiceRoleForManagedUpdates option of the
aws:elasticbeanstalk:managedactions (p. 657) namespace.
If you create an environment by using the Elastic Beanstalk API and don't specify a service role, Elastic
Beanstalk creates a monitoring service-linked role (p. 869) for your account, if one doesn't already exist.
Elastic Beanstalk uses this role for the new environment. You can also use IAM to create a monitoring
service-linked role for your account in advance. After your account has this role, you can use it to create
an environment using the Elastic Beanstalk API, the Elastic Beanstalk console, or the EB CLI.
If you enable managed platform updates (p. 464) for the environment
and specify AWSServiceRoleForElasticBeanstalkManagedUpdates
as the value for the ServiceRoleForManagedUpdates option of the
aws:elasticbeanstalk:managedactions (p. 657) namespace, Elastic Beanstalk creates a
managed-updates service-linked role (p. 874) for your account, if one doesn't already exist. Elastic
Beanstalk uses the role to perform managed updates for the new environment.
Note
When Elastic Beanstalk tries to create the monitoring and managed-updates service-
linked roles for your account when you create an environment, you must have the
iam:CreateServiceLinkedRole permission. If you don't have this permission, environment
creation fails, and a message explaining the issue is displayed.
As an alternative, another user with permission to create service-linked roles can use
IAM to create the service linked-role in advance. Using this method, you don't need the
iam:CreateServiceLinkedRole permission to create your environment.
867
AWS Elastic Beanstalk Developer Guide
Service roles
2. Choose aws-elasticbeanstalk-service-role.
3. On the Permissions tab, review the list of policies attached to the role.
4. To view the permissions that a policy grants, choose the policy.
Alternatively, you can manually add the managed policies to the default service role.
• AWSElasticBeanstalkEnhancedHealth
• AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
868
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
Apply your custom service role when you create an environment either using the environment creation
wizard (p. 409) or with the --service-role option for the eb create (p. 1003) command.
• Monitoring service-linked role – Allows Elastic Beanstalk to monitor the health of running environments
and publish health event notifications.
• Maintenance service-linked role – Allows Elastic Beanstalk to perform regular maintenance activities for
your running environments.
• managed-updates service-linked role – Allows Elastic Beanstalk to perform scheduled platform updates
of your running environments.
Topics
• The monitoring service-linked role (p. 869)
• The maintenance service-linked role (p. 872)
• The managed-updates service-linked role (p. 874)
A service-linked role makes setting up Elastic Beanstalk easier because you don’t have to manually add
the necessary permissions. Elastic Beanstalk defines the permissions of its service-linked roles, and
unless defined otherwise, only Elastic Beanstalk can assume its roles. The defined permissions include
the trust policy and the permissions policy, and that permissions policy cannot be attached to any other
IAM entity.
You can delete a service-linked role only after first deleting their related resources. This protects your
Elastic Beanstalk resources because you can't inadvertently remove permission to access the resources.
For information about other services that support service-linked roles, see AWS Services That Work with
IAM and look for the services that have Yes in the Service-Linked Role column. Choose a Yes with a link
to view the service-linked role documentation for that service.
869
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
The AWSServiceRoleForElasticBeanstalk service-linked role trusts the following services to assume the
role:
• elasticbeanstalk.amazonaws.com
The permissions policy of the AWSServiceRoleForElasticBeanstalk service-linked role contains all of the
permissions that Elastic Beanstalk needs to complete actions on your behalf:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudformationReadOperationsOnElasticBeanstalkStacks",
"Effect": "Allow",
"Action": [
"cloudformation:DescribeStackResource",
"cloudformation:DescribeStackResources",
"cloudformation:DescribeStacks"
],
"Resource": [
"arn:aws:cloudformation:*:*:stack/awseb-*",
"arn:aws:cloudformation:*:*:stack/eb-*"
]
},
{
"Sid": "AllowOperations",
"Effect": "Allow",
"Action": [
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"autoscaling:DescribeNotificationConfigurations",
"autoscaling:DescribeScalingActivities",
"autoscaling:PutNotificationConfiguration",
"ec2:DescribeInstanceStatus",
"ec2:AssociateAddress",
"ec2:DescribeAddresses",
"ec2:DescribeInstances",
"ec2:DescribeSecurityGroups",
"elasticloadbalancing:DescribeInstanceHealth",
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeTargetHealth",
"elasticloadbalancing:DescribeTargetGroups",
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl",
"sns:Publish"
],
"Resource": [
"*"
]
}
]
}
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or
delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User
Guide.
870
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
Alternatively, you can use an AWS managed policy to provide full access (p. 879) to Elastic Beanstalk.
When Elastic Beanstalk tries to create the AWSServiceRoleForElasticBeanstalk service-linked role for
your account when you create an environment, you must have the iam:CreateServiceLinkedRole
permission. If you don't have this permission, environment creation fails, and you see a message
explaining the issue.
As an alternative, another user with permission to create service-linked roles can use IAM to pre-create
the service linked-role in advance. You can then create your environment even without having the
iam:CreateServiceLinkedRole permission.
You (or another user) can use the IAM console to create a service-linked role with the Elastic
Beanstalk use case. In the IAM CLI or the IAM API, create a service-linked role with the
elasticbeanstalk.amazonaws.com service name. For more information, see Creating a Service-
Linked Role in the IAM User Guide. If you delete this service-linked role, you can use this same process to
create the role again.
If you delete this service-linked role, and then need to create it again, you can use the same process to
recreate the role in your account. When you create an Elastic Beanstalk environment using the Elastic
Beanstalk API and don't specify a service role, Elastic Beanstalk creates the service-linked role for you
again.
Before you can use IAM to delete a service-linked role, you must first be sure that all Elastic Beanstalk
environments are either using a different service role or are terminated.
Note
If the Elastic Beanstalk service is using the service-linked role when you try to terminate the
environments, then the termination might fail. If that happens, wait for a few minutes and try
the operation again.
871
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
See eb terminate (p. 1043) for details about terminating an Elastic Beanstalk environment using the EB
CLI.
See TerminateEnvironment for details about terminating an Elastic Beanstalk environment using the API.
Use the IAM console, the IAM CLI, or the IAM API to delete the AWSServiceRoleForElasticBeanstalk
service-linked role. For more information, see Deleting a Service-Linked Role in the IAM User Guide.
A service-linked role makes setting up Elastic Beanstalk easier because you don’t have to manually add
the necessary permissions. Elastic Beanstalk defines the permissions of its service-linked roles, and
unless defined otherwise, only Elastic Beanstalk can assume its roles. The defined permissions include
the trust policy and the permissions policy, and that permissions policy cannot be attached to any other
IAM entity.
You can delete a service-linked role only after first deleting their related resources. This protects your
Elastic Beanstalk resources because you can't inadvertently remove permission to access the resources.
For information about other services that support service-linked roles, see AWS Services That Work with
IAM and look for the services that have Yes in the Service-Linked Role column. Choose a Yes with a link
to view the service-linked role documentation for that service.
• maintenance.elasticbeanstalk.amazonaws.com
872
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
{
"Version": "2012-10-17",
"Statement":
{
"Sid": "AllowCloudformationChangeSetOperationsOnElasticBeanstalkStacks",
"Effect": "Allow",
"Action": [
"cloudformation:CreateChangeSet",
"cloudformation:DescribeChangeSet",
"cloudformation:ExecuteChangeSet",
"cloudformation:DeleteChangeSet",
"cloudformation:ListChangeSets",
"cloudformation:DescribeStacks"
],
"Resource": [
"arn:aws:cloudformation:*:*:stack/awseb-*",
"arn:aws:cloudformation:*:*:stack/eb-*"
]
}
}
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or
delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User
Guide.
Alternatively, you can use an AWS managed policy to provide full access (p. 879) to Elastic Beanstalk.
If you delete this service-linked role, and then need to create it again, you can use the same process to
recreate the role in your account. When you create an Elastic Beanstalk environment using the Elastic
Beanstalk API and don't specify an instance profile, Elastic Beanstalk creates the service-linked role for
you again.
873
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
or maintained. However, you must clean up the resources for your service-linked role before you can
manually delete it.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Terminate environment.
4. Use the on-screen dialog box to confirm environment termination.
See eb terminate (p. 1043) for details about terminating an Elastic Beanstalk environment using the EB
CLI.
See TerminateEnvironment for details about terminating an Elastic Beanstalk environment using the API.
A service-linked role makes setting up Elastic Beanstalk easier because you don’t have to manually add
the necessary permissions. Elastic Beanstalk defines the permissions of its service-linked roles, and
unless defined otherwise, only Elastic Beanstalk can assume its roles. The defined permissions include
the trust policy and the permissions policy, and that permissions policy cannot be attached to any other
IAM entity.
You can delete a service-linked role only after first deleting their related resources. This protects your
Elastic Beanstalk resources because you can't inadvertently remove permission to access the resources.
For information about other services that support service-linked roles, see AWS Services That Work with
IAM and look for the services that have Yes in the Service-Linked Role column. Choose a Yes with a link
to view the service-linked role documentation for that service.
874
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
• managedupdates.elasticbeanstalk.amazonaws.com
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPassRoleToElasticBeanstalkAndDownstreamServices",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "*",
"Condition": {
"StringLikeIfExists": {
"iam:PassedToService": [
"elasticbeanstalk.amazonaws.com",
"ec2.amazonaws.com",
"autoscaling.amazonaws.com",
"elasticloadbalancing.amazonaws.com",
"ecs.amazonaws.com",
"cloudformation.amazonaws.com"
]
}
}
},
{
"Sid": "SingleInstanceAPIs",
"Effect": "Allow",
"Action": [
"ec2:releaseAddress",
"ec2:allocateAddress",
"ec2:DisassociateAddress",
"ec2:AssociateAddress"
],
"Resource": "*"
},
{
"Sid": "ECS",
"Effect": "Allow",
"Action": [
"ecs:RegisterTaskDefinition",
"ecs:DeRegisterTaskDefinition",
"ecs:List*",
"ecs:Describe*"
],
"Resource": "*"
},
{
"Sid": "ElasticBeanstalkAPIs",
"Effect": "Allow",
"Action": [
"elasticbeanstalk:*"
875
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
],
"Resource": "*"
},
{
"Sid": "ReadOnlyAPIs",
"Effect": "Allow",
"Action": [
"cloudformation:Describe*",
"cloudformation:List*",
"ec2:Describe*",
"autoscaling:Describe*",
"elasticloadbalancing:Describe*"
],
"Resource": "*"
},
{
"Sid": "ASG",
"Effect": "Allow",
"Action": [
"autoscaling:AttachInstances",
"autoscaling:CreateAutoScalingGroup",
"autoscaling:CreateLaunchConfiguration",
"autoscaling:DeleteAutoScalingGroup",
"autoscaling:DeleteLaunchConfiguration",
"autoscaling:DeleteScheduledAction",
"autoscaling:DetachInstances",
"autoscaling:PutNotificationConfiguration",
"autoscaling:PutScalingPolicy",
"autoscaling:PutScheduledUpdateGroupAction",
"autoscaling:ResumeProcesses",
"autoscaling:SuspendProcesses",
"autoscaling:TerminateInstanceInAutoScalingGroup",
"autoscaling:UpdateAutoScalingGroup"
],
"Resource": [
"arn:aws:autoscaling:*:*:launchConfiguration:*:launchConfigurationName/
awseb-e-*",
"arn:aws:autoscaling:*:*:autoScalingGroup:*:autoScalingGroupName/awseb-e-*"
]
},
{
"Sid": "CFN",
"Effect": "Allow",
"Action": [
"cloudformation:CreateStack",
"cloudformation:DeleteStack",
"cloudformation:GetTemplate",
"cloudformation:UpdateStack"
],
"Resource": "arn:aws:cloudformation:*:*:stack/awseb-e-*"
},
{
"Sid": "EC2",
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances"
],
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"StringLike": {
"ec2:ResourceTag/aws:cloudformation:stack-id":
"arn:aws:cloudformation:*:*:stack/awseb-e-*"
}
}
},
{
876
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
"Sid": "S3Obj",
"Effect": "Allow",
"Action": [
"s3:DeleteObject",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:GetObjectVersion",
"s3:GetObjectVersionAcl",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutObjectVersionAcl"
],
"Resource": "arn:aws:s3:::elasticbeanstalk-*/*"
},
{
"Sid": "S3Bucket",
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:GetBucketPolicy",
"s3:ListBucket",
"s3:PutBucketPolicy"
],
"Resource": "arn:aws:s3:::elasticbeanstalk-*"
},
{
"Sid": "CWL",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:DeleteLogGroup",
"logs:PutRetentionPolicy"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk/*"
},
{
"Sid": "ELB",
"Effect": "Allow",
"Action": [
"elasticloadbalancing:RegisterTargets",
"elasticloadbalancing:DeRegisterTargets",
"elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
"elasticloadbalancing:RegisterInstancesWithLoadBalancer"
],
"Resource": [
"arn:aws:elasticloadbalancing:*:*:targetgroup/awseb-*",
"arn:aws:elasticloadbalancing:*:*:loadbalancer/awseb-e-*"
]
}
]
}
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or
delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User
Guide.
Alternatively, you can use an AWS managed policy to provide full access (p. 879) to Elastic Beanstalk.
877
AWS Elastic Beanstalk Developer Guide
Using service-linked roles
As an alternative, another user with permission to create service-linked roles can use IAM to pre-create
the service linked-role in advance. You can then create your environment even without having the
iam:CreateServiceLinkedRole permission.
You (or another user) can use the IAM console to create a service-linked role with the Elastic Beanstalk
Managed Updates use case. In the IAM CLI or the IAM API, create a service-linked role with the
managedupdates.elasticbeanstalk.amazonaws.com service name. For more information, see
Creating a Service-Linked Role in the IAM User Guide. If you delete this service-linked role, you can use
this same process to create the role again.
If you delete this service-linked role, and then need to create it again, you can
use the same process to recreate the role in your account. When you create an
Elastic Beanstalk environment using the Elastic Beanstalk API, enable managed
updates, and specify AWSServiceRoleForElasticBeanstalkManagedUpdates
as the value for the ServiceRoleForManagedUpdates option of the
aws:elasticbeanstalk:managedactions (p. 657) namespace, Elastic Beanstalk creates the
service-linked role for you again.
Before you can use IAM to delete a service-linked role, you must first be sure that Elastic Beanstalk
environments with managed updates enabled are either using a different service role or are terminated.
Note
If the Elastic Beanstalk service is using the service-linked role when you try to terminate the
environments, then the termination might fail. If that happens, wait for a few minutes and try
the operation again.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
878
AWS Elastic Beanstalk Developer Guide
User policies
See eb terminate (p. 1043) for details about terminating an Elastic Beanstalk environment using the EB
CLI.
See TerminateEnvironment for details about terminating an Elastic Beanstalk environment using the API.
Use the IAM console, the IAM CLI, or the IAM API to delete the
AWSServiceRoleForElasticBeanstalkManagedUpdates service-linked role. For more information, see
Deleting a Service-Linked Role in the IAM User Guide.
To view the content of a managed policy, use the Policies page in the IAM console.
Note
Previously, Elastic Beanstalk supported two other managed user policies,
AWSElasticBeanstalkFullAccess and AWSElasticBeanstalkReadOnlyAccess. We plan on
retiring these previous policies. You might still be able to see and use them in the IAM console.
Nevertheless, we recommend that you transition to using the new managed user policies, and
add custom policies to grant permissions to custom resources, if you have any.
879
AWS Elastic Beanstalk Developer Guide
User policies
In November 2019, Elastic Beanstalk released support for Amazon EC2 launch templates. This is a new
resource type that your environment's Auto Scaling group can use to launch Amazon EC2 instances, and
it requires new permissions. Most customers shouldn't be affected, because environments can still use
the legacy resource, launch configurations, if your user policy lacks the required permissions. However,
if you're trying to use a new feature that requires Amazon EC2 launch templates, and you have a custom
policy, your environment creation or update might fail. In this case, ensure that your custom policy has
the following permissions.
• EC2:CreateLaunchTemplate
• EC2:CreateLaunchTemplateVersions
• EC2:DeleteLaunchTemplate
• EC2:DeleteLaunchTemplateVersions
• EC2:DescribeLaunchTemplate
• EC2:DescribeLaunchTemplateVersions
An IAM policy contains policy statements that describe the permissions that you want to grant. When
you create a policy statement for Elastic Beanstalk, you need to understand how to use the following
four parts of a policy statement:
880
AWS Elastic Beanstalk Developer Guide
User policies
• Action specifies the API operations that you want to control. For example, use
elasticbeanstalk:CreateEnvironment to specify the CreateEnvironment operation. Certain
operations, such as creating an environment, require additional permissions to perform those actions.
For more information, see Resources and conditions for Elastic Beanstalk actions (p. 885).
Note
To use the UpdateTagsForResource API operation, specify one of the following two virtual
actions (or both) instead of the API operation name:
elasticbeanstalk:AddTags
The following sections demonstrate a few cases in which you might consider a custom user policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid":"CreateEnvironmentPerm",
"Action": [
"elasticbeanstalk:CreateEnvironment"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My First Elastic
Beanstalk Application/Test*"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My First Elastic Beanstalk Application"],
"elasticbeanstalk:FromApplicationVersion": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My First Elastic Beanstalk Application/First
Release"]
}
}
},
{
"Sid":"AllNonResourceCalls",
"Action":[
"elasticbeanstalk:CheckDNSAvailability",
"elasticbeanstalk:CreateStorageLocation"
],
"Effect":"Allow",
"Resource":[
"*"
]
881
AWS Elastic Beanstalk Developer Guide
User policies
}
]
}
The above policy shows how to grant limited access to Elastic Beanstalk operations. In order to actually
launch an environment, the user must have permission to create the AWS resources that power the
environment as well. For example, the following policy grants access to the default set of resources for a
web server environment:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:*",
"ecs:*",
"elasticloadbalancing:*",
"autoscaling:*",
"cloudwatch:*",
"s3:*",
"sns:*",
"cloudformation:*",
"sqs:*"
],
"Resource": "*"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:DeleteObject",
"s3:GetObjectAcl",
"s3:PutObjectAcl"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::elasticbeanstalk-*"
}
]
}
Note
To restrict these permissions to only the logs path, use the following resource format.
"arn:aws:s3:::elasticbeanstalk-us-east-2-123456789012/resources/environments/logs/
*"
882
AWS Elastic Beanstalk Developer Guide
User policies
Note
The policy doesn't deny access to any resources through other services. It demonstrates an
effective way to distribute responsibilities for managing Elastic Beanstalk applications among
different users, not as a way to secure the underlying resources.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"elasticbeanstalk:CreateApplication",
"elasticbeanstalk:DeleteApplication"
],
"Resource": [
"*"
]
},
{
"Effect": "Deny",
"Action": [
"elasticbeanstalk:CreateApplicationVersion",
"elasticbeanstalk:CreateConfigurationTemplate",
"elasticbeanstalk:CreateEnvironment",
"elasticbeanstalk:DeleteApplicationVersion",
"elasticbeanstalk:DeleteConfigurationTemplate",
"elasticbeanstalk:DeleteEnvironmentConfiguration",
"elasticbeanstalk:DescribeApplicationVersions",
"elasticbeanstalk:DescribeConfigurationOptions",
"elasticbeanstalk:DescribeConfigurationSettings",
"elasticbeanstalk:DescribeEnvironmentResources",
"elasticbeanstalk:DescribeEnvironments",
"elasticbeanstalk:DescribeEvents",
"elasticbeanstalk:DeleteEnvironmentConfiguration",
"elasticbeanstalk:RebuildEnvironment",
"elasticbeanstalk:RequestEnvironmentInfo",
"elasticbeanstalk:RestartAppServer",
"elasticbeanstalk:RetrieveEnvironmentInfo",
"elasticbeanstalk:SwapEnvironmentCNAMEs",
"elasticbeanstalk:TerminateEnvironment",
"elasticbeanstalk:UpdateApplicationVersion",
"elasticbeanstalk:UpdateConfigurationTemplate",
"elasticbeanstalk:UpdateEnvironment",
"elasticbeanstalk:RetrieveEnvironmentInfo",
"elasticbeanstalk:ValidateConfigurationSettings"
],
"Resource": [
"*"
],
"Condition": {
"StringNotEquals": {
"elasticbeanstalk:InApplication": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/myapplication"
]
}
}
}
]
}
883
AWS Elastic Beanstalk Developer Guide
ARN format
arn:aws:elasticbeanstalk:region:account-id:resource-type/resource-path
Where:
myApp/myEnvironment
Elastic Beanstalk has several types of resources you can specify in a policy. The following table shows the
ARN format for each resource type and an example.
application arn:aws:elasticbeanstalk:region:account-
id:application/application-name
Example: arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App
applicationversion
arn:aws:elasticbeanstalk:region:account-
id:applicationversion/application-name/version-label
Example: arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My Version
configurationtemplate
arn:aws:elasticbeanstalk:region:account-
id:configurationtemplate/application-name/template-name
Example: arn:aws:elasticbeanstalk:us-
east-2:123456789012:configurationtemplate/My App/My Template
environment arn:aws:elasticbeanstalk:region:account-
id:environment/application-name/environment-name
Example: arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/MyEnvironment
platform arn:aws:elasticbeanstalk:region:account-id:platform/platform-
name/platform-version
Example: arn:aws:elasticbeanstalk:us-east-2:123456789012:platform/
MyPlatform/1.0
884
AWS Elastic Beanstalk Developer Guide
Resources and conditions
solutionstack arn:aws:elasticbeanstalk:region::solutionstack/solutionstack-
name
Example: arn:aws:elasticbeanstalk:us-east-2::solutionstack/32bit
Amazon Linux running Tomcat 7
An environment, application version, and configuration template are always contained within a specific
application. You'll notice that these resources all have an application name in their resource path so that
they are uniquely identified by their resource name and the containing application. Although solution
stacks are used by configuration templates and environments, solution stacks are not specific to an
application or AWS account and do not have the application or AWS account in their ARNs.
Conditions enable you to specify permissions to resources that the action needs to complete. For
example, when you can call the CreateEnvironment action, you must also specify the application
version to deploy as well as the application that contains that application name. When you set
permissions for the CreateEnvironment action, you specify the application and application version
that you want the action to act upon by using the InApplication and FromApplicationVersion
conditions.
In addition, you can specify the environment configuration with a solution stack (FromSolutionStack)
or a configuration template (FromConfigurationTemplate). The following policy statement
allows the CreateEnvironment action to create an environment with the name myenv (specified by
Resource) in the application My App (specified by the InApplication condition) using the application
version My Version (FromApplicationVersion) with a 32bit Amazon Linux running Tomcat
7 configuration (FromSolutionStack):
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:CreateEnvironment"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromApplicationVersion": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My Version"],
"elasticbeanstalk:FromSolutionStack": ["arn:aws:elasticbeanstalk:us-
east-2::solutionstack/32bit Amazon Linux running Tomcat 7"]
}
}
}
]
885
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Note
Most condition keys mentioned in this topic are specific to Elastic Beanstalk, and their names
contain the elasticbeanstalk: prefix. For brevity, we omit this prefix from the condition
key names when we mention them in the following sections. For example, we mention
InApplication instead of its full name elasticbeanstalk:InApplication.
In contrast, we mention a few condition keys used across AWS services, and we include their
aws: prefix to highlight the exception.
Policy examples always show full condition key names, including the prefix.
Sections
• Policy information for Elastic Beanstalk actions (p. 886)
• Condition keys for Elastic Beanstalk actions (p. 908)
Policy information for Elastic Beanstalk actions, including resources, conditions, examples,
and dependencies
Action: AbortEnvironmentUpdate
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:AbortEnvironmentUpdate"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"
]
}
]
}
Action: CheckDNSAvailability
"*" N/A
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:CheckDNSAvailability"
],
"Effect": "Allow",
"Resource": "*"
886
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: ComposeEnvironments
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:ComposeEnvironments"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App"
]
}
]
}
Action: CreateApplication
Action: CreateApplicationVersion
887
AWS Elastic Beanstalk Developer Guide
Resources and conditions
applicationversion
InApplication This example allows the CreateApplicationVersion
action to create application versions with any name (*) in
aws:RequestTag/ the application My App:
key-name
(Optional) {
"Version": "2012-10-17",
aws:TagKeys "Statement": [
(Optional) {
"Action": [
"elasticbeanstalk:CreateApplicationVersion"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/*"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: CreateConfigurationTemplate
888
AWS Elastic Beanstalk Developer Guide
Resources and conditions
configurationtemplate
InApplication The following policy allows the
CreateConfigurationTemplate action to create
FromApplication configuration templates whose name begins with My
Template (My Template*) in the application My App:
FromApplicationVersion
{
FromConfigurationTemplate
"Version": "2012-10-17",
"Statement": [
FromEnvironment
{
"Action": [
FromSolutionStack
"elasticbeanstalk:CreateConfigurationTemplate"
aws:RequestTag/ ],
key-name "Effect": "Allow",
(Optional) "Resource": [
"arn:aws:elasticbeanstalk:us-
aws:TagKeys east-2:123456789012:configurationtemplate/My App/
(Optional) My Template*"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromSolutionStack":
["arn:aws:elasticbeanstalk:us-
east-2::solutionstack/32bit Amazon Linux running
Tomcat 7"]
}
}
}
]
}
Action: CreateEnvironment
889
AWS Elastic Beanstalk Developer Guide
Resources and conditions
FromSolutionStack{
"Version": "2012-10-17",
"Statement": [
aws:RequestTag/
{
key-name "Action": [
(Optional) "elasticbeanstalk:CreateEnvironment"
],
aws:TagKeys "Effect": "Allow",
(Optional) "Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromApplicationVersion":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"],
"elasticbeanstalk:FromSolutionStack":
["arn:aws:elasticbeanstalk:us-
east-2::solutionstack/32bit Amazon Linux running
Tomcat 7"]
}
}
}
]
}
Action: CreatePlatformVersion
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:CreatePlatformVersion"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:platform/us-east-2_*"
]
}
]
}
890
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: CreateStorageLocation
"*" N/A
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:CreateStorageLocation"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Action: DeleteApplication
Action: DeleteApplicationVersion
891
AWS Elastic Beanstalk Developer Guide
Resources and conditions
applicationversion
InApplication The following policy allows the
DeleteApplicationVersion action to delete an
aws:ResourceTag/ application version whose name is My Version in the
key-name application My App:
(Optional)
{
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": [
"elasticbeanstalk:DeleteApplicationVersion"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: DeleteConfigurationTemplate
configurationtemplate
InApplication The following policy allows the
(Optional) DeleteConfigurationTemplate action to delete a
configuration template whose name is My Template in
aws:ResourceTag/ the application My App. Specifying the application name
key-name as a condition is optional.
(Optional)
{
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": [
"elasticbeanstalk:DeleteConfigurationTemplate"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:configurationtemplate/My App/
My Template"
]
}
]
}
Action: DeleteEnvironmentConfiguration
892
AWS Elastic Beanstalk Developer Guide
Resources and conditions
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:DeleteEnvironmentConfiguration"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
]
}
]
}
Action: DeletePlatformVersion
Action: DescribeApplications
893
AWS Elastic Beanstalk Developer Guide
Resources and conditions
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:DescribeApplications"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"
]
}
]
}
Action: DescribeApplicationVersions
applicationversion
InApplication The following policy allows the
(Optional) DescribeApplicationVersions action to describe
the application version My Version in the application
aws:ResourceTag/ My App. Specifying the application name as a condition is
key-name optional.
(Optional)
{
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": [
"elasticbeanstalk:DescribeApplicationVersions"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"
]
}
]
}
Action: DescribeConfigurationOptions
894
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: DescribeConfigurationSettings
Action: DescribeEnvironmentHealth
895
AWS Elastic Beanstalk Developer Guide
Resources and conditions
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action":
"elasticbeanstalk:DescribeEnvironmentHealth",
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
]
}
]
}
Action: DescribeEnvironmentResources
Action: DescribeEnvironments
896
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: DescribeEvents
environment {
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": "elasticbeanstalk:DescribeEvents",
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv",
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: DescribeInstancesHealth
897
AWS Elastic Beanstalk Developer Guide
Resources and conditions
{
"Version": "2012-10-17",
"Statement": [
{
"Action":
"elasticbeanstalk:DescribeInstancesHealth",
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
]
}
]
}
Action: DescribePlatformVersion
Action: ListAvailableSolutionStacks
898
AWS Elastic Beanstalk Developer Guide
Resources and conditions
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:ListAvailableSolutionStacks"
],
"Effect": "Allow",
"Resource": "arn:aws:elasticbeanstalk:us-
east-2::solutionstack/32bit Amazon Linux running
Tomcat 7"
}
]
}
Action: ListPlatformVersions
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:ListPlatformVersions"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:platform/us-east-2_*"
]
}
]
}
Action: ListTagsForResource
899
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: RebuildEnvironment
Action: RequestEnvironmentInfo
900
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: RestartAppServer
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:RestartAppServer"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: RetrieveEnvironmentInfo
901
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: SwapEnvironmentCNAMEs
Action: TerminateEnvironment
902
AWS Elastic Beanstalk Developer Guide
Resources and conditions
Action: UpdateApplication
Action: UpdateApplicationResourceLifecycle
903
AWS Elastic Beanstalk Developer Guide
Resources and conditions
aws:TagKeys {
(Optional) "Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:UpdateApplicationResourceLifecycle"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"
]
}
]
}
Action: UpdateApplicationVersion
applicationversion
InApplication The following policy allows the
UpdateApplicationVersion action to update the
aws:ResourceTag/ properties of the application version My Version in the
key-name application My App.
(Optional)
{
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": [
"elasticbeanstalk:UpdateApplicationVersion"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: UpdateConfigurationTemplate
904
AWS Elastic Beanstalk Developer Guide
Resources and conditions
configurationtemplate
InApplication The following policy allows the
UpdateConfigurationTemplate action to update the
aws:ResourceTag/ properties or options of the configuration template My
key-name Template in the application My App.
(Optional)
{
aws:TagKeys "Version": "2012-10-17",
(Optional) "Statement": [
{
"Action": [
"elasticbeanstalk:UpdateConfigurationTemplate"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:configurationtemplate/My App/
My Template"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
Action: UpdateEnvironment
905
AWS Elastic Beanstalk Developer Guide
Resources and conditions
aws:ResourceTag/ {
"Version": "2012-10-17",
key-name
"Statement": [
(Optional) {
"Action": [
aws:TagKeys "elasticbeanstalk:UpdateEnvironment"
(Optional) ],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromApplicationVersion":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My
Version"]
}
}
}
]
}
906
AWS Elastic Beanstalk Developer Guide
Resources and conditions
platform {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:RemoveTags"
],
"Effect": "Deny",
"Resource": "*",
"Condition": {
"ForAnyValue:StringEquals": {
"aws:TagKeys": ["stage"]
}
}
}
]
}
Action: ValidateConfigurationSettings
"elasticbeanstalk:ValidateConfigurationSettings"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-
east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication":
["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
907
AWS Elastic Beanstalk Developer Guide
Resources and conditions
InApplication
Specifies the application that contains the resource that the action operates on.
The following example allows the UpdateApplicationVersion action to update the properties
of the application version My Version. The InApplication condition specifies My App as the
container for My Version.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:UpdateApplicationVersion"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:applicationversion/My App/My
Version"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"]
}
}
}
]
}
FromApplicationVersion
The following example allows the UpdateEnvironment action to update the environment myenv in
the application My App. The FromApplicationVersion condition constrains the VersionLabel
parameter to allow only the application version My Version to update the environment.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:UpdateEnvironment"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromApplicationVersion": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:applicationversion/My App/My Version"]
}
}
908
AWS Elastic Beanstalk Developer Guide
Resources and conditions
}
]
}
FromConfigurationTemplate
The following example allows the UpdateEnvironment action to update the environment
myenv in the application My App. The FromConfigurationTemplate condition constrains the
TemplateName parameter to allow only the configuration template My Template to update the
environment.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:UpdateEnvironment"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/myenv"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromConfigurationTemplate": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:configurationtemplate/My App/My Template"]
}
}
}
]
}
FromEnvironment
The following example allows the SwapEnvironmentCNAMEs action to swap the CNAMEs in
My App for all environments whose names begin with mysrcenv and mydestenv but not those
environments whose names begin with mysrcenvPROD* and mydestenvPROD*.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:SwapEnvironmentCNAMEs"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/mysrcenv*",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/mydestenv*"
],
"Condition": {
"StringNotLike": {
"elasticbeanstalk:FromEnvironment": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/
mysrcenvPROD*",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/My App/
mydestenvPROD*"
909
AWS Elastic Beanstalk Developer Guide
Tag-based access control
]
}
}
}
]
}
FromSolutionStack
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"elasticbeanstalk:CreateConfigurationTemplate"
],
"Effect": "Allow",
"Resource": [
"arn:aws:elasticbeanstalk:us-east-2:123456789012:configurationtemplate/My App/
My Template*"
],
"Condition": {
"StringEquals": {
"elasticbeanstalk:InApplication": ["arn:aws:elasticbeanstalk:us-
east-2:123456789012:application/My App"],
"elasticbeanstalk:FromSolutionStack": ["arn:aws:elasticbeanstalk:us-
east-2::solutionstack/32bit Amazon Linux running Tomcat 7"]
}
}
}
]
}
Specify tag-based conditions. For details, see Using tags to control access to Elastic Beanstalk
resources (p. 910).
When you design IAM policies, you might be setting granular permissions by granting access to specific
resources. As the number of resources that you manage grows, this task becomes more difficult. Tagging
resources and using tags in policy statement conditions can make this task easier. You grant access in
910
AWS Elastic Beanstalk Developer Guide
Tag-based access control
bulk to any resource with a certain tag. Then you repeatedly apply this tag to relevant resources, during
creation or later.
Tags can be attached to the resource or passed in the request to services that support tagging. In Elastic
Beanstalk, resources can have tags, and some actions can include tags. When you create an IAM policy,
you can use tag condition keys to control:
• Which users can perform actions on an environment, based on tags that it already has.
• What tags can be passed in an action's request.
• Whether specific tag keys can be used in a request.
For the complete syntax and semantics of tag condition keys, see Controlling Access Using Tags in the
IAM User Guide.
The following examples demonstrate how to specify tag conditions in policies for Elastic Beanstalk users.
The following policy limits this power and denies unauthorized users permission to create Elastic
Beanstalk production environments. To do that, it denies the CreateEnvironment action if the request
specifies a tag named stage with one of the values gamma or prod. In addition, the policy prevents
these unauthorized users from tampering with the stage of production environments by not allowing
tag modification actions to include these same tag values or to completely remove the stage tag.
A customer's administrator must attach this IAM policy to unauthorized IAM users, in addition to the
managed user policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"elasticbeanstalk:CreateEnvironment",
"elasticbeanstalk:AddTags"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:RequestTag/stage": ["gamma", "prod"]
}
}
},
{
"Effect": "Deny",
"Action": [
"elasticbeanstalk:RemoveTags"
],
"Resource": "*",
"Condition": {
"ForAnyValue:StringEquals": {
"aws:TagKeys": ["stage"]
}
}
}
]
}
911
AWS Elastic Beanstalk Developer Guide
Tag-based access control
The following policy limits this power and denies unauthorized users permission to perform actions on
Elastic Beanstalk production environments. To do that, it denies specific actions if the environment has
a tag named stage with one of the values gamma or prod. A customer's administrator must attach this
IAM policy to unauthorized IAM users, in addition to the managed user policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"elasticbeanstalk:AddTags",
"elasticbeanstalk:RemoveTags",
"elasticbeanstalk:DescribeEnvironments",
"elasticbeanstalk:TerminateEnvironment",
"elasticbeanstalk:UpdateEnvironment",
"elasticbeanstalk:ListTagsForResource"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/stage": ["gamma", "prod"]
}
}
}
]
}
The following policy grants users permission to create Elastic Beanstalk development applications.
To do that, it allows the CreateApplicationand AddTags actions if the request specifies a tag named
stage with the value development. The aws:TagKeys condition ensures that the user can't add
other tag keys. In particular, it ensures case sensitivity of the stage tag key. Notice that this policy is
useful for IAM users that don't have the Elastic Beanstalk AdministratorAccess-AWSElasticBeanstalk
managed user policy attached. The managed policy gives users unlimited permission to perform any
Elastic Beanstalk action on any Elastic Beanstalk-managed resource.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticbeanstalk:CreateApplication",
"elasticbeanstalk:AddTags"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:RequestTag/stage": "development"
},
"ForAllValues:StringEquals": {
"aws:TagKeys": ["stage"]
912
AWS Elastic Beanstalk Developer Guide
Example managed policies
}
}
}
]
}
The following policy grants users permission to perform actions on, and get information about, Elastic
Beanstalk development applications.
To do that, it allows specific actions if the application has a tag named stage with the value
development. The aws:TagKeys condition ensures that the user can't add other tag keys. In particular,
it ensures case sensitivity of the stage tag key. Notice that this policy is useful for IAM users that don't
have the Elastic Beanstalk AdministratorAccess-AWSElasticBeanstalk managed user policy attached.
The managed policy gives users unlimited permission to perform any Elastic Beanstalk action on any
Elastic Beanstalk-managed resource.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticbeanstalk:UpdateApplication",
"elasticbeanstalk:DeleteApplication",
"elasticbeanstalk:DescribeApplications"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/stage": "development"
},
"ForAllValues:StringEquals": {
"aws:TagKeys": ["stage"]
}
}
}
]
}
In this scenario, Example Corp. is a software company with three teams responsible for the company
website: administrators who manage the infrastructure, developers who build the software for the
website, and a QA team that tests the website. To help manage permissions to their Elastic Beanstalk
resources, Example Corp. creates three groups to which members of each respective team belong:
Admins, Developers, and Testers. Example Corp. wants the Admins group to have full access to all
applications, environments, and their underlying resources so that they can create, troubleshoot, and
delete all Elastic Beanstalk assets. Developers require permissions to view all Elastic Beanstalk assets and
to create and deploy application versions. Developers should not be able to create new applications or
environments or terminate running environments. Testers need to view all Elastic Beanstalk resources to
monitor and test applications. The Testers should not be able to make changes to any Elastic Beanstalk
resources.
913
AWS Elastic Beanstalk Developer Guide
Example managed policies
The following example policies provide the required permissions for each group.
Note that this policy is an example. It gives a broad set of permissions to the AWS services that Elastic
Beanstalk uses to manage applications and environments. For example, ec2:* allows an AWS Identity
and Access Management (IAM) user to perform any action on any Amazon EC2 resource in the AWS
account. These permissions are not limited to the resources that you use with Elastic Beanstalk. As a best
practice, you should grant individuals only the permissions they need to perform their duties.
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"elasticbeanstalk:*",
"ec2:*",
"elasticloadbalancing:*",
"autoscaling:*",
"cloudwatch:*",
"s3:*",
"sns:*",
"rds:*",
"cloudformation:*"
],
"Resource" : "*"
}
]
}
Note that this policy is an example. It gives a broad set of permissions to the AWS products that Elastic
Beanstalk uses to manage applications and environments. For example, ec2:* allows an IAM user to
914
AWS Elastic Beanstalk Developer Guide
Example managed policies
perform any action on any Amazon EC2 resource in the AWS account. These permissions are not limited
to the resources that you use with Elastic Beanstalk. As a best practice, you should grant individuals only
the permissions they need to perform their duties.
{
"Version" : "2012-10-17",
"Statement" : [
{
"Action" : [
"elasticbeanstalk:CreateApplication",
"elasticbeanstalk:CreateEnvironment",
"elasticbeanstalk:DeleteApplication",
"elasticbeanstalk:RebuildEnvironment",
"elasticbeanstalk:SwapEnvironmentCNAMEs",
"elasticbeanstalk:TerminateEnvironment"],
"Effect" : "Deny",
"Resource" : "*"
},
{
"Action" : [
"elasticbeanstalk:*",
"ec2:*",
"elasticloadbalancing:*",
"autoscaling:*",
"cloudwatch:*",
"s3:*",
"sns:*",
"rds:*",
"cloudformation:*"],
"Effect" : "Allow",
"Resource" : "*"
}
]
}
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"elasticbeanstalk:Check*",
"elasticbeanstalk:Describe*",
"elasticbeanstalk:List*",
"elasticbeanstalk:RequestEnvironmentInfo",
"elasticbeanstalk:RetrieveEnvironmentInfo",
"ec2:Describe*",
"elasticloadbalancing:Describe*",
"autoscaling:Describe*",
"cloudwatch:Describe*",
"cloudwatch:List*",
"cloudwatch:Get*",
"s3:Get*",
"s3:List*",
"sns:Get*",
"sns:List*",
"rds:Describe*",
915
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
"cloudformation:Describe*",
"cloudformation:Get*",
"cloudformation:List*",
"cloudformation:Validate*",
"cloudformation:Estimate*"
],
"Resource" : "*"
}
]
}
In our use case, Example Corp. is a small consulting firm developing applications for two different
customers. John is the development manager overseeing the development of the two Elastic Beanstalk
applications, app1 and app2. John does development and some testing on the two applications, and only
he can update the production environment for the two applications. These are the permissions that he
needs for app1 and app2:
Jill is a tester who needs access to view the following resources in order to monitor and test the two
applications: applications, application versions, environments, and configuration templates. However, she
should not be able to make changes to any Elastic Beanstalk resources.
Jack is the developer for app1 who needs access to view all resources for app1 and also needs to create
application versions for app1 and deploy them to the staging environment.
Judy is the administrator of the AWS account for Example Corp. She has created IAM users for John, Jill,
and Jack and attaches the following policies to those users to grant the appropriate permissions to the
app1 and app2 applications.
The first policy specifies actions for Auto Scaling, Amazon S3, Amazon EC2, CloudWatch, Amazon
SNS, Elastic Load Balancing, Amazon RDS, and AWS CloudFormation. Elastic Beanstalk relies on these
additional services to provision underlying resources when creating an environment.
Note that this policy is an example. It gives a broad set of permissions to the AWS products that Elastic
Beanstalk uses to manage applications and environments. For example, ec2:* allows an IAM user to
perform any action on any Amazon EC2 resource in the AWS account. These permissions are not limited
to the resources that you use with Elastic Beanstalk. As a best practice, you should grant individuals only
the permissions they need to perform their duties.
916
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
{
"Version": "2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"ec2:*",
"ecs:*",
"ecr:*",
"elasticloadbalancing:*",
"autoscaling:*",
"cloudwatch:*",
"s3:*",
"sns:*",
"cloudformation:*",
"dynamodb:*",
"rds:*",
"sqs:*",
"logs:*",
"iam:GetPolicyVersion",
"iam:GetRole",
"iam:PassRole",
"iam:ListRolePolicies",
"iam:ListAttachedRolePolicies",
"iam:ListInstanceProfiles",
"iam:ListRoles",
"iam:ListServerCertificates",
"acm:DescribeCertificate",
"acm:ListCertificates",
"codebuild:CreateProject",
"codebuild:DeleteProject",
"codebuild:BatchGetBuilds",
"codebuild:StartBuild"
],
"Resource":"*"
}
]
}
The second policy specifies the Elastic Beanstalk actions that John is allowed to perform on
the app1 and app2 resources. The AllCallsInApplications statement allows all Elastic
Beanstalk actions ("elasticbeanstalk:*") performed on all resources within app1 and app2
(for example, elasticbeanstalk:CreateEnvironment). The AllCallsOnApplications
statement allows all Elastic Beanstalk actions ("elasticbeanstalk:*") on the app1 and
app2 application resources (for example, elasticbeanstalk:DescribeApplications,
elasticbeanstalk:UpdateApplication, etc.). The AllCallsOnSolutionStacks statement
allows all Elastic Beanstalk actions ("elasticbeanstalk:*") for solution stack resources (for example,
elasticbeanstalk:ListAvailableSolutionStacks).
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllCallsInApplications",
"Action":[
"elasticbeanstalk:*"
],
"Effect":"Allow",
"Resource":[
"*"
],
"Condition":{
"StringEquals":{
917
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
"elasticbeanstalk:InApplication":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app2"
]
}
}
},
{
"Sid":"AllCallsOnApplications",
"Action":[
"elasticbeanstalk:*"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app2"
]
},
{
"Sid":"AllCallsOnSolutionStacks",
"Action":[
"elasticbeanstalk:*"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2::solutionstack/*"
]
}
]
}
The third policy specifies the Elastic Beanstalk actions that the second policy needs permissions
to in order to complete those Elastic Beanstalk actions. The AllNonResourceCalls
statement allows the elasticbeanstalk:CheckDNSAvailability action, which is
required to call elasticbeanstalk:CreateEnvironment and other actions. It also
allows the elasticbeanstalk:CreateStorageLocation action, which is required for
elasticbeanstalk:CreateApplication, elasticbeanstalk:CreateEnvironment, and other
actions.
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllNonResourceCalls",
"Action":[
"elasticbeanstalk:CheckDNSAvailability",
"elasticbeanstalk:CreateStorageLocation"
],
"Effect":"Allow",
"Resource":[
"*"
]
}
]
}
918
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
The first policy specifies Describe*, List*, and Get* actions on Auto Scaling, Amazon S3, Amazon
EC2, CloudWatch, Amazon SNS, Elastic Load Balancing, Amazon RDS, and AWS CloudFormation (for non-
legacy container types) so that the Elastic Beanstalk actions are able to retrieve the relevant information
about the underlying resources of the app1 and app2 applications.
{
"Version": "2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"ec2:Describe*",
"elasticloadbalancing:Describe*",
"autoscaling:Describe*",
"cloudwatch:Describe*",
"cloudwatch:List*",
"cloudwatch:Get*",
"s3:Get*",
"s3:List*",
"sns:Get*",
"sns:List*",
"rds:Describe*",
"cloudformation:Describe*",
"cloudformation:Get*",
"cloudformation:List*",
"cloudformation:Validate*",
"cloudformation:Estimate*"
],
"Resource":"*"
}
]
}
The second policy specifies the Elastic Beanstalk actions that Jill is allowed to perform on the app1 and
app2 resources. The AllReadCallsInApplications statement allows her to call the Describe*
actions and the environment info actions. The AllReadCallsOnApplications statement allows her
to call the DescribeApplications and DescribeEvents actions on the app1 and app2 application
resources. The AllReadCallsOnSolutionStacks statement allows viewing actions that involve
solution stack resources (ListAvailableSolutionStacks, DescribeConfigurationOptions, and
ValidateConfigurationSettings).
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllReadCallsInApplications",
"Action":[
"elasticbeanstalk:Describe*",
"elasticbeanstalk:RequestEnvironmentInfo",
"elasticbeanstalk:RetrieveEnvironmentInfo"
],
"Effect":"Allow",
"Resource":[
"*"
],
"Condition":{
"StringEquals":{
"elasticbeanstalk:InApplication":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app2"
]
}
}
919
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
},
{
"Sid":"AllReadCallsOnApplications",
"Action":[
"elasticbeanstalk:DescribeApplications",
"elasticbeanstalk:DescribeEvents"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1",
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app2"
]
},
{
"Sid":"AllReadCallsOnSolutionStacks",
"Action":[
"elasticbeanstalk:ListAvailableSolutionStacks",
"elasticbeanstalk:DescribeConfigurationOptions",
"elasticbeanstalk:ValidateConfigurationSettings"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2::solutionstack/*"
]
}
]
}
The third policy specifies the Elastic Beanstalk actions that the second policy needs permissions to in
order to complete those Elastic Beanstalk actions. The AllNonResourceCalls statement allows the
elasticbeanstalk:CheckDNSAvailability action, which is required for some viewing actions.
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllNonResourceCalls",
"Action":[
"elasticbeanstalk:CheckDNSAvailability"
],
"Effect":"Allow",
"Resource":[
"*"
]
}
]
}
The first policy specifies the actions on Auto Scaling, Amazon S3, Amazon EC2, CloudWatch, Amazon
SNS, Elastic Load Balancing, Amazon RDS, and AWS CloudFormation (for non-legacy container types) so
that the Elastic Beanstalk actions are able to view and work with the underlying resources of app1. For
a list of supported non-legacy container types, see the section called “Why are some platform versions
marked legacy?” (p. 470)
Note that this policy is an example. It gives a broad set of permissions to the AWS products that Elastic
Beanstalk uses to manage applications and environments. For example, ec2:* allows an IAM user to
920
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
perform any action on any Amazon EC2 resource in the AWS account. These permissions are not limited
to the resources that you use with Elastic Beanstalk. As a best practice, you should grant individuals only
the permissions they need to perform their duties.
{
"Version": "2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"ec2:*",
"elasticloadbalancing:*",
"autoscaling:*",
"cloudwatch:*",
"s3:*",
"sns:*",
"rds:*",
"cloudformation:*"
],
"Resource":"*"
}
]
}
The second policy specifies the Elastic Beanstalk actions that Jack is allowed to perform on the app1
resource.
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllReadCallsAndAllVersionCallsInApplications",
"Action":[
"elasticbeanstalk:Describe*",
"elasticbeanstalk:RequestEnvironmentInfo",
"elasticbeanstalk:RetrieveEnvironmentInfo",
"elasticbeanstalk:CreateApplicationVersion",
"elasticbeanstalk:DeleteApplicationVersion",
"elasticbeanstalk:UpdateApplicationVersion"
],
"Effect":"Allow",
"Resource":[
"*"
],
"Condition":{
"StringEquals":{
"elasticbeanstalk:InApplication":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1"
]
}
}
},
{
"Sid":"AllReadCallsOnApplications",
"Action":[
"elasticbeanstalk:DescribeApplications",
"elasticbeanstalk:DescribeEvents"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1"
]
},
{
921
AWS Elastic Beanstalk Developer Guide
Example resource-specific policies
"Sid":"UpdateEnvironmentInApplications",
"Action":[
"elasticbeanstalk:UpdateEnvironment"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:environment/app1/app1-
staging*"
],
"Condition":{
"StringEquals":{
"elasticbeanstalk:InApplication":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:application/app1"
]
},
"StringLike":{
"elasticbeanstalk:FromApplicationVersion":[
"arn:aws:elasticbeanstalk:us-east-2:123456789012:applicationversion/app1/
*"
]
}
}
},
{
"Sid":"AllReadCallsOnSolutionStacks",
"Action":[
"elasticbeanstalk:ListAvailableSolutionStacks",
"elasticbeanstalk:DescribeConfigurationOptions",
"elasticbeanstalk:ValidateConfigurationSettings"
],
"Effect":"Allow",
"Resource":[
"arn:aws:elasticbeanstalk:us-east-2::solutionstack/*"
]
}
]
}
The third policy specifies the Elastic Beanstalk actions that the second policy needs permissions
to in order to complete those Elastic Beanstalk actions. The AllNonResourceCalls
statement allows the elasticbeanstalk:CheckDNSAvailability action, which is
required to call elasticbeanstalk:CreateEnvironment and other actions. It also
allows the elasticbeanstalk:CreateStorageLocation action, which is required for
elasticbeanstalk:CreateEnvironment, and other actions.
{
"Version": "2012-10-17",
"Statement":[
{
"Sid":"AllNonResourceCalls",
"Action":[
"elasticbeanstalk:CheckDNSAvailability",
"elasticbeanstalk:CreateStorageLocation"
],
"Effect":"Allow",
"Resource":[
"*"
]
}
]
}
922
AWS Elastic Beanstalk Developer Guide
Amazon RDS
You can use either approach to run a database instance in Amazon RDS and configure your application
to connect to it on launch. You can connect multiple environments to a database and also perform
seamless updates with blue-green deployments.
Note
If you haven't used a database instance with your application before, we recommend that
you add a database to a test environment with the Elastic Beanstalk console first. By doing
this, you can verify that your application can read the environment properties, construct a
connection string, and connect to a database instance, without the additional configuration
work required for a standalone database. For more information, see Adding a database to your
Elastic Beanstalk environment (p. 577).
To allow the Amazon EC2 instances in your environment to connect to an outside database, configure
an additional security group for the Auto Scaling group that's associated with your environment. You
can attach the same security group that's attached to your database instance. Or, you can use a separate
security group. If you attach a different security group, you must configure the security group that's
attached to your database to allow inbound access from this security group.
Note
You can connect your environment to a database by adding a rule to the security group that's
attached to your database. This rule must allow inbound access from the autogenerated security
group that Elastic Beanstalk attaches to the Auto Scaling group for your environment. However,
know that, by creating this rule, you also create a dependency between the two security groups.
Subsequently, when you attempt to terminate the environment, Elastic Beanstalk will be unable
to delete the environment's security group, because the database's security group is dependent
on it.
After you launch your database instance and configure security groups, you can pass the connection
information, such as the endpoint and password, to your application by using environment properties.
This is the same mechanism that Elastic Beanstalk uses in the background when you run a database
instance in your environment.
For an additional layer of security, you can store your connection information in Amazon S3,
and configure Elastic Beanstalk to retrieve it during deployment. With configuration files
(.ebextensions) (p. 683), you can configure the instances in your environment to securely retrieve files
from Amazon S3 when you deploy your application.
Topics
• Launching and connecting to an external Amazon RDS instance in a default VPC (p. 924)
• Launching and connecting to an external Amazon RDS instance in EC2 classic (p. 929)
• Storing the connection string in Amazon S3 (p. 933)
• Cleaning up an external Amazon RDS instance (p. 935)
923
AWS Elastic Beanstalk Developer Guide
Amazon RDS in default VPC
Or, as an alternative to launching a new DB instance, you can start with a database that was previously
created by Elastic Beanstalk (p. 577) and subsequently decoupled (p. 581) from a Beanstalk environment.
For more information, see the section called “Database” (p. 577). With this option, you don't need
to complete the procedure for launching a new database. However, you do need to complete the
subsequent procedures that are described in this topic.
The following procedures describe the process for a default VPC. The process is the same if you're using
a custom VPC. The only additional requirements are that your environment and DB instance are in the
same subnet, or in subnets that are allowed to communicate with each other. For more information
about configuring a custom VPC to use with Elastic Beanstalk, see Using Elastic Beanstalk with Amazon
VPC (p. 938).
Note
• If you’re starting with a database that was created by Elastic Beanstalk and subsequently
decoupled from a Beanstalk environment, you can skip the first group of steps and continue
with the steps grouped under To modify the inbound rules on your RDS instance's security
group.
• If you plan to use the database that you decouple for a production environment, verify the
storage type that the database uses is suitable for your workload. For more information, see
DB Instance Storage and Modifying a DB instance in the Amazon RDS User Guide.
• DB instance class – Choose an instance size that has an appropriate amount of memory and CPU
power for your workload.
• Multi-AZ deployment – For high availability, set this to Create an Aurora Replica/Reader node in
a different AZ.
• Master username and Master password – The database username and password. Make a note of
these settings because you will use them later.
7. Verify the default settings for the remaining options, and then choose Create database.
924
AWS Elastic Beanstalk Developer Guide
Amazon RDS in default VPC
Next, modify the security group that's attached to your DB instance to allow inbound traffic on
the appropriate port. This is the same security group that you will attach to your Elastic Beanstalk
environment later. As a result, the rule that you add will grant inbound access permission to other
resources in the same security group.
To modify the inbound rules on the security group that's attached to your RDS instance
925
AWS Elastic Beanstalk Developer Guide
Amazon RDS in default VPC
Next, add the security group for the DB instance to your running environment. In this procedure Elastic
Beanstalk reprovisions all instances in your environment with the additional security group attached.
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Environments, and then choose the name of your
environment from the list.
Note
If you have many environments, use the search bar to filter the environment list.
c. In the navigation pane, choose Configuration.
d. In the Instances configuration category, choose Edit.
e. Under EC2 security groups, choose the security group to attach to the instances, in
addition to the instance security group that Elastic Beanstalk creates.
f. Choose Apply.
g. Read the warning, and then choose Confirm.
• To add a security group using a configuration file (p. 683), use the securitygroup-
addexisting.config example file.
Next, pass the connection information to your environment by using environment properties. When you
add a DB instance to your environment (p. 577) with the Elastic Beanstalk console, Elastic Beanstalk uses
environment properties, such as RDS_HOSTNAME, to pass connection information to your application.
You can use the same properties. By doing this, you use the same application code with both integrated
DB instances and external DB instances. Or, alternatively, you can choose your own property names.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
926
AWS Elastic Beanstalk Developer Guide
Amazon RDS in default VPC
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Environment properties section, define the variables that your application reads to construct
a connection string. For compatibility with environments that have an integrated RDS DB instance,
use the following names and values. You can find all values, except for your password, in the RDS
console.
927
AWS Elastic Beanstalk Developer Guide
Amazon RDS in default VPC
6. Choose Apply.
If you didn't program your application to read environment properties and construct a connection string
yet, see the following language-specific topics for instructions:
Finally, depending on when your application reads environment variables, you might need to restart the
application server on the instances in your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
928
AWS Elastic Beanstalk Developer Guide
Amazon RDS in EC2 classic
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Restart app server(s).
If you use EC2 Classic (no VPC) with AWS Elastic Beanstalk, the procedure changes slightly due to
differences in how security groups work. In EC2 Classic, DB instances can't use EC2 security groups, so
they get a DB security group that works only with Amazon RDS.
You can add rules to a DB security group that allow inbound access from EC2 security groups. However,
you can't attach a DB security group to the Auto Scaling group that's associated with your environment.
To avoid creating a dependency between the DB security group and your environment, you must create
a third security group in Amazon EC2. Then, you need to add a rule in the DB security group to grant
inbound access to the new security group. Last, you should assign it to the Auto Scaling group in your
Elastic Beanstalk environment.
Note
• If you’re starting with a database that was created by Elastic Beanstalk and subsequently
decoupled from a Beanstalk environment, you can skip the first group of steps and continue
with the steps grouped under To create a bridge security group.
• If you plan to use the database that you decouple for a production environment, verify the
storage type that the database uses is suitable for your workload. For more information, see
DB Instance Storage and Modifying a DB instance in the Amazon RDS User Guide.
• Master Username
• Master Password
4. When you reach Configure advanced settings, for Network and Security settings, choose the
following:
• VPC – Not in VPC. If this option isn't available, your account might not support EC2-Classic, or
you might have chosen an instance type that is only available in VPC.
• Availability Zone – No Preference
• DB Security Group(s) – Create new Security Group
5. Configure the remaining options and choose Create database. Note the values that you enter for the
following options:
929
AWS Elastic Beanstalk Developer Guide
Amazon RDS in EC2 classic
• Database Name
• Database Port
In EC2-Classic, your DB instance has a DB security group instead of a VPC security group. You can't attach
a DB security group to your Elastic Beanstalk environment. Instead you need to create a new security
group that you can authorize to access the DB instance and attach to your environment. We will refer to
this as a bridge security group and name it webapp-bridge.
Next, modify the security group attached to your DB instance to allow inbound traffic from the bridge
security group.
To modify the ingress rules on the security group for your RDS instance
Next, add the bridge security group to your running environment. This procedure requires all instances in
your environment to be reprovisioned with the additional security group attached.
a. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
b. In the navigation pane, choose Environments, and then choose the name of your
environment from the list.
Note
If you have many environments, use the search bar to filter the environment list.
c. In the navigation pane, choose Configuration.
d. In the Instances configuration category, choose Edit.
930
AWS Elastic Beanstalk Developer Guide
Amazon RDS in EC2 classic
e. Under EC2 security groups, choose the security group to attach to the instances, in
addition to the instance security group that Elastic Beanstalk creates.
f. Choose Apply.
g. Read the warning, and then choose Confirm.
• To add a security group using a configuration file (p. 683), use the securitygroup-
addexisting.config example file.
Next, pass the connection information to your environment by using environment properties. When you
add a DB instance to your environment (p. 577) with the Elastic Beanstalk console, Elastic Beanstalk uses
environment properties such as RDS_HOSTNAME to pass connection information to your application.
You can use the same properties in order to use the same application code with both integrated DB
instances and external DB instances. Or, alternatively, you can choose your own property names.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
Note
If you have many environments, use the search bar to filter the environment list.
3. In the navigation pane, choose Configuration.
4. In the Software configuration category, choose Edit.
5. In the Environment Properties section, define the variables that your application reads to construct
a connection string. For compatibility with environments that have an integrated RDS instance, use
the following:
931
AWS Elastic Beanstalk Developer Guide
Amazon RDS in EC2 classic
6. Choose Apply
If you didn't already program your application to read environment properties and construct a
connection string, see the following language-specific topics for instructions:
Finally, depending on when your application reads environment variables, you might need to restart the
application server on the instances in your environment.
1. Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.
2. In the navigation pane, choose Environments, and then choose the name of your environment from
the list.
932
AWS Elastic Beanstalk Developer Guide
Connection string in Amazon S3
Note
If you have many environments, use the search bar to filter the environment list.
3. Choose Environment actions, and then choose Restart app server(s).
To prevent this situation, we recommend that you lock down your connection information by storing it in
an Amazon S3 bucket instead. The main steps are as follows:
First, create a bucket to store the file that contains your connection string. For this example, a JSON
file that has a single key and value is used. The value is a JDBC connection string for a PostgreSQL DB
instance in Amazon RDS.
beanstalk-database.json
{
"connection": "jdbc:postgresql://mydb.b5uacpxznijm.us-west-2.rds.amazonaws.com:5432/ebdb?
user=username&password=mypassword"
}
The highlighted portions of the URL correspond to the endpoint, port, DB name, user name, and
password for the database.
By default, your account owns the file and has permission to manage it. However, IAM users and roles
only have this permission if you grant them access explicitly. Grant the instances in your Elastic Beanstalk
environment by adding a policy to the instance profile (p. 21).
The default instance profile is named aws-elasticbeanstalk-ec2-role. If you're not sure what your
instance profile is named, you can find it on the Configuration page in the environment management
console (p. 497).
933
AWS Elastic Beanstalk Developer Guide
Connection string in Amazon S3
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "database",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::DOC-EXAMPLE-BUCKET-123456789012/beanstalk-database.json"
]
}
]
}
Replace the bucket and object names with the names of your bucket and object.
Next, add a configuration file (p. 683) to your source code that directs Elastic Beanstalk to download the
file from Amazon S3 during deployment.
~/my-app/.ebextensions/database.config
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["DOC-EXAMPLE-BUCKET-123456789012"]
roleName: "aws-elasticbeanstalk-ec2-role"
files:
"/tmp/beanstalk-database.json" :
mode: "000644"
owner: root
group: root
authentication: "S3Auth"
source: https://s3-us-west-2.amazonaws.com/DOC-EXAMPLE-BUCKET-123456789012/beanstalk-
database.json
This configuration file does two things. The Resources key adds an authentication method to the Auto
Scaling group metadata for the environment. Elastic Beanstalk can use this authentication method to
access Amazon S3. The files key allows Elastic Beanstalk to download the file from Amazon S3 and
store it locally in /tmp/ during deployment.
Deploy your application with the configuration file in .ebextensions folder at the root of your
source code. If you configured permissions correctly, the deployment will succeed and the file will be
downloaded to all of the instances in your environment. If not successful, the deployment will fail.
934
AWS Elastic Beanstalk Developer Guide
Cleaning up an external Amazon RDS instance
Finally, add code to your application to read the JSON file and use the connection string to connect to
the database.
Elastic Beanstalk doesn't turn on default encryption for the Amazon S3 bucket that it creates. This means
that by default, objects are stored unencrypted in the bucket (and are accessible only by authorized
users). Some applications require all objects to be encrypted when they are stored—on a hard drive, in
a database, etc. (also known as encryption at rest). If you have this requirement, you can configure your
account's buckets for default encryption. For more details, see Amazon S3 Default Encryption for S3
Buckets in the Amazon Simple Storage Service User Guide.
Source When you upload a new application version Manually. When you delete an
bundles (p. 380)using the Elastic Beanstalk console or the EB application version, you can choose
CLI, Elastic Beanstalk stores a copy of it in Delete versions from Amazon S3 to
Amazon S3, and sets it as your environment's also delete the related source bundle.
source bundle. For details, see Managing application
versions (p. 380).
Custom When you create a custom platform, Elastic Upon successful completion of the
platforms (p. 1066)
Beanstalk temporarily stores related data in custom platform's creation.
Amazon S3.
Log You can request Elastic Beanstalk to retrieve Tail and bundle logs: 15 minutes after
files (p. 820) instance log files (tail or bundle logs) and they are created.
store them in Amazon S3. You can also enable
935
AWS Elastic Beanstalk Developer Guide
Deleting objects in the Elastic Beanstalk Amazon S3 bucket
• Delete application versions that you don't expect to use in your application anymore. When you
delete an application version, you can select Delete versions from Amazon S3 to also delete the
related source bundle—a copy of your application's source code and configurations files, which Elastic
Beanstalk uploaded to Amazon S3 when you deployed an application or uploaded an application
version. To learn how to delete an application version, see Managing application versions (p. 380).
• Delete rotated logs that you don't need. Alternatively, download them or move them to Amazon S3
Glacier for further analysis.
• Delete saved configurations that you aren't going to use in any environment anymore.
• When an environment scales out, Elastic Beanstalk should be able to find the environment's
application version in the Amazon S3 bucket and use it to start new Amazon EC2 instances.
• When you create a custom platform, Elastic Beanstalk uses temporary Amazon S3 storage
during the creation process.
We recommend that you delete specific unnecessary objects from your Elastic Beanstalk
Amazon S3 bucket, instead of deleting the entire bucket.
936
AWS Elastic Beanstalk Developer Guide
Deleting the Elastic Beanstalk Amazon S3 bucket
6. Go back to the Amazon S3 console's main page, and then select the Elastic Beanstalk storage bucket
by clicking its line anywhere outside of the bucket name.
937
AWS Elastic Beanstalk Developer Guide
Amazon VPC
VPC requirements
• Internet Access – Instances can have access to the internet through one of the following methods:
• Public Subnet – Instances have a public IP address and use an internet gateway to access the
internet.
• Private Subnet – Instances use a NAT device to access the internet.
Note
If you configure VPC endpoints (p. 951) in your VPC to connect to both the
elasticbeanstalk and elasticbeanstalk-health services, internet access is optional,
and is only required if your application specifically needs it. Without VPC endpoints, your VPC
must have access to the internet.
The default VPC that Elastic Beanstalk sets up for you provides internet access.
Elastic Beanstalk doesn't support proxy settings like HTTPS_PROXY for configuring a web proxy.
• NTP – Instances in your Elastic Beanstalk environment use Network Time Protocol (NTP) to synchronize
the system clock. If instances are unable to communicate on UDP port 123, the clock may go out of
sync, causing issues with Elastic Beanstalk health reporting. Ensure that your VPC security groups and
network ACLs allow inbound and outbound UDP traffic on port 123 to avoid these issues.
The elastic-beanstalk-samples repository provides AWS CloudFormation templates that you can use to
create a VPC for use with your Elastic Beanstalk environments.
1. Clone the samples repository or download a template using the links in the README.
2. Open the AWS CloudFormation console.
938
AWS Elastic Beanstalk Developer Guide
Public VPC
When stack creation completes, check the Outputs tab to find the VPC ID and subnet IDs. Use these to
configure the VPC in the new environment wizard network configuration category (p. 424).
Topics
• Public VPC (p. 939)
• Public/private VPC (p. 940)
• Private VPC (p. 940)
• Example: Launching an Elastic Beanstalk application in a VPC with bastion hosts (p. 941)
• Example: Launching an Elastic Beanstalk in a VPC with Amazon RDS (p. 946)
• Using Elastic Beanstalk with VPC endpoints (p. 951)
Public VPC
AWS CloudFormation template – vpc-public.yaml
A basic public-only VPC layout includes one or more public subnets, an internet gateway, and a default
security group that allows traffic between resources in the VPC. When you create an environment in the
VPC, Elastic Beanstalk creates additional resources that vary depending on the environment type.
VPC resources
• Single instance – Elastic Beanstalk creates a security group for the application instance that allows
traffic on port 80 from the internet, and assigns the instance an Elastic IP to give it a public IP address.
The environment's domain name resolves to the instance's public IP address.
• Load balanced – Elastic Beanstalk creates a security group for the load balancer that allows traffic on
port 80 from the internet, and a security group for the application instances that allows traffic from
the load balancer's security group. The environment's domain name resolves to the load balancer's
public domain name.
This is similar to the way that Elastic Beanstalk manages networking when you use the default VPC.
Security in a public subnet depends on the load balancer and instance security groups created by Elastic
Beanstalk. It is the least expensive configuration as it does not require a NAT Gateway.
939
AWS Elastic Beanstalk Developer Guide
Public/private VPC
Public/private VPC
AWS CloudFormation template – vpc-privatepublic.yaml
For additional security, add private subnets to your VPC to create a public-private layout. This layout
requires a load balancer and NAT gateway in the public subnets, and lets you run your application
instances, database, and any other resources in private subnets. Instances in private subnets can only
communicate with the internet through the load balancer and NAT gateway.
Private VPC
AWS CloudFormation template – vpc-private.yaml
For internal applications that shouldn't have access from the internet, you can run everything in private
subnets and configure the load balancer to be internally facing (change Load balancer visibility to
Internal). This template creates a VPC with no public subnets and no internet gateway. Use this layout
for applications that should only be accessible from the same VPC or an attached VPN.
• Configure VPC endpoints for Elastic Beanstalk – Elastic Beanstalk and its enhanced health service
support VPC endpoints, which ensure that traffic to these services stays inside the Amazon
network and doesn't require internet access. For more information, see the section called “VPC
endpoints” (p. 951).
• Configure VPC endpoints for additional services – Elastic Beanstalk instances send traffic to several
other AWS services on your behalf: Amazon Simple Storage Service (Amazon S3), Amazon Simple
940
AWS Elastic Beanstalk Developer Guide
Bastion hosts
Queue Service (Amazon SQS), AWS CloudFormation, and Amazon CloudWatch Logs. You must
configure VPC endpoints for these services too. For detailed information about VPC endpoints,
including per-service links, see VPC Endpoints in the Amazon VPC User Guide.
Note
Some AWS services, including Elastic Beanstalk, support VPC endpoints in a limited number
of AWS Regions. When you design your private VPC solution, verify that Elastic Beanstalk and
the other dependent services mentioned here support VPC endpoints in the AWS Region that
you choose.
• Provide a private Docker image – In a Docker (p. 48) environment, code on the environment's instances
might try to pull your configured Docker image from the internet during environment creation and
fail. To avoid this failure, build a custom Docker image (p. 61) on your environment, or use a Docker
image stored in Amazon Elastic Container Registry (Amazon ECR) and configure a VPC endpoint for the
Amazon ECR service.
• Enable DNS names – Elastic Beanstalk code on environment instances sends traffic to all AWS services
using their public endpoints. To ensure that this traffic goes through, choose the Enable DNS name
option when you configure all interface VPC endpoints. This adds a DNS entry in your VPC that maps
the public service endpoint to the interface VPC endpoint.
Important
If your VPC isn't private and has public internet access, and if Enable DNS name is disabled
for any VPC endpoint, traffic to the respective service travels through the public internet. This
is probably not what you intend. It's easy to detect this issue with a private VPC, because it
prevents this traffic from going through and you receive errors. However, with a public facing
VPC, you get no indication.
• Include application dependencies – If your application has dependencies such as language runtime
packages, it might try to download and install them from the internet during environment creation
and fail. To avoid this failure, include all dependency packages in your application's source bundle.
• Use a current platform version – Be sure that your environment uses a platform version that was
released on February 24, 2020 or later. Specifically, use a platform version that was released in or after
one of these two updates: Linux Update 2020-02-28, Windows Update 2020-02-24.
Note
The reason for needing an updated platform version is that older versions had an issue that
would prevent DNS entries created by the Enable DNS name option from working properly
for Amazon SQS.
941
AWS Elastic Beanstalk Developer Guide
Bastion hosts
To deploy an Elastic Beanstalk application inside a VPC using a bastion host, complete the steps
described in the following subsections.
Steps
• Create a VPC with a public and private subnet (p. 943)
• Create and configure the bastion host security group (p. 943)
• Update the instance security group (p. 945)
• Create a bastion host (p. 945)
942
AWS Elastic Beanstalk Developer Guide
Bastion hosts
The security group is created and appears on the Security Groups page. Notice that it has an ID (e.g.,
sg-xxxxxxxx). You might have to turn on the Group ID column by clicking Show/Hide in the top
right corner of the page.
1. In the list of security groups, select the check box for the security group you just created for your
bastion host.
2. On the Inbound Rules tab, choose Edit.
3. If needed, choose Add another rule.
4. If your bastion host is a Linux instance, under Type, select SSH.
943
AWS Elastic Beanstalk Developer Guide
Bastion hosts
To find it:
944
AWS Elastic Beanstalk Developer Guide
Bastion hosts
1. In the list of security groups, select the check box for the instance security group.
2. On the Inbound tab, choose Edit.
3. If needed, choose Add another rule.
4. Enter the following values, and choose Save.
Type
RDP
Protocol
TCP
Port Range
3389
Source
Enter the ID of the bastion host security group (e.g., sg-8a6f71e8) and choose Save.
For more information about setting up a bastion host for Windows instances in the private subnet, see
Controlling Network Access to EC2 Instances Using a Bastion Server .
For more information about setting up a bastion host for Linux instances in the private subnet, see
Securely Connect to Linux Instances Running in a Private Amazon VPC .
945
AWS Elastic Beanstalk Developer Guide
Amazon RDS
Note
If you haven't used a DB instance with your application before, try adding one to a test
environment (p. 577), and connecting to an external DB instance (p. 923) before adding a VPC
configuration to the mix.
946
AWS Elastic Beanstalk Developer Guide
Amazon RDS
To create a VPC
4. Your Elastic Load Balancing load balancer and your Amazon EC2 instances must be in the same
Availability Zone so they can communicate with each other. Choose the same Availability Zone from
each Availability Zone list.
The wizard begins to create your VPC, subnets, and internet gateway. It also updates the main route
table and creates a custom route table. Finally, the wizard creates a NAT gateway in the public
subnet.
Note
You can choose to launch a NAT instance in the public subnet instead of a NAT gateway. For
more information, see Scenario 2: VPC with Public and Private Subnets (NAT) in the Amazon
VPC User Guide.
7. After the VPC is successfully created, you get a VPC ID. You need this value for the next step. To view
your VPC ID, choose Your VPCs in the left pane of the Amazon VPC console.
947
AWS Elastic Beanstalk Developer Guide
Amazon RDS
Your new DB subnet group appears in the Subnet groups list of the Amazon RDS console. You can
choose it to see details, such as all of the subnets associated with this group, in the details pane at
the bottom of the page.
948
AWS Elastic Beanstalk Developer Guide
Amazon RDS
VPC
Select External if your load balancer should be publicly available, or select Internal if the load
balancer should be available only within your VPC.
Select the subnets for your load balancer and EC2 instances. Be sure you select the public subnet for the
load balancer, and the private subnet for your Amazon EC2 instances. By default, the VPC creation wizard
creates the public subnet in 10.0.0.0/24 and the private subnet in 10.0.1.0/24.
You can view your subnet IDs by choosing Subnets in the Amazon VPC console.
949
AWS Elastic Beanstalk Developer Guide
Amazon RDS
When you update the option settings, you need to specify at least the following:
• ELBScheme – Specify internal to create an internal load balancer inside your VPC so that your
Elastic Beanstalk application can't be accessed from outside your VPC.
The following is an example of the option settings you could use when deploying your Elastic Beanstalk
application inside a VPC. For more information about VPC option settings (including examples for how
to specify them, default values, and valid values), see the aws:ec2:vpc namespace table in Configuration
options (p. 613).
option_settings:
- namespace: aws:autoscaling:launchconfiguration
option_name: EC2KeyName
value: ec2keypair
- namespace: aws:ec2:vpc
option_name: VPCId
value: vpc-170647c
- namespace: aws:ec2:vpc
option_name: Subnets
value: subnet-4f195024
- namespace: aws:ec2:vpc
option_name: ELBSubnets
value: subnet-fe064f95
- namespace: aws:ec2:vpc
option_name: DBSubnets
value: subnet-fg148g78
- namespace: aws:autoscaling:launchconfiguration
option_name: InstanceType
value: m1.small
- namespace: aws:autoscaling:launchconfiguration
option_name: SecurityGroups
value: sg-7f1ef110
Note
When using DB subnets, be sure you have subnets in your VPC to cover all the Availability Zones
in the AWS Region.
950
AWS Elastic Beanstalk Developer Guide
VPC endpoints
Instances in your VPC don't require public IP addresses to communicate with resources in the service.
Traffic between your VPC and the other service doesn't leave the Amazon network. For complete
information about VPC endpoints, see VPC Endpoints in the Amazon VPC User Guide.
AWS Elastic Beanstalk supports AWS PrivateLink, which provides private connectivity to the Elastic
Beanstalk service and eliminates exposure of traffic to the public internet. To enable your application to
send requests to Elastic Beanstalk using AWS PrivateLink, you configure a type of VPC endpoint known
as an interface VPC endpoint (interface endpoint). For more information, see Interface VPC Endpoints
(AWS PrivateLink) in the Amazon VPC User Guide.
Note
Elastic Beanstalk supports AWS PrivateLink and interface VPC endpoints in a limited number of
AWS Regions. We're working to extend support to more AWS Regions in the near future.
If your VPC is configured with public internet access, your application can still access Elastic Beanstalk
over the internet using the elasticbeanstalk.region.amazonaws.com public endpoint. You can
prevent this by ensuring that Enable DNS name is enabled during endpoint creation (true by default).
This adds a DNS entry in your VPC that maps the public service endpoint to the interface VPC endpoint.
951
AWS Elastic Beanstalk Developer Guide
VPC endpoints
An endpoint policy is an AWS Identity and Access Management (IAM) resource policy that controls access
from the endpoint to the specified service. The endpoint policy is specific to the endpoint. It's separate
from any user or instance IAM policies that your environment might have and doesn't override or replace
them. For details about authoring and using VPC endpoint policies, see Controlling Access to Services
with VPC Endpoints in the Amazon VPC User Guide.
The following example denies all users the permission to terminate an environment through the VPC
endpoint, and allows full access to all other actions.
{
"Statement": [
{
"Action": "*",
"Effect": "Allow",
"Resource": "*",
"Principal": "*"
},
{
"Action": "elasticbeanstalk:TerminateEnvironment",
"Effect": "Deny",
"Resource": "*",
"Principal": "*"
}
]
}
Note
At this time, only the main Elastic Beanstalk service supports attaching an endpoint policy to its
VPC endpoint. The enhanced health service doesn't support endpoint policies.
952
AWS Elastic Beanstalk Developer Guide
Creating a project folder
Topics
• Creating a project folder (p. 953)
• Setting up source control (p. 953)
• Configuring a remote repository (p. 954)
• Installing the EB CLI (p. 954)
• Installing the AWS CLI (p. 954)
workspace/
|-- my-first-app
`-- my-second-app
The contents of your project folder will vary depending on the web container or framework that your
application uses.
Note
Avoid folders and paths with single-quote (') or double-quote (") characters in the folder name
or any path element. Some Elastic Beanstalk commands fail when run within a folder with either
character in the name.
If you don't have a source control system, consider Git, a free and easy-to-use option, and it integrates
well with the Elastic Beanstalk Command Line Interface (CLI). Visit the Git homepage to install Git.
Follow the instructions on the Git website to install and configure Git, and then run git init in your
project folder to set up a local repository:
953
AWS Elastic Beanstalk Developer Guide
Configuring a remote repository
As you add content to your project folder and update content, commit the changes to your Git
repository:
Every time you commit, you create a snapshot of your project that you can restore later if anything goes
wrong. For much more information on Git commands and workflows, see the Git documentation.
AWS CodeCommit lets you create a private repository in the AWS cloud. CodeCommit is free in the AWS
free tier for up to five AWS Identity and Access Management (IAM) users in your account. For pricing
details, see AWS CodeCommit Pricing.
Visit the AWS CodeCommit User Guide for instructions on getting set up.
GitHub is another popular option for storing your project code online. It lets you create a public online
repository for free and also supports private repositories for a monthly charge. Sign up for GitHub at
github.com.
After you've created a remote repository for your project, attach it to your local repository with git
remote add:
By default, the EB CLI packages everything in your project folder and uploads it to Elastic Beanstalk as
a source bundle. When you use Git and the EB CLI together, you can prevent built class files from being
committed to source with .gitignore and prevent source files from being deployed with .ebignore.
You can also configure the EB CLI to deploy a build artifact (p. 967) (a WAR or ZIP file) instead of the
contents of your project folder.
954
AWS Elastic Beanstalk Developer Guide
Installing the AWS CLI
account without setting up a repository on your local machine. Use the AWS CLI to create scripts that
simplify or automate operational tasks.
For more information about supported services and to download the AWS Command Line Interface, see
AWS Command Line Interface.
955
AWS Elastic Beanstalk Developer Guide
After you install the EB CLI (p. 957) and configure a project directory, you can create environments with
a single command:
The source code for the EB CLI is an open-source project. It resides in the aws/aws-elastic-
beanstalk-cli GitHub repository. You can participate by reporting issues, making suggestions, and
submitting pull requests. We value your contributions! For an environment where you only intend to use
the EB CLI as is, we recommend that you install it using one of the EB CLI setup scripts, as detailed in the
section called “Install the EB CLI using setup scripts” (p. 957).
Previously, Elastic Beanstalk supported a separate CLI that provided direct access to API operations called
the Elastic Beanstalk API CLI (p. 1047). This has been replaced with the AWS CLI (p. 954), which provides
the same functionality but for all AWS services' APIs.
With the AWS CLI you have direct access to the Elastic Beanstalk API. The AWS CLI is great for scripting,
but is not as easy to use from the command line because of the number of commands that you need to
run and the number of parameters on each command. For example, creating an environment requires a
series of commands:
For information about installing the EB CLI, configuring a repository, and working with environments, see
the following topics.
Topics
• Install the EB CLI (p. 957)
• Configure the EB CLI (p. 964)
• Managing Elastic Beanstalk environments with the EB CLI (p. 968)
• Using the EB CLI with AWS CodeBuild (p. 972)
956
AWS Elastic Beanstalk Developer Guide
Install the EB CLI
Topics
• Install the EB CLI using setup scripts (p. 957)
• Manually install the EB CLI (p. 957)
The primary distribution method for the EB CLI on Linux, macOS, and Windows is pip. This is a package
manager for Python that provides an easy way to install, upgrade, and remove Python packages and
their dependencies. For macOS, you can also get the latest version of the EB CLI with Homebrew.
Compatibility notes
The EB CLI is developed in Python and requires Python version 2.7, 3.4, or later.
Note
Amazon Linux, starting with version 2015.03, comes with Python 2.7 and pip.
We recommend using the EB CLI setup scripts to install the EB CLI and its dependencies. If you manually
install the EB CLI, it can be difficult to manage dependency conflicts in your development environment.
The EB CLI and the AWS Command Line Interface (AWS CLI) share a dependency on the botocore Python
package. Due to a breaking change in botocore, different versions of these two CLI tools depend on
different versions of botocore.
957
AWS Elastic Beanstalk Developer Guide
Manual installation
The latest versions of the two CLIs are compatible. If you need to use an earlier version, see the following
table for a compatible version to use.
If you don't have Python and pip, use the procedure for the operating system you're using.
The --upgrade option tells pip to upgrade any requirements that are already installed. The --
user option tells pip to install the program to a subdirectory of your user directory to avoid
modifying libraries that your operating system uses.
Note
If you encounter issues when you try to install the EB CLI with pip, you can install the EB
CLI in a virtual environment (p. 964) to isolate the tool and its dependencies, or use a
different version of Python than you normally do.
2. Add the path to the executable file to your PATH variable:
• On Linux and macOS:
Linux – ~/.local/bin
macOS – ~/Library/Python/3.7/bin
a. Find your shell's profile script in your user folder. If you are not sure which shell you have,
run echo $SHELL.
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
958
AWS Elastic Beanstalk Developer Guide
Manual installation
export PATH=LOCAL_PATH:$PATH
c. Load the profile script described in the first step into your current session. The following
example loads the profile script represented by PROFILE_SCRIPT.
$ source ~/PROFILE_SCRIPT
• On Windows:
$ eb --version
EB CLI 3.14.8 (Python 3.7)
The EB CLI is updated regularly to add functionality that supports the latest Elastic Beanstalk features.
To update to the latest version of the EB CLI, run the installation command again.
$ python --version
Note
If your Linux distribution came with Python, you might need to install the Python developer
package to get the headers and libraries required to compile extensions and install the EB
CLI. Use your package manager to install the developer package (typically named python-
dev or python-devel).
959
AWS Elastic Beanstalk Developer Guide
Manual installation
2. If Python 2.7 or later isn't installed, install Python 3.7 using your distribution's package manager.
The command and package name vary:
3. To verify that Python installed correctly, open a terminal or shell and run the following command.
$ python3 --version
Python 3.7.3
Install pip by using the script provided by the Python Packaging Authority, and then install the EB CLI.
$ curl -O https://bootstrap.pypa.io/get-pip.py
The script downloads and installs the latest version of pip and another required package named
setuptools.
2. Run the script with Python.
Invoking Python version 3 directly by using the python3 command instead of python ensures that
pip is installed in the proper location, even if an earlier version of Python is present on your system.
3. Add the executable path, ~/.local/bin, to your PATH variable.
a. Find your shell's profile script in your user folder. If you are not sure which shell you have, run
echo $SHELL.
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
960
AWS Elastic Beanstalk Developer Guide
Manual installation
• Zsh – .zshrc
• Tcsh – .tcshrc, .cshrc or .login.
b. Add an export command to your profile script. The following example adds the path
represented by LOCAL_PATH to the current PATH variable.
export PATH=LOCAL_PATH:$PATH
c. Load the profile script described in the first step into your current session. The following
example loads the profile script represented by PROFILE_SCRIPT.
$ source ~/PROFILE_SCRIPT
$ pip --version
pip 8.1.2 from ~/.local/lib/python3.7/site-packages (python 3.7)
$ eb --version
EB CLI 3.14.8 (Python 3.7)
$ brew update
$ eb --version
961
AWS Elastic Beanstalk Developer Guide
Manual installation
1. Download and install Python from the downloads page of Python.org. We use version 3.7 to
demonstrate.
Note
The EB CLI requires Python 2 version 2.7, or Python 3 version in the range of 3.4 to 3.7.
2. Install pip with the script that the Python Packaging Authority provides.
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ python3 get-pip.py --user
a. Find your shell's profile script in your user folder. If you are not sure which shell you have, run
echo $SHELL.
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
export PATH=LOCAL_PATH:$PATH
c. Load the profile script described in the first step into your current session. The following
example loads the profile script represented by PROFILE_SCRIPT.
$ source ~/PROFILE_SCRIPT
$ eb --version
EB CLI 3.14.8 (Python 3.7)
962
AWS Elastic Beanstalk Developer Guide
Manual installation
1. Download the Python 3.7 Windows x86-64 executable installer from the downloads page of
Python.org.
2. Run the installer.
3. Choose Add Python 3.7 to PATH.
4. Choose Install Now.
The installer installs Python in your user folder and adds its executable directories to your user path.
C:\Windows\System32> eb --version
EB CLI 3.14.8 (Python 3.7)
963
AWS Elastic Beanstalk Developer Guide
Configure the EB CLI
$ virtualenv ~/eb-ve
To use a Python executable other than the default, use the -p option.
$ source ~/eb-ve/bin/activate
Windows
$ %USERPROFILE%\eb-ve\Scripts\activate
$ eb --version
EB CLI 3.14.8 (Python 3.7)
You can use the deactivate command to exit the virtual environment. Whenever you start a new
session, run the activation command again.
The following example shows the configuration steps when running eb init for the first time in a project
folder named eb.
964
AWS Elastic Beanstalk Developer Guide
Configure the EB CLI
1. First, the EB CLI prompts you to select a region. Type the number that corresponds to the region that
you want to use, and then press Enter.
~/eb $ eb init
Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : Europe (Ireland)
5) eu-central-1 : Europe (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
...
(default is 3): 3
2. Next, provide your access key and secret key so that the EB CLI can manage resources for you. Access
keys are created in the AWS Identity and Access Management console. If you don't have keys, see
How Do I Get Security Credentials? in the Amazon Web Services General Reference.
You have not yet set up your credentials or your credentials are incorrect.
You must provide your credentials.
(aws-access-id): AKIAJOUAASEXAMPLE
(aws-secret-key): 5ZRIrtTM4ciIAvd4EXAMPLEDtm+PiPSzpoK
3. An application in Elastic Beanstalk is a resource that contains a set of application versions (source),
environments, and saved configurations that are associated with a single web application. Each
time you deploy your source code to Elastic Beanstalk using the EB CLI, a new application version is
created and added to the list.
4. The default application name is the name of the folder in which you run eb init. Enter any name that
describes your project.
5. Select a platform that matches the language or framework that your web application is developed
in. If you haven't started developing an application yet, choose a platform that you're interested
in. You will see how to launch a sample application shortly, and you can always change this setting
later.
Select a platform.
1) Node.js
2) PHP
3) Python
4) Ruby
5) Tomcat
6) IIS
7) Docker
8) Multi-container Docker
9) GlassFish
10) Go
11) Java
(default is 1): 1
965
AWS Elastic Beanstalk Developer Guide
Ignoring files using .ebignore
6. Choose yes to assign an SSH key pair to the instances in your Elastic Beanstalk environment. This
allows you to connect directly to them for troubleshooting.
7. Choose an existing key pair or create a new one. To use eb init to create a new key pair, you must
have ssh-keygen installed on your local machine and available from the command line. The EB CLI
registers the new key pair with Amazon EC2 for you and stores the private key locally in a folder
named .ssh in your user directory.
Select a keypair.
1) [ Create new KeyPair ]
(default is 1): 1
Your EB CLI installation is now configured and ready to use. See Managing Elastic Beanstalk
environments with the EB CLI (p. 968) for instructions on creating and working with an Elastic
Beanstalk environment.
Advanced Configuration
• Ignoring files using .ebignore (p. 966)
• Using named profiles (p. 966)
• Deploying an artifact instead of the project folder (p. 967)
• Configuration settings and precedence (p. 967)
• Instance metadata (p. 968)
If .ebignore isn't present, but .gitignore is, the EB CLI ignores files specified in .gitignore. If
.ebignore is present, the EB CLI doesn't read .gitignore.
When .ebignore is present, the EB CLI doesn't use git commands to create your source bundle. This
means that EB CLI ignores files specified in .ebignore, and includes all other files. In particular, it
includes uncommitted source files.
Note
In Windows, adding .ebignore causes the EB CLI to follow symbolic links and include the
linked file when creating a source bundle. This is a known issue and will be fixed in a future
update.
966
AWS Elastic Beanstalk Developer Guide
Deploying an artifact instead of the project folder
You can also change the default profile by setting the AWS_EB_PROFILE environment variable. When
this variable is set, the EB CLI reads credentials from the specified profile instead of default or eb-cli.
$ export AWS_EB_PROFILE=user2
Windows
deploy:
artifact: path/to/buildartifact.zip
If you configure the EB CLI in your Git repository (p. 974), and you don't commit the artifact to source,
use the --staged option to deploy the latest build.
The EB CLI looks for credentials and configuration settings in the following order:
1. Command line options – Specify a named profile by using --profile to override default settings.
2. Environment variables – AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
3. The AWS credentials file – Located at ~/.aws/credentials on Linux and OS X systems, or at C:
\Users\USERNAME\.aws\credentials on Windows systems. This file can contain multiple named
profiles in addition to a default profile.
4. The AWS CLI configuration file – Located at ~/.aws/config on Linux and OS X systems or C:
\Users\USERNAME\.aws\config on Windows systems. This file can contain a default profile,
named profiles, and AWS CLI–specific configuration parameters for each.
5. Legacy EB CLI configuration file – Located at ~/.elasticbeanstalk/config on Linux and OS X
systems or C:\Users\USERNAME\.elasticbeanstalk\config on Windows systems.
6. Instance profile credentials – These credentials can be used on Amazon EC2 instances with an
assigned instance role, and are delivered through the Amazon EC2 metadata service. The instance
profile (p. 21) must have permission to use Elastic Beanstalk.
If the credentials file contains a named profile with the name "eb-cli", the EB CLI will prefer that profile
over the default profile. If no profiles are found, or a profile is found but does not have permission to use
Elastic Beanstalk, the EB CLI prompts you to enter keys.
967
AWS Elastic Beanstalk Developer Guide
Instance metadata
Instance metadata
To use the EB CLI from an Amazon EC2 instance, create a role that has access to the resources needed
and assign that role to the instance when it is launched. Launch the instance and install the EB CLI by
using pip.
The EB CLI reads credentials from the instance metadata. For more information, see Granting
Applications that Run on Amazon EC2 Instances Access to AWS Resources in IAM User Guide.
The EB CLI returns a zero (0) exit code for all successful commands, and a non-zero exit code when it
encounters any error.
The following examples use an empty project folder named eb that was initialized with the EB CLI for
use with a sample Docker application.
Basic Commands
• Eb create (p. 968)
• Eb status (p. 969)
• Eb health (p. 969)
• Eb events (p. 970)
• Eb logs (p. 970)
• Eb open (p. 970)
• Eb deploy (p. 971)
• Eb config (p. 971)
• Eb terminate (p. 972)
Eb create
To create your first environment, run eb create (p. 1003) and follow the prompts. If your project
directory has source code in it, the EB CLI will bundle it up and deploy it to your environment. Otherwise,
a sample application will be used.
~/eb$ eb create
Enter Environment Name
(default is eb-dev): eb-dev
Enter DNS CNAME prefix
968
AWS Elastic Beanstalk Developer Guide
Eb status
Your environment can take several minutes to become ready. Press Ctrl+C to return to the command line
while the environment is created.
Eb status
Run eb status to see the current status of your environment. When the status is ready, the sample
application is available at elasticbeanstalk.com and the environment is ready to be updated.
~/eb$ eb status
Environment details for: elasticBeanstalkExa-env
Application name: elastic-beanstalk-example
Region: us-west-2
Deployed Version: Sample Application
Environment ID: e-gbzqc3jcra
Platform: 64bit Amazon Linux 2015.03 v1.4.3 running Docker 1.6.2
Tier: WebServer-Standard
CNAME: elasticbeanstalkexa-env.elasticbeanstalk.com
Updated: 2015-06-30 01:47:45.589000+00:00
Status: Ready
Health: Green
Eb health
Use the eb health command to view health information (p. 776) about the instances in your environment
and the state of your environment overall. Use the --refresh option to view health in an interactive
view that updates every 10 seconds.
~/eb$ eb health
api Ok 2016-09-15 18:39:04
WebServer Java 8
total ok warning degraded severe info pending unknown
3 3 0 0 0 0 0 0
969
AWS Elastic Beanstalk Developer Guide
Eb events
Eb events
Use eb events to see a list of events output by Elastic Beanstalk.
~/eb$ eb events
2015-06-29 23:21:09 INFO createEnvironment is starting.
2015-06-29 23:21:10 INFO Using elasticbeanstalk-us-east-2-EXAMPLE as Amazon S3
storage bucket for environment data.
2015-06-29 23:21:23 INFO Created load balancer named: awseb-e-g-AWSEBLoa-EXAMPLE
2015-06-29 23:21:42 INFO Created security group named: awseb-e-gbzqc3jcra-stack-
AWSEBSecurityGroup-EXAMPLE
...
Eb logs
Use eb logs to pull logs from an instance in your environment. By default, eb logs pull logs from the
first instance launched and displays them in standard output. You can specify an instance ID with the --
instance option to get logs from a specific instance.
The --all option pulls logs from all instances and saves them to subdirectories under
.elasticbeanstalk/logs.
Eb open
To open your environment's website in a browser, use eb open:
~/eb$ eb open
In a windowed environment, your default browser will open in a new window. In a terminal environment,
a command line browser (e.g. w3m) will be used if available.
970
AWS Elastic Beanstalk Developer Guide
Eb deploy
Eb deploy
Once the environment is up and ready, you can update it using eb deploy.
This command works better with some source code to bundle up and deploy, so for this example we've
created a Dockerfile in the project directory with the following content:
~/eb/Dockerfile
FROM ubuntu:12.04
EXPOSE 80
This Dockerfile deploys an image of Ubuntu 12.04 and installs the game 2048. Run eb deploy to
upload the application to your environment:
~/eb$ eb deploy
Creating application version archive "app-150630_014338".
Uploading elastic-beanstalk-example/app-150630_014338.zip to S3. This may take a while.
Upload Complete.
INFO: Environment update is starting.
-- Events -- (safe to Ctrl+C) Use "eb abort" to cancel the command.
When you run eb deploy, the EB CLI bundles up the contents of your project directory and deploys it to
your environment.
Note
If you have initialized a git repository in your project folder, the EB CLI will always deploy the
latest commit, even if you have pending changes. Commit your changes prior to running eb
deploy to deploy them to your environment.
Eb config
Take a look at the configuration options available for your running environment with the eb config
command:
~/eb$ eb config
ApplicationName: elastic-beanstalk-example
DateUpdated: 2015-06-30 02:12:03+00:00
EnvironmentName: elasticBeanstalkExa-env
SolutionStackName: 64bit Amazon Linux 2015.03 v1.4.3 running Docker 1.6.2
settings:
AWSEBAutoScalingScaleDownPolicy.aws:autoscaling:trigger:
LowerBreachScaleIncrement: '-1'
AWSEBAutoScalingScaleUpPolicy.aws:autoscaling:trigger:
UpperBreachScaleIncrement: '1'
AWSEBCloudwatchAlarmHigh.aws:autoscaling:trigger:
UpperThreshold: '6000000'
...
971
AWS Elastic Beanstalk Developer Guide
Eb terminate
This command populates a list of available configuration options in a text editor. Many of the options
shown have a null value, these are not set by default but can be modified to update the resources in
your environment. See Configuration options (p. 613) for more information about these options.
Eb terminate
If you are done using the environment for now, use eb terminate to terminate it.
~/eb$ eb terminate
The environment "eb-dev" and all associated instances will be terminated.
To confirm, type the environment name: eb-dev
INFO: terminateEnvironment is starting.
INFO: Deleted CloudWatch alarm named: awseb-e-jc8t3pmscn-stack-
AWSEBCloudwatchAlarmHigh-1XLMU7DNCBV6Y
INFO: Deleted CloudWatch alarm named: awseb-e-jc8t3pmscn-stack-
AWSEBCloudwatchAlarmLow-8IVI04W2SCXS
INFO: Deleted Auto Scaling group policy named: arn:aws:autoscaling:us-
east-2:123456789012:scalingPolicy:1753d43e-ae87-4df6-
a405-11d31f4c8f97:autoScalingGroupName/awseb-e-jc8t3pmscn-stack-
AWSEBAutoScalingGroup-90TTS2ZL4MXV:policyName/awseb-e-jc8t3pmscn-stack-
AWSEBAutoScalingScaleUpPolicy-A070H1BMUQAJ
INFO: Deleted Auto Scaling group policy named: arn:aws:autoscaling:us-
east-2:123456789012:scalingPolicy:1fd24ea4-3d6f-4373-
affc-4912012092ba:autoScalingGroupName/awseb-e-jc8t3pmscn-stack-
AWSEBAutoScalingGroup-90TTS2ZL4MXV:policyName/awseb-e-jc8t3pmscn-stack-
AWSEBAutoScalingScaleDownPolicy-LSWFUMZ46H1V
INFO: Waiting for EC2 instances to terminate. This may take a few minutes.
-- Events -- (safe to Ctrl+C)
For a full list of available EB CLI commands, check out the EB CLI command reference (p. 989).
Creating an application
To create an Elastic Beanstalk application that uses CodeBuild
Elastic Beanstalk extends the CodeBuild build specification file format to include the following additional
settings:
eb_codebuild_settings:
CodeBuildServiceRole: role-name
972
AWS Elastic Beanstalk Developer Guide
Building and deploying your application code
ComputeType: size
Image: image
Timeout: minutes
CodeBuildServiceRole
The ARN or name of the AWS Identity and Access Management (IAM) service role that CodeBuild can
use to interact with dependent AWS services on your behalf. This value is required. If you omit it, any
subsequent eb create or eb deploy command fails.
To learn more about creating a service role for CodeBuild, see Create a CodeBuild Service Role in the
AWS CodeBuild User Guide.
Note
You also need permissions to perform actions in CodeBuild itself. The Elastic Beanstalk
AdministratorAccess-AWSElasticBeanstalk managed user policy includes all the required
CodeBuild action permissions. If you're not using the managed policy, be sure to allow the
following permissions in your user policy.
"codebuild:CreateProject",
"codebuild:DeleteProject",
"codebuild:BatchGetBuilds",
"codebuild:StartBuild"
For details, see Managing Elastic Beanstalk user policies (p. 879).
ComputeType
The amount of resources used by the Docker container in the CodeBuild build environment. Valid
values are BUILD_GENERAL1_SMALL, BUILD_GENERAL1_MEDIUM, and BUILD_GENERAL1_LARGE.
Image
The name of the Docker Hub or Amazon ECR image that CodeBuild uses for the build environment.
This Docker image should contain all the tools and runtime libraries required to build your code, and
should match your application's target platform. CodeBuild manages and maintains a set of images
specifically meant to be used with Elastic Beanstalk. It is recommended that you use one of them.
For details, see Docker Images Provided by CodeBuild in the AWS CodeBuild User Guide.
The Image value is optional. If you omit it, the eb init command attempts to choose an image that
best matches your target platform. In addition, if you run eb init in interactive mode and it fails to
choose an image for you, it prompts you to choose one. At the end of a successful initialization, eb
init writes the chosen image into the buildspec.yml file.
Timeout
The duration, in minutes, that the CodeBuild build runs before timing out. This value is optional. For
details about valid and default values, see Create a Build Project in CodeBuild.
Note
This timeout controls the maximum duration for a CodeBuild run, and the EB CLI also
respects it as part of its first step to create an application version. It's distinct from the
value you can specify with the --timeout option of the eb create (p. 1003) or eb
deploy (p. 1013) commands. The latter value controls the maximum duration that for EB
CLI to wait for environment creation or update.
973
AWS Elastic Beanstalk Developer Guide
Using the EB CLI with Git
Beanstalk environment for your application using the eb create (p. 1003) command, and each time you
later deploy code changes to the environment using the eb deploy (p. 1013) command.
EB CLI will now recognize that your application is set up with Git.
3. If you haven't already run eb init, do that now:
~/eb$ eb init
Deploying changes
By default, the EB CLI deploys the latest commit in the current branch, using the commit ID and message
as the application version label and description, respectively. If you want to deploy to your environment
without committing, you can use the --staged option to deploy changes that have been added to the
staging area.
974
AWS Elastic Beanstalk Developer Guide
Using Git submodules
If you have configured the EB CLI to deploy an artifact (p. 967), and you don't commit the artifact to
your git repository, use the --staged option to deploy the latest build.
You can control the inclusion of submodules by using the include_git_submodules option in the
global section of the EB CLI configuration file, .elasticbeanstalk/config.yml in your project
folder.
global:
include_git_submodules: true
When the include_git_submodules option is missing or set to false, EB CLI does not include
submodules in the uploaded zip file.
See Git Tools - Submodules for more details about Git submodules.
Default behavior
When you run eb init to configure your project, the EB CLI adds the
include_git_submodules option and sets it to true. This ensures that any submodules you
have in your project are included in your deployments.
The EB CLI did not always support including submodules. To avoid an accidental and undesirable
change to projects that had existed before we added submodule support, the EB CLI does not
include submodules when the include_git_submodules option is missing. If you have one
of these existing projects and you want to include submodules in your deployments, add the
option and set it to true as explained in this section.
CodeCommit behavior
Elastic Beanstalk's integration with CodeCommit (p. 975) doesn't support submodules at this
time. If you enabled your environment to integrate with CodeCommit, submodules are not
included in your deployments.
To deploy your changes, CodeCommit integration requires you to commit changes first. However, as you
develop or debug, you might not want to push changes that you haven't confirmed are working. You
can avoid committing your changes by staging them and using eb deploy --staged (which performs a
975
AWS Elastic Beanstalk Developer Guide
Prerequisites
standard deployment). Or commit your changes to a development or testing branch first, and merge to
your mainline branch only when your code is ready. With eb use, you can configure the EB CLI to deploy
to one environment from your development branch, and to a different environment from your mainline
branch.
Note
Some regions don't offer CodeCommit. The integration between Elastic Beanstalk and
CodeCommit doesn't work in these regions.
For information about the AWS services offered in each region, see Region Table.
Sections
• Prerequisites (p. 976)
• Creating a CodeCommit repository with the EB CLI (p. 976)
• Deploying from your CodeCommit repository (p. 977)
• Configuring additional branches and environments (p. 978)
• Using an existing CodeCommit repository (p. 979)
Prerequisites
To use CodeCommit with AWS Elastic Beanstalk, you need a local Git repository (either one you have
already or a new one you create) with at least one commit, permission to use CodeCommit, and an
Elastic Beanstalk environment in a region that CodeCommit supports. Your environment and repository
must be in the same region.
1. Run eb init in your project folder. During configuration, the EB CLI asks if you want to use
CodeCommit to store your code and speed up deployments. If you previously configured your
project with eb init, you can still run it again to configure CodeCommit. Type y at the prompt to set
up CodeCommit.
~/my-app$ eb init
Note: Elastic Beanstalk now supports AWS CodeCommit; a fully-managed source control
service. To learn more, see Docs: https://aws.amazon.com/codecommit/
976
AWS Elastic Beanstalk Developer Guide
Deploying from your CodeCommit repository
Select a repository
1) my-repo
2) [ Create new Repository ]
(default is 2): 2
4. Choose an existing branch for your commits, or use the EB CLI to create a new branch.
The EB CLI uses the latest commit in the tracked branch to create the application version that is
deployed to the environment.
2. When you have new local commits, use eb deploy to push the commits and deploy to your
environment.
~/my-app$ eb deploy
977
AWS Elastic Beanstalk Developer Guide
Configuring additional branches and environments
3. To test changes before you commit them, use the --staged option to deploy changes that you
added to the staging area with git add.
Deploying with the --staged option performs a standard deployment, bypassing CodeCommit.
1. To change the remote branch, use the eb use (p. 1045) command's --source option.
2. To create a new branch and environment, check out a new branch, push it to CodeCommit, create
the environment, and then use eb use to connect the local branch, remote branch, and environment.
Select a repository
1) my-repo
2) my-app
3) [ Create new Repository ]
(default is 2): 2
Select a branch
1) mainline
2) test
3) [ Create new Branch with local HEAD ]
(default is 1): 1
978
AWS Elastic Beanstalk Developer Guide
Using an existing CodeCommit repository
Branch: mainline
Default set to use local sources
2. Check out and push a branch to use for your Elastic Beanstalk environment.
3. Run eb init. Choose the same region, repository, and branch name that you are currently using.
~/my-app$ eb init
Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : Europe (Ireland)
5) eu-central-1 : Europe (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
...
(default is 3): 1
...
Note: Elastic Beanstalk now supports AWS CodeCommit; a fully-managed source control
service. To learn more, see Docs: https://aws.amazon.com/codecommit/
Do you wish to continue with CodeCommit? (y/n)(default is n): y
Select a repository
1) my-app
2) [ Create new Repository ]
(default is 1): 1
Select a branch
1) mainline
2) dev-env
3) [ Create new Branch with local HEAD ]
(default is 2): 2
For more information about using eb init, see Configure the EB CLI (p. 964).
979
AWS Elastic Beanstalk Developer Guide
Monitoring health
After installing (p. 957) and configuring (p. 964) the EB CLI, you can launch a new
environment (p. 968) and deploy your code to it with the eb create command. If you already have an
environment that you created in the Elastic Beanstalk console, you can attach the EB CLI to it by running
eb init in a project folder and following the prompts (the project folder can be empty).
Important
Ensure that you are using the latest version of the EB CLI by running pip install with the --
upgrade option:
For complete EB CLI installation instructions, see Install the EB CLI (p. 957).
To use the EB CLI to monitor your environment's health, you must first configure a local project folder by
running eb init and following the prompts. For complete instructions, see Configure the EB CLI (p. 964).
If you already have an environment running in Elastic Beanstalk and want to use the EB CLI to monitor its
health, follow these steps to attach it to the existing environment.
~/project$ eb init
Select an application to use
1) elastic-beanstalk-example
2) [ Create new Application ]
(default is 2): 1
Select the default environment.
You can change this later by typing "eb use [environment_name]".
1) elasticBeanstalkEx2-env
2) elasticBeanstalkExa-env
(default is 1): 1
~/project $ eb health
elasticBeanstalkExa-env Ok
2015-07-08 23:13:20
WebServer
Ruby 2.1 (Puma)
total ok warning degraded severe info pending unknown
5 5 0 0 0 0 0 0
980
AWS Elastic Beanstalk Developer Guide
Monitoring health
i-126e00c1 Ok
i-8b2cf575 Ok
instance-id r/sec %2xx %3xx %4xx %5xx p99 p90 p75 p50
p10 requests
Overall 671.8 100.0 0.0 0.0 0.0 0.003 0.002 0.001 0.001
0.000
i-d581497d 143.0 1430 0 0 0 0.003 0.002 0.001 0.001
0.000
i-d481497c 128.8 1288 0 0 0 0.003 0.002 0.001 0.001
0.000
i-136e00c0 125.4 1254 0 0 0 0.004 0.002 0.001 0.001
0.000
i-126e00c1 133.4 1334 0 0 0 0.003 0.002 0.001 0.001
0.000
i-8b2cf575 141.2 1412 0 0 0 0.003 0.002 0.001 0.001
0.000
~/project $ eb health
WindowsSampleApp-env Ok
2018-05-22 17:33:19
WebServer IIS 10.0 running on 64bit
Windows Server 2016/2.2.0
total ok warning degraded severe info pending unknown
1 1 0 0 0 0 0 0
981
AWS Elastic Beanstalk Developer Guide
Reading the output
elasticBeanstalkExa-env Ok
2015-07-08 23:13:20
The next three lines display the type of environment ("WebServer" in this case), the configuration (Ruby
2.1 with Puma), and a breakdown of how many instances are in each of the seven states.
WebServer Ruby
2.1 (Puma)
total ok warning degraded severe info pending unknown
5 5 0 0 0 0 0 0
The rest of the output is split into four sections. The first displays the status and the cause of the status
for the environment overall, and then for each instance. The following example shows two instances in
the environment with a status of Info and a cause indicating that a deployment has started.
For information about health statuses and colors, see Health colors and statuses (p. 792).
The requests section displays information from the web server logs on each instance. In this example,
each instance is taking requests normally and there are no errors.
instance-id r/sec %2xx %3xx %4xx %5xx p99 p90 p75 p50
p10 requests
Overall 13.7 100.0 0.0 0.0 0.0 1.403 0.970 0.710 0.413
0.079
i-d581497d 2.4 100.0 0.0 0.0 0.0 1.102* 0.865 0.601 0.413
0.091
i-d481497c 2.7 100.0 0.0 0.0 0.0 0.842* 0.788 0.480 0.305
0.062
i-136e00c0 4.1 100.0 0.0 0.0 0.0 1.520* 1.088 0.883 0.524
0.104
i-126e00c1 2.2 100.0 0.0 0.0 0.0 1.334* 0.791 0.760 0.344
0.197
i-8b2cf575 2.3 100.0 0.0 0.0 0.0 1.162* 0.867 0.698 0.477
0.076
The cpu section shows operating system metrics for each instance. The output differs by operating
system. Here is the output for Linux environments.
982
AWS Elastic Beanstalk Developer Guide
Interactive health view
For information about the server and operating system metrics shown, see Instance metrics (p. 794).
The final section, deployments, shows the deployment status of each instance. If a rolling deployment
fails, you can use the deployment ID, status, and version label shown to identify instances in your
environment that are running the wrong version.
$ eb health --refresh
elasticBeanstalkExa-env Ok
2015-07-09 22:10:04 (1 secs)
WebServer
Ruby 2.1 (Puma)
total ok warning degraded severe info pending unknown
5 5 0 0 0 0 0 0
983
AWS Elastic Beanstalk Developer Guide
Interactive health view options
instance-id r/sec %2xx %3xx %4xx %5xx p99 p90 p75 p50
p10 requests
Overall 671.8 100.0 0.0 0.0 0.0 0.003 0.002 0.001 0.001
0.000
i-bb65c145 143.0 1430 0 0 0 0.003 0.002 0.001 0.001
0.000
i-ba65c144 128.8 1288 0 0 0 0.003 0.002 0.001 0.001
0.000
i-f6a2d525 125.4 1254 0 0 0 0.004 0.002 0.001 0.001
0.000
i-e8a2d53b 133.4 1334 0 0 0 0.003 0.002 0.001 0.001
0.000
i-e81cca40 141.2 1412 0 0 0 0.003 0.002 0.001 0.001
0.000
(Commands: Help,Quit, # # # #)
This example shows an environment that has recently been scaled up from one to five instances. The
scaling operation succeeded, and all instances are now passing health checks and are ready to take
requests. In interactive mode, the health status updates every 10 seconds. In the upper-right corner, a
timer ticks down to the next update.
In the lower-left corner, the report displays a list of options. To exit interactive mode, press Q. To scroll,
press the arrow keys. To see a list of additional commands, press H.
984
AWS Elastic Beanstalk Developer Guide
Composing environments
Views
1 All tables/split view
2 Status Table
3 Request Summary Table
4 CPU%/Load Table
H This help menu
~/project-name
|-- component-a
| `-- env.yaml
`-- component-b
`-- env.yaml
Each subfolder contains the source code for an independent component of an application that will run in
its own environment and an environment definition file named env.yaml. For details on the env.yaml
format, see Environment manifest (env.yaml) (p. 727).
To use the Compose Environments API, first run eb init from the project folder, specifying each
component by the name of the folder that contains it with the --modules option:
The EB CLI prompts you to configure each component (p. 964), and then creates the
.elasticbeanstalk directory in each component folder. EB CLI doesn't create configuration files in
the parent directory.
~/project-name
|-- component-a
| |-- .elasticbeanstalk
| `-- env.yaml
985
AWS Elastic Beanstalk Developer Guide
Troubleshooting
`-- component-b
|-- .elasticbeanstalk
`-- env.yaml
Next, run the eb create command with a list of environments to create, one for each component:
This command creates an environment for each component. The names of the environments are created
by concatenating the EnvironmentName specified in the env.yaml file with the group name, separated
by a hyphen. The total length of these two options and the hyphen must not exceed the maximum
allowed environment name length of 23 characters.
You can update each component individually or you can update them as a group. Specify the
components that you want to update with the --modules option.
The EB CLI stores the group name that you used with eb create in the branch-defaults section of the
EB CLI configuration file under /.elasticbeanstalk/config.yml. To deploy your application to a
different group, use the --env-group-suffix option when you run eb deploy. If the group does not
already exist, the EB CLI will create a new group of environments:
To terminate environments, run eb terminate in the folder for each module. By default, the EB CLI will
show an error if you try to terminate an environment that another running environment is dependent on.
Terminate the dependent environment first, or use the --ignore-links option to override the default
behavior:
ERROR: An error occurred while handling git command. Error code: 128 Error: fatal: Not a valid
object name HEAD
Cause: This error message is shown when you have initialized a Git repository but have not yet
committed. The EB CLI looks for the HEAD revision when your project folder contains a Git repository.
Solution: Add the files in your project folder to the staging area and commit:
986
AWS Elastic Beanstalk Developer Guide
Troubleshooting deployments
ERROR: This branch does not have a default environment. You must either specify an environment by
typing "eb status my-env-name" or set a default environment by typing "eb use my-env-name".
Cause: When you create a new branch in git, it is not attached to an Elastic Beanstalk environment by
default.
Solution: Run eb list to see a list of available environments. Then run eb use env-name to use one of
the available environments.
ERROR: 2.0+ Platforms require a service role. You can provide one with --service-role option
Cause: If you specify an environment name with eb create (for example, eb create my-env), the EB CLI
will not attempt to create a service role for you. If you don't have the default service role, the above error
is shown.
Solution: Run eb create without an environment name and follow the prompts to create the default
service role.
Troubleshooting deployments
If your Elastic Beanstalk deployment didn't go quite as smoothly as planned, you may get a 404 (if your
application failed to launch) or 500 (if your application fails during runtime) response, instead of seeing
your website. To troubleshoot many common issues, you can use the EB CLI to check the status of your
deployment, view its logs, gain access to your EC2 instance with SSH, or to open the AWS Management
Console page for your application environment.
1. Run eb status to see the status of your current deployment and health of your EC2 hosts. For
example:
$ eb status --verbose
Note
Using the --verbose switch provides information about the status of your running
instances. Without it, eb status will print only general information about your environment.
2. Run eb health to view health information about your environment:
$ eb health --refresh
elasticBeanstalkExa-env Degraded
2016-03-28 23:13:20
WebServer
Ruby 2.1 (Puma)
total ok warning degraded severe info pending unknown
5 2 0 2 1 0 0 0
987
AWS Elastic Beanstalk Developer Guide
Troubleshooting deployments
instance-id r/sec %2xx %3xx %4xx %5xx p99 p90 p75 p50
p10
Overall 646.7 100.0 0.0 0.0 0.0 0.003 0.002 0.001 0.001
0.000
i-dac3f859 167.5 1675 0 0 0 0.003 0.002 0.001 0.001
0.000
i-05013a81 161.2 1612 0 0 0 0.003 0.002 0.001 0.001
0.000
i-04013a80 0.0 - - - - - - - -
-
i-3ab524a1 155.9 1559 0 0 0 0.003 0.002 0.001 0.001
0.000
i-bf300d3c 162.1 1621 0 0 0 0.003 0.002 0.001 0.001
0.000
The above example shows an environment with five instances where the deployment of version
"v2" failed on the third instance. After a failed deployment, the expected version is reset to the last
version that succeeded, which in this case is "Sample Application" from the first deployment. See
Using the EB CLI to monitor environment health (p. 979) for more information.
3. Run eb logs to download and view the logs associated with your application deployment.
$ eb logs
4. Run eb ssh to connect with the EC2 instance that's running your application and examine it directly.
On the instance, your deployed application can be found in the /opt/python/current/app
directory, and your Python environment will be found in /opt/python/run/venv/.
5. Run eb console to view your application environment on the AWS Management Console. You
can use the web interface to easily examine various aspects of your deployment, including
your application's configuration, status, events, logs. You can also download the current or past
application versions that you've deployed to the server.
988
AWS Elastic Beanstalk Developer Guide
EB CLI commands
Commands
• eb abort (p. 989)
• eb appversion (p. 990)
• eb clone (p. 994)
• eb codesource (p. 995)
• eb config (p. 997)
• eb console (p. 1002)
• eb create (p. 1003)
• eb deploy (p. 1013)
• eb events (p. 1014)
• eb health (p. 1015)
• eb init (p. 1017)
• eb labs (p. 1019)
• eb list (p. 1020)
• eb local (p. 1021)
• eb logs (p. 1023)
• eb open (p. 1026)
• eb platform (p. 1026)
• eb printenv (p. 1033)
• eb restore (p. 1034)
• eb scale (p. 1035)
• eb setenv (p. 1035)
• eb ssh (p. 1036)
• eb status (p. 1038)
• eb swap (p. 1039)
• eb tags (p. 1040)
• eb terminate (p. 1043)
• eb upgrade (p. 1044)
• eb use (p. 1045)
• Common options (p. 1046)
eb abort
Description
Cancels an upgrade when environment configuration changes to instances are still in progress.
989
AWS Elastic Beanstalk Developer Guide
eb appversion
Note
If you have more than two environments that are undergoing a update, you are prompted to
select the name of the environment for which you want to roll back changes.
Syntax
eb abort
eb abort environment-name
Options
Name Description
Output
The command shows a list of environments currently being updated and prompts you to choose the
update that you want to abort. If only one environment is currently being updated, you do not need to
specify the environment name. If successful, the command reverts environment configuration changes.
The rollback process continues until all instances in the environment have the previous environment
configuration or until the rollback process fails.
Example
The following example cancels the platform upgrade.
$ eb abort
Aborting update to environment "tmp-dev".
<list of events>
eb appversion
Description
The EB CLI appversion command manages your Elastic Beanstalk application versions (p. 13). You can
create a new version of the application without deploying, delete a version of the application, or create
the application version lifecycle policy (p. 382). If you invoke the command without any options, it enters
the interactive mode (p. 992).
Use the lifecycle option to display or create the application version lifecycle policy. For more
information, see the section called “Version lifecycle” (p. 382).
Syntax
eb appversion
990
AWS Elastic Beanstalk Developer Guide
eb appversion
Options
Name Description
Type: String
or
--create
--delete version-label
-l version_label Specify a label to use for the version that the EB CLI creates. If you
don't use this option, the EB CLI generates a new unique label. If
or you provide a version label, make sure that it's unique.
--label version_label Only applicable with the --create option.
Type: String
or
lifecycle --print
-m "version_description" The description for the application version. It's enclosed in double
quotation marks.
or
Only applicable with the --create option.
--message
"version_description" Type: String
991
AWS Elastic Beanstalk Developer Guide
eb appversion
Name Description
Type: String
Only applicable with the --create option.
--staged Use the files staged in the git index, instead of the HEAD commit, to
create the application version.
--timeout minutes The number of minutes before the command times out.
Press d to delete an application version, press l to manage the lifecycle policy for your application, or
press q to quit without making any changes.
Note
If the version is deployed to any environment, you can't delete that version.
Output
The command with the --create option displays a message confirming that the application version was
created.
The command with the --delete version-label option displays a message confirming that the
application version was deleted.
Examples
The following example shows the interactive window for an application with no deployments.
992
AWS Elastic Beanstalk Developer Guide
eb appversion
The following example shows the interactive window for an application with the fourth version, with
version label Sample Application, deployed.
The following example shows the output from an eb appversion lifecycle -p command, where
ACCOUNT-ID is the user's account ID:
993
AWS Elastic Beanstalk Developer Guide
eb clone
VersionLifecycleConfig:
MaxCountRule:
DeleteSourceFromS3: False
Enabled: False
MaxCount: 200
MaxAgeRule:
DeleteSourceFromS3: False
Enabled: False
MaxAgeInDays: 180
ServiceRole: arn:aws:iam::ACCOUNT-ID:role/aws-elasticbeanstalk-service-role
eb clone
Description
Clones an environment to a new environment so that both have identical environment settings.
Note
By default, regardless of the solution stack version of the environment from which you create
the clone, the eb clone command creates the clone environment with the most recent solution
stack. You can suppress this by including the --exact option when you run the command.
Syntax
eb clone
eb clone environment-name
Options
Name Description
or
--clone_name string
or
--cname string
Type: String
Constraints:
994
AWS Elastic Beanstalk Developer Guide
eb codesource
Name Description
• Values cannot match the environment name.
• Values cannot include either aws: or elasticbeanstalk:.
• The combined size of all environment properties cannot exceed
4096 bytes.
--exact Prevents Elastic Beanstalk from updating the solution stack version
for the new clone environment to the most recent version available
(for the original environment's platform).
--scale number The number of instances to run in the clone environment when it is
launched.
--tags name=value Tags (p. 587) for the resources in your environment in a comma-
separated list with the format name=value.
Output
If successful, the command creates an environment that has the same settings as the original
environment or with modifications to the environment as specified by any eb clone options.
Example
The following example clones the specified environment.
$ eb clone
Enter name for Environment Clone
(default is tmp-dev-clone):
Enter DNS CNAME prefix
(default is tmp-dev-clone):
Environment details for: tmp-dev-clone
Application name: tmp
Region: us-west-2
Deployed Version: app-141029_144740
Environment ID: e-vjvrqnn5pv
Platform: 64bit Amazon Linux 2014.09 v1.0.9 running PHP 5.5
Tier: WebServer-Standard-1.0
CNAME: tmp-dev-clone.elasticbeanstalk.com
Updated: 2014-10-29 22:00:23.008000+00:00
Printing Status:
2018-07-11 21:04:20 INFO: createEnvironment is starting.
2018-07-11 21:04:21 INFO: Using elasticbeanstalk-us-west-2-888888888888 as Amazon S3
storage bucket for environment data.
...
2018-07-11 21:07:10 INFO: Successfully launched environment: tmp-dev-clone
eb codesource
Description
Configures the EB CLI to deploy from a CodeCommit repository (p. 975), or disables CodeCommit
integration and uploads the source bundle from your local machine.
995
AWS Elastic Beanstalk Developer Guide
eb codesource
Note
Some AWS Regions don't offer CodeCommit. The integration between Elastic Beanstalk and
CodeCommit doesn't work in these Regions.
For information about the AWS services offered in each Region, see Region Table.
Syntax
eb codesource
eb codesource codecommit
eb codesource local
Options
Name Description
Output
eb codesource prompts you to choose between CodeCommit integration and standard deployments.
eb codesource local shows the original configuration and disables CodeCommit integration.
Examples
Use eb codesource codecommit to configure CodeCommit integration for the current branch.
Select a branch
1) mainline
2) test
3) [ Create new Branch with local HEAD ]
(default is 1): 1
Use eb codesource local to disable CodeCommit integration for the current branch.
996
AWS Elastic Beanstalk Developer Guide
eb config
eb config
Description
Manages the active configuration (p. 13) settings and saved configurations (p. 14) of your environment.
You can use this command to upload, download, or list the saved configurations of your environment.
You can also use it to download, display, or update its active configuration settings.
If the root directory contains a platform.yaml file specifying a custom platform, this command
also changes the builder configuration settings. This is done based on the values that are set in
platform.yaml.
Note
eb config doesn't show environment properties. To set environment properties that you can
read from within your application, use eb setenv (p. 629) instead.
Syntax
The following are parts of the syntax that's used for the eb config command to work with the active
configuration settings (p. 13) of your environment. For specific examples, see the Examples (p. 1000)
section later in this topic.
• eb config – Displays the active configuration settings of your environment in a text editor that you
configured as the EDITOR environment variable. When you save changes to the file and close the
editor, the environment is updated with the option settings that you saved in the file.
Note
If you didn't configure an EDITOR environment variable, EB CLI displays your option settings
in your default editor for YAML files.
• eb config environment-name – Displays and updates the configuration for the named environment.
The configuration is either displayed in a text editor that you configured or your default editor YAML
files.
• eb config save – Saves the active configuration settings for the current environment to
.elasticbeanstalk/saved_configs/ with the filename [configuration-name].cfg.yml.
By default, the EB CLI saves the configuration settings with a configuration-name based on the
environment name. You can specify a different configuration name by including the --cfg option with
your desired configuration name when you run the command.
You can tag your saved configuration using the --tags option.
• eb config --display – Writes an environment's active configuration settings to stdout instead of a
file. By default this displays the configuration settings to the terminal.
• eb config --update configuration_string | file_path – Updates the active configuration
settings for the current environment with the information that's specified in configuration_string
or inside the file identified by file_path.
Note
The --display and --update options provide flexibility for reading and revising an
environment's configuration settings programmatically.
The following describes the syntax for using the eb config command to work with saved
configurations (p. 14). For examples, see the Examples (p. 1000) section later in this topic.
• eb config get config-name – Downloads the named saved configuration from Amazon S3.
997
AWS Elastic Beanstalk Developer Guide
eb config
• eb config delete config-name – Deletes the named saved configuration from Amazon S3. Also
deletes it locally, if you already downloaded it.
• eb config list – Lists the saved configurations that you have in Amazon S3.
• eb config put filename – Uploads the named saved configuration to an Amazon S3 bucket. The
filename must have the file extension .cfg.yml. To specify the file name without a path, you can
save the file to the .elasticbeanstalk folder or to the .elasticbeanstalk/saved_configs/
folder before you run the command. Alternatively, you can specify the filename by providing the full
path.
Options
Name Description
This option only works if you use the eb config command without
any of the other subcommands.
or Defaults to YAML.
--format format_type This option works with the --display option only.
--timeout timeout The number of minutes before the command times out.
or This option only works if you use the eb config command without
any of the other subcommands.
--update
configuration_string | The configuration_string | file_path parameter is of
file_path the type string. The string provides the list of namespaces and
corresponding options to add to, update, or remove from the
configuration settings for your environment. Alternatively, the input
string can represent a file that contains the same information.
To specify a file name, the input string must follow the format
"file://<path><filename>". To specify the file name without
a path, save the file to the folder where you run the command.
Alternatively, specify the filename by providing the full path.
998
AWS Elastic Beanstalk Developer Guide
eb config
Name Description
The configuration information must meet the following conditions.
At least one of the sections, OptionSettings or OptionsToRemove,
is required. Use OptionSettings to add or change options. Use
OptionsToRemove to remove options from a namespace. For
specific examples, see the Examples (p. 1000) section later in this
topic.
Example
YAML Format
OptionSettings:
namespace1:
option-name-1: option-value-1
option-name-2: option-value-2
...
OptionsToRemove:
namespace1:
option-name-1
option-name-2
...
Example
JSON Format
{
"OptionSettings": {
"namespace1": {
"option-name-1": "option-value-1",
"option-name-2": "option-value-2",
...
}
},
"OptionsToRemove": {
"namespace1": {
"option-name-1",
"option-name-2",
...
}
}
}
Output
If the eb config or eb config environment-name command is run successfully with no subcommands or
options added, the command displays your current option settings in the text editor that you configured
as the EDITOR environment variable. If you didn't configure an EDITOR environment variable, EB CLI
displays your option settings in your default editor for YAML files.
When you save changes to the file and close the editor, the environment is updated with the option
settings that you saved in the file. The following output is displayed to confirm the configuration update.
$ eb config myApp-dev
999
AWS Elastic Beanstalk Developer Guide
eb config
Printing Status:
2021-05-19 18:09:45 INFO Environment update is starting.
2021-05-19 18:09:55 INFO Updating environment myApp-dev's configuration settings.
2021-05-19 18:11:20 INFO Successfully deployed new configuration to environment.
If the command runs successfully with the --display option, it displays the configuration settings for
the current environment (writes to stdout).
If the command runs successfully with the get parameter, the command displays the location of the
local copy that you downloaded.
If the command runs successfully with the save parameter, the command displays the location of the
saved file.
Examples
This section describes how to change the text editor that you use to view and edit your option settings
file.
For Linux and UNIX, the following example changes the editor to vim:
$ export EDITOR=vim
For Linux and UNIX, the following example changes the editor to whatever is installed at /usr/bin/
kate.
$ export EDITOR=/usr/bin/kate
This section provides examples for the eb config command when it's run with subcommands.
The following example downloads the saved configuration with the name app-tmp from your Amazon
S3 bucket.
The following example lists the names of saved configurations that are stored in your Amazon S3 bucket.
$ eb config list
The following example uploads the local copy of the saved configuration named app-tmp to your
Amazon S3 bucket.
The following example saves configuration settings from the current running environment. If you don't
provide a name to use for the saved configuration, then Elastic Beanstalk names the configuration file
1000
AWS Elastic Beanstalk Developer Guide
eb config
according to the environment name. For example, an environment named tmp-dev would be called tmp-
dev.cfg.yml. Elastic Beanstalk saves the file to the /.elasticbeanstalk/saved_configs/ folder.
$ eb config save
In the following example, the --cfg option is used to save the configuration settings from the
environment tmp-dev to a file called v1-app-tmp.cfg.yml. Elastic Beanstalk saves the file to the
folder /.elasticbeanstalk/saved_configs/. If you don't specify an environment name, Elastic
Beanstalk saves configuration settings from the current running environment.
This section provides examples for the eb config command when it's run without subcommands.
The following command displays the option settings of your current environment in a text editor.
$ eb config
The following command displays the option settings for the my-env environment in a text editor.
$ eb config my-env
The following example displays the options settings for your current environment. It outputs in the YAML
format because no specific format was specified with the --format option.
$ eb config --display
The following example updates the options settings for your current environment with the specifications
in the file named example.txt. The file is in either the YAML or JSON format. The EB CLI automatically
detects the file format.
OptionSettings:
'aws:elasticbeanstalk:command':
BatchSize: '30'
BatchSizeType: Percentage
'aws:autoscaling:asg':
MinSize: '1'
OptionsToRemove:
'AWSEBV2LoadBalancer.aws:elbv2:loadbalancer':
IdleTimeout
1001
AWS Elastic Beanstalk Developer Guide
eb console
"OptionSettings": {
"aws:elasticbeanstalk:command": {
"BatchSize": "30",
"BatchSizeType": "Percentage"
},
"aws:autoscaling:asg": {
"MinSize": "1"
}
},
"OptionsToRemove": {
"AWSEBV2LoadBalancer.aws:elbv2:loadbalancer": {
"IdleTimeout"
}
}
}
The following examples update the options settings for your current environment. The command sets
the Minsize option to 1 for theaws:autoscaling:asg namespace.
Note
These examples are specific to Windows PowerShell. They escape literal occurrences of the
double-quote (") character by preceding it with a slash (\) character. Different operating
systems and command-line environments might have different escape sequences. For this
reason, we recommend using the file option that's shown in the previous examples. Specifying
the configuration options in a file doesn't require escaping characters and is consistent across
different operating systems.
The following example is in JSON format. The EB CLI detects if the format is in JSON or YAML.
The following example is in YAML format. To enter the YAML string in the correct format, the command
includes spacing and end-of-line returns that are required in a YAML file.
eb console
Description
Opens a browser to display the environment configuration dashboard in the Elastic Beanstalk
Management Console.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
displays the builder environment configuration, as specified in platform.yaml, in the Elastic Beanstalk
Management Console.
Syntax
eb console
1002
AWS Elastic Beanstalk Developer Guide
eb create
eb console environment-name
Options
Name Description
eb create
Description
Creates a new environment and deploys an application version to it.
Note
• To use eb create on a .NET application, you must create a deployment package as described in
Creating a source bundle for a .NET application (p. 390), then set up the CLI configuration to
deploy the package as an artifact as described in Deploying an artifact instead of the project
folder (p. 967).
• Creating environments with the EB CLI requires a service role (p. 20). You can create a service
role by creating an environment in the Elastic Beanstalk console. If you don't have a service
role, the EB CLI attempts to create one when you run eb create.
• By default: From the application source code in the local project directory.
• Using the --version option: From an application version that already exists in your application.
• When your project directory doesn't have application code, or when using the --sample option:
Deployed from a sample application, specific to your environment's platform.
Syntax
eb create
eb create environment-name
An environment name must be between 4 and 40 characters in length. It can only contain letters,
numbers, and hyphens (-). An environment name can't begin or end with a hyphen.
If you include an environment name in the command, the EB CLI doesn't prompt you to make any
selections or create a service role.
If you run the command without an environment name argument, it runs in an interactive flow, and
prompts you to enter or select values for some settings. In this interactive flow, in case you are deploying
a sample application, the EB CLI also asks you if you want to download this sample application to your
local project directory. By downloading it, you can use the EB CLI with the new environment later to run
operations that require the application's code, such as eb deploy (p. 1013).
Some interactive flow prompts are displayed only under certain conditions. For example, if you choose to
use an Application Load Balancer, and your account has at least one sharable Application Load Balancer,
Elastic Beanstalk displays a prompt that asks if you want to use a shared load balancer. If no sharable
Application Load Balancer exists in your account, this prompt isn't displayed.
1003
AWS Elastic Beanstalk Developer Guide
eb create
Options
None of these options are required. If you run eb create without any options, the EB CLI prompts you to
enter or select a value for each setting.
Name Description
--branch_default
--cfg config-name Use platform settings from a saved configuration (p. 622) in
.elasticbeanstalk/saved_configs/ or your Amazon
S3 bucket. Specify the name of the file only, without the
.cfg.yml extension.
-c subdomain-name The subdomain name to prefix the CNAME DNS entry that
routes to your website.
or
Type: String
--cname subdomain-name
Default: The environment name
-db.engine engine The database engine type. If you run eb create with this
option, then EB CLI launches the environment with a
or database attached. This is the case even if you didn't run the
command with the --database option.
--database.engine engine
Type: String
-db.i instance_type The type of Amazon EC2 instance to use for the database. If
you run eb create with this option, then EB CLI launches the
or environment with a database attached. This is the case even
if you didn't run the command with the --database option.
--database.instance
instance_type Type: String
Valid values:
-db.pass password The password for the database. If you run eb create with
this option, then EB CLI launches the environment with a
or
1004
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
--database.password password database attached. This is the case even if you didn't run the
command with the --database option.
Valid values:
-db.user username The user name for the database. If you run eb create with
this option, then EB CLI launches the environment with a
or database attached even if you didn't run the command with
the --database option. If you run eb create with the --
--database.username username database option, but without the --database.username
and --database.password options, then EB CLI prompts
you for the master database user name and password.
-db.version version Used to specify the database engine version. If this flag is
present, the environment will launch with a database with
or the specified version number, even if the --database flag
isn't present.
--database.version version
Type: String
Default: application
--env-group-suffix groupname The group name to append to the environment name. Only
for use with Compose Environments (p. 985).
1005
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
-ip profile_name The instance profile with the IAM role with the temporary
security credentials that your application needs to access
or AWS resources.
--instance_profile
profile_name
-k key_name The name of the Amazon EC2 key pair to use with the Secure
Shell (SSH) client to securely log in to the Amazon EC2
or instances that are running your Elastic Beanstalk application.
If you include this option with the eb create command, the
--keyname key_name value you provide overwrites any key name that you might
have specified with eb init.
-im number-of-instances The minimum number of Amazon EC2 instances that you
require your environment to have.
or
Type: Number (integer)
--min-instances number-of-
instances Default: 1
1006
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
-ix number-of-instances The maximum number of Amazon EC2 instances you allow
your environment to have.
or
Type: Number (integer)
--max-instances number-of-
instances Default: 4
Default: 0
1007
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
-p platform-version The platform version (p. 29) to use. You can specify a
platform, a platform and version, a platform branch, a
or solution stack name, or a solution stack ARN. For example:
--platform platform-version • php, PHP, node.js – The latest platform version for the
specified platform
• php-7.2, "PHP 7.2" – The recommended (typically
latest) PHP 7.2 platform version
• "PHP 7.2 running on 64bit Amazon Linux" – The
recommended (typically latest) PHP platform version in
this platform branch
• "64bit Amazon Linux 2017.09 v2.6.3 running
PHP 7.1" – The PHP platform version specified by this
solution stack name
• "arn:aws:elasticbeanstalk:us-
east-2::platform/PHP 7.1 running on 64bit
Amazon Linux/2.6.3" – The PHP platform version
specified by this solution stack ARN
-r region The AWS Region where you want to deploy the application.
or For the list of values you can specify for this option, see AWS
Elastic Beanstalk Endpoints and Quotas in the AWS General
--region region Reference.
1008
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
Parameter examples:
-lp port The default listener port of the shared load balancer for
this environment. Elastic Beanstalk adds a listener rule
or that routes all traffic from this listener to the default
environment process. For more information, see Shared
--shared-lb-port port Application Load Balancer (p. 554).
Default: 80
1009
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
-sm The maximum price per unit hour, in US dollars, that you're
willing to pay for a Spot Instance.
or
This option can only be specified with the --enable-spot
--spot-max-price option. For more details, see Auto Scaling group (p. 511).
--tier worker
--timeout minutes Set number of minutes before the command times out.
--version version_label Specifies the application version that you want deployed to
the environment instead of the application source code in
the local project directory.
Type: String
1010
AWS Elastic Beanstalk Developer Guide
eb create
Name Description
Output
If successful, the command prompts you with questions and then returns the status of the create
operation. If there were problems during the launch, you can use the eb events (p. 1014) operation to
get more details.
If you enabled CodeBuild support in your application, eb create displays information from CodeBuild as
your code is built. For information about CodeBuild support in Elastic Beanstalk, see Using the EB CLI
with AWS CodeBuild (p. 972).
Examples
The following example creates an environment in interactive mode.
$ eb create
Enter Environment Name
(default is tmp-dev): ENTER
Enter DNS CNAME prefix
(default is tmp-dev): ENTER
Select a load balancer type
1) classic
2) application
3) network
(default is 2): ENTER
Environment details for: tmp-dev
Application name: tmp
Region: us-east-2
Deployed Version: app-141029_145448
Environment ID: e-um3yfrzq22
Platform: 64bit Amazon Linux 2014.09 v1.0.9 running PHP 5.5
Tier: WebServer-Standard-1.0
CNAME: tmp-dev.elasticbeanstalk.com
Updated: 2014-10-29 21:54:51.063000+00:00
Printing Status:
...
1011
AWS Elastic Beanstalk Developer Guide
eb create
The following example also creates an environment in interactive mode. In this example, your project
directory doesn't have application code. The command deploys a sample application and downloads it to
your local project directory.
$ eb create
Enter Environment Name
(default is tmp-dev): ENTER
Enter DNS CNAME prefix
(default is tmp-dev): ENTER
Select a load balancer type
1) classic
2) application
3) network
(default is 2): ENTER
NOTE: The current directory does not contain any source code. Elastic Beanstalk is
launching the sample application instead.
Do you want to download the sample application into the current directory?
(Y/n): ENTER
INFO: Downloading sample application to the current directory.
INFO: Download complete.
Environment details for: tmp-dev
Application name: tmp
Region: us-east-2
Deployed Version: Sample Application
Environment ID: e-um3yfrzq22
Platform: 64bit Amazon Linux 2014.09 v1.0.9 running PHP 5.5
Tier: WebServer-Standard-1.0
CNAME: tmp-dev.elasticbeanstalk.com
Updated: 2017-11-08 21:54:51.063000+00:00
Printing Status:
...
$ eb create dev-env
Creating application version archive "app-160312_014028".
Uploading test/app-160312_014028.zip to S3. This may take a while.
Upload Complete.
Application test has been created.
Environment details for: dev-env
Application name: test
Region: us-east-2
Deployed Version: app-160312_014028
Environment ID: e-6fgpkjxyyi
Platform: 64bit Amazon Linux 2015.09 v2.0.8 running PHP 5.6
Tier: WebServer-Standard
CNAME: UNKNOWN
Updated: 2016-03-12 01:40:33.614000+00:00
Printing Status:
...
1012
AWS Elastic Beanstalk Developer Guide
eb deploy
eb deploy
Description
Deploys the application source bundle from the initialized project directory to the running application.
If git is installed, EB CLI uses the git archive command to create a .zip file from the contents of the
most recent git commit command.
However, when .ebignore is present in your project directory, the EB CLI doesn't use git commands and
semantics to create your source bundle. This means that EB CLI ignores files specified in .ebignore, and
includes all other files. In particular, it includes uncommitted source files.
Note
You can configure the EB CLI to deploy an artifact from your build process instead of creating a
ZIP file of your project folder. See Deploying an artifact instead of the project folder (p. 967)
for details.
Syntax
eb deploy
eb deploy environment-name
Options
Name Description
-l version_label Specify a label to use for the version that the EB CLI creates. If the
label has already been used, the EB CLI redeploys the previous
or version with that label.
--label version_label Type: String
--env-group-suffix Group name to append to the environment name. Only for use
groupname with Compose Environments (p. 985).
--modules component-a List of components to update. Only for use with Compose
component-b Environments (p. 985).
1013
AWS Elastic Beanstalk Developer Guide
eb events
Name Description
--source CodeCommit repository and branch. See Using the EB CLI with
codecommit/repository- AWS CodeCommit (p. 975).
name/branch-name
--staged Deploy files staged in the git index instead of the HEAD commit.
--timeout minutes The number of minutes before the command times out.
Type: String
Output
If successful, the command returns the status of the deploy operation.
If you enabled CodeBuild support in your application, eb deploy displays information from CodeBuild
as your code is built. For information about CodeBuild support in Elastic Beanstalk, see Using the EB CLI
with AWS CodeBuild (p. 972).
Example
The following example deploys the current application.
$ eb deploy
2018-07-11 21:05:22 INFO: Environment update is starting.
2018-07-11 21:05:27 INFO: Deploying new version to instance(s).
2018-07-11 21:05:53 INFO: New application version was deployed to running EC2 instances.
2018-07-11 21:05:53 INFO: Environment update completed successfully.
eb events
Description
Returns the most recent events for the environment.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
returns the most recent evens for the builder environment.
Syntax
eb events
eb events environment-name
Options
Name Description
or
1014
AWS Elastic Beanstalk Developer Guide
eb health
Name Description
--follow
Output
If successful, the command returns recent events.
Example
The following example returns the most recent events.
$ eb events
2014-10-29 21:55:39 INFO createEnvironment is starting.
2014-10-29 21:55:40 INFO Using elasticbeanstalk-us-west-2-111122223333 as Amazon S3
storage bucket for environment data.
2014-10-29 21:55:57 INFO Created load balancer named: awseb-e-r-AWSEBLoa-
NSKUOK5X6Z9J
2014-10-29 21:56:16 INFO Created security group named: awseb-e-rxgrhjr9bx-stack-
AWSEBSecurityGroup-1UUHU5LZ20ZY7
2014-10-29 21:57:18 INFO Waiting for EC2 instances to launch. This may take a few
minutes.
2014-10-29 21:57:18 INFO Created Auto Scaling group named: awseb-e-rxgrhjr9bx-stack-
AWSEBAutoScalingGroup-1TE320ZCJ9RPD
2014-10-29 21:57:22 INFO Created Auto Scaling group policy named:
arn:aws:autoscaling:us-east-2:11122223333:scalingPolicy:2cced9e6-859b-421a-
be63-8ab34771155a:autoScalingGroupName/awseb-e-rxgrhjr9bx-stack-
AWSEBAutoScalingGroup-1TE320ZCJ9RPD:policyName/awseb-e-rxgrhjr9bx-stack-
AWSEBAutoScalingScaleUpPolicy-1I2ZSNVU4APRY
2014-10-29 21:57:22 INFO Created Auto Scaling group policy named:
arn:aws:autoscaling:us-east-2:11122223333:scalingPolicy:1f08b863-
bf65-415a-b584-b7fa3a69a0d5:autoScalingGroupName/awseb-e-rxgrhjr9bx-stack-
AWSEBAutoScalingGroup-1TE320ZCJ9RPD:policyName/awseb-e-rxgrhjr9bx-stack-
AWSEBAutoScalingScaleDownPolicy-1E3G7PZKZPSOG
2014-10-29 21:57:25 INFO Created CloudWatch alarm named: awseb-e-rxgrhjr9bx-stack-
AWSEBCloudwatchAlarmLow-VF5EJ549FZBL
2014-10-29 21:57:25 INFO Created CloudWatch alarm named: awseb-e-rxgrhjr9bx-stack-
AWSEBCloudwatchAlarmHigh-LA9YEW3O6WJO
2014-10-29 21:58:50 INFO Added EC2 instance 'i-c7ee492d' to Auto ScalingGroup
'awseb-e-rxgrhjr9bx-stack-AWSEBAutoScalingGroup-1TE320ZCJ9RPD'.
2014-10-29 21:58:53 INFO Successfully launched environment: tmp-dev
2014-10-29 21:59:14 INFO Environment health has been set to GREEN
2014-10-29 21:59:43 INFO Adding instance 'i-c7ee492d' to your environment.
eb health
Description
Returns the most recent health for the environment.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
returns the most recent health for the builder environment.
Syntax
eb health
eb health environment-name
1015
AWS Elastic Beanstalk Developer Guide
eb health
Options
Name Description
--refresh
Output
If successful, the command returns recent health.
Example
The following example returns the most recent health information for a Linux environment.
~/project $ eb health
elasticBeanstalkExa-env Ok
2015-07-08 23:13:20
WebServer Ruby
2.1 (Puma)
total ok warning degraded severe info pending unknown
5 5 0 0 0 0 0 0
instance-id r/sec %2xx %3xx %4xx %5xx p99 p90 p75 p50
p10 requests
Overall 671.8 100.0 0.0 0.0 0.0 0.003 0.002 0.001 0.001
0.000
i-d581497d 143.0 1430 0 0 0 0.003 0.002 0.001 0.001
0.000
i-d481497c 128.8 1288 0 0 0 0.003 0.002 0.001 0.001
0.000
i-136e00c0 125.4 1254 0 0 0 0.004 0.002 0.001 0.001
0.000
i-126e00c1 133.4 1334 0 0 0 0.003 0.002 0.001 0.001
0.000
i-8b2cf575 141.2 1412 0 0 0 0.003 0.002 0.001 0.001
0.000
1016
AWS Elastic Beanstalk Developer Guide
eb init
eb init
Description
Sets default values for Elastic Beanstalk applications created with EB CLI by prompting you with a series
of questions.
Note
The values you set with eb init apply only to the current directory and repository on the current
computer.
The command doesn't create anything in your Elastic Beanstalk account. To create an Elastic
Beanstalk environment, run eb create (p. 1003) after running eb init.
Syntax
eb init
eb init application-name
Options
If you run eb init without specifying the --platform option, the EB CLI prompts you to enter a value
for each setting.
Note
To use eb init to create a new key pair, you must have ssh-keygen installed on your local
machine and available from the command line.
Name Description
-k keyname The name of the Amazon EC2 key pair to use with the
Secure Shell (SSH) client to securely log in to the Amazon
--keyname keyname EC2 instances running your Elastic Beanstalk application.
1017
AWS Elastic Beanstalk Developer Guide
eb init
Name Description
--modules folder-1 List of child directories to initialize. Only for use with
folder-2 Compose Environments (p. 985).
-p platform-version The platform version (p. 29) to use. You can specify a
platform, a platform and version, a platform branch,
--platform platform- a solution stack name, or a solution stack ARN. For
version example:
CodeBuild support
If you run eb init in a folder that contains a buildspec.yml file, Elastic Beanstalk parses the file for an
eb_codebuild_settings entry with options specific to Elastic Beanstalk. For information about CodeBuild
support in Elastic Beanstalk, see Using the EB CLI with AWS CodeBuild (p. 972).
1018
AWS Elastic Beanstalk Developer Guide
eb labs
Output
If successful, the command guides you through setting up a new Elastic Beanstalk application through a
series of prompts.
Example
The following example request initializes EB CLI and prompts you to enter information about your
application. Replace placeholder text with your own values.
$ eb init -i
Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : Europe (Ireland)
5) eu-central-1 : Europe (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
...
(default is 3): 3
Select a keypair.
1) aws-eb
2) [ Create new KeyPair ]
(default is 2): 1
eb labs
Description
Subcommands of eb labs support work-in-progress or experimental functionality. These commands
may be removed or reworked in future versions of the EB CLI and are not guaranteed to be forward
compatible.
1019
AWS Elastic Beanstalk Developer Guide
eb list
eb list
Description
Lists all environments in the current application or all environments in all applications, as specified by
the --all option.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
lists the builder environments.
Syntax
eb list
Options
Name Description
or
--all
--verbose
Output
If successful, the command returns a list of environment names in which your current environment is
marked with an asterisk (*).
Example 1
The following example lists your environments and indicates that tmp-dev is your default environment.
$ eb list
* tmp-dev
Example 2
The following example lists your environments with additional details.
$ eb list --verbose
Region: us-west-2
Application: tmp
1020
AWS Elastic Beanstalk Developer Guide
eb local
Environments: 1
* tmp-dev : ['i-c7ee492d']
eb local
Description
Use eb local run to run your application's containers locally in Docker. Check the application's container
status with eb local status. Open the application in a web browser with eb local open. Retrieve the
location of the application's logs with eb local logs.
eb local setenv and eb local printenv let you set and view environment variables that are provided to
the Docker containers that you run locally with eb local run.
You must run all eb local commands in the project directory of a Docker application that has been
initialized as an EB CLI repository by using eb init.
Note
Use eb local on a local computer running Linux or macOS. The command doesn't support
Windows.
Before using the command on macOS, install Docker for Mac, and ensure that boot2docker isn't
installed (or isn't in the execution path). The eb local command tries to use boot2docker if it's
present, but doesn't work well with it on macOS.
Syntax
eb local run
eb local status
eb local open
eb local logs
eb local setenv
eb local printenv
Options
eb local run
Name Description
--envvars Sets environment variables that the EB CLI will pass to the local
key1=value1,key2=value2 Docker containers. In multicontainer environments, all variables are
passed to all containers.
--port hostport Maps a port on the host to the exposed port on the container. If
you don't specify this option, the EB CLI uses the same port on both
host and container.
1021
AWS Elastic Beanstalk Developer Guide
eb local
Name Description
eb local status
eb local open
eb local logs
eb local setenv
eb local printenv
Name Description
Output
eb local run
Status messages from Docker. Remains active as long as application is running. Press Ctrl+C to stop the
application.
eb local status
eb local open
eb local logs
The location of the logs generated in your project directory by applications running locally under eb
local run.
eb local setenv
None
eb local printenv
The name and values of environment variables set with eb local setenv.
Examples
eb local run
1022
AWS Elastic Beanstalk Developer Guide
eb logs
eb local status
eb local logs
eb local setenv
eb logs
Description
The eb logs command has two distinct purposes: to enable or disable log streaming to CloudWatch Logs,
and to retrieve instance logs or CloudWatch Logs logs. With the --cloudwatch-logs (-cw) option, the
command enables or disables log streaming. Without this option, it retrieves logs.
When retrieving logs, specify the --all, --zip, or --stream option to retrieve complete logs. If you
don't specify any of these options, Elastic Beanstalk retrieves tail logs.
The command processes logs for the specified or default environment. Relevant logs vary by container
type. If the root directory contains a platform.yaml file specifying a custom platform, this command
also processes logs for the builder environment.
1023
AWS Elastic Beanstalk Developer Guide
eb logs
For more information, see the section called “CloudWatch Logs” (p. 831).
Syntax
To enable or disable log streaming to CloudWatch Logs:
Options
Name Description
-cls instance | Specifies the source of logs when working with CloudWatch Logs.
environment-health | all With the enable or disable form of the command, these are the logs
for which to enable or disable CloudWatch Logs streaming. With
or the retrieval form of the command, these are the logs to retrieve
from CloudWatch Logs.
--cloudwatch-log-source
instance | environment- Valid values:
health | all
• With --cloudwatch-logs (enable or disable) – instance |
environment-health | all
• Without --cloudwatch-logs (retrieve) – instance |
environment-health
Value meanings:
--all
1024
AWS Elastic Beanstalk Developer Guide
eb logs
Name Description
--zip
--stream Streams (continuously outputs) complete logs. With this option, the
command keeps running until you interrupt it (press Ctrl+C).
or
--instance instance-id
-g log-group Specifies the CloudWatch Logs log group from which to retrieve
logs. The option is valid only when instance log streaming to
or CloudWatch Logs is enabled.
--log-group log-group If instance log streaming is enabled, and you don't specify the --
log-group option, the default log group is one of the following:
For information about the log group corresponding to each log file,
see How Elastic Beanstalk sets up CloudWatch Logs (p. 834).
Output
By default, displays the logs directly in the terminal. Uses a paging program to display the output. Press
Q or q to exit.
With --stream, shows existing logs in the terminal and keeps running. Press Ctrl+C to exit.
With --all and --zip, saves the logs to local files and displays the file location.
Examples
The following example enables instance log streaming to CloudWatch Logs.
1025
AWS Elastic Beanstalk Developer Guide
eb open
$ eb logs --zip
Retrieving logs...
Logs were saved to /home/workspace/environment/.elasticbeanstalk/logs/150622_173444.zip
eb open
Description
Opens the public URL of your website in the default browser.
Syntax
eb open
eb open environment-name
Options
Name Description
Output
The command eb open does not have output. Instead, it opens the application in a browser window.
eb platform
Description
This command supports two different workspaces:
Use this workspace to select a default platform or show information about the current platform.
1026
AWS Elastic Beanstalk Developer Guide
eb platform
Syntax
eb platform create [version] [options]
Options
Name Description
create [version] Build a new version of the platform. Learn more (p. 1028).
[options]
delete version [options] Delete a platform version. Learn more (p. 1029).
events [version] Display the events from a platform version. Learn more (p. 1029).
[options]
list [options] List the versions of the current platform. Learn more (p. 1030).
logs [version] [options] Display logs from the builder environment for a platform version.
Learn more (p. 1031).
status [version] Display the status of the a platform version. Learn more (p. 1031).
[options]
use [platform] [options] Select a different platform from which new versions are built. Learn
more (p. 1031).
Common options
All eb platform commands include the following common options.
Name Description
OR
--help
1027
AWS Elastic Beanstalk Developer Guide
eb platform
Name Description
OR
--verbose
OR
--region REGION
Eb platform create
Builds a new version of the platform and returns the ARN for the new version. If there is no builder
environment running in the current region, this command launches one. The version and increment
options (-M, -m, and -p) are mutually exclusive.
Options
Name Description
version If version isn't specified, creates a new version based on the most-
recent platform with the patch version (N in n.n.N) incremented.
OR
--major-increment
OR
--minor-increment
OR
--patch-increment
OR
--instance-type
INSTANCE_TYPE
1028
AWS Elastic Beanstalk Developer Guide
eb platform
Name Description
For more details, see Tagging custom platform versions (p. 1075).
--timeout minutes Set number of minutes before the command times out.
Eb platform delete
Delete a platform version. The version isn't deleted if an environment is using that version.
Options
Name Description
Eb platform events
Display the events from a platform version. If version is specified, display the events from that version,
otherwise display the events from the current version.
Options
Name Description
version The version for which events are displayed. This value is required.
OR
--follow
1029
AWS Elastic Beanstalk Developer Guide
eb platform
Eb platform init
Initialize a platform repository.
Options
Name Description
platform The name of the platform to initialize. This value is required, unless
-i (interactive mode) is enabled.
OR
--interactive
OR
--keyname KEYNAME
You can run this command in a directory that has been previously initialized, although you cannot
change the workspace type if run in a directory that has been previously initialized.
Eb platform list
List the versions of the platform associated with a workspace (directory) or a region.
The command returns different results depending on the type of workspace you run it in, as follows:
• In a platform workspace (a directory initialized by eb platform init), the command returns a list of
all platform versions of the custom platform defined in the workspace. Add the --all-platforms or
--verbose option to get a list of all platform versions of all custom platforms your account has in the
region associated with the workspace.
• In an application workspace (a directory initialized by eb init), the command returns a list of all
platform versions, both for platforms managed by Elastic Beanstalk and for your account's custom
platforms. The list uses short platform version names, and some platform version variants might be
combined. Add the --verbose option to get a detailed list with full names and all variants listed
separately.
• In an uninitialized directory, the command only works with the --region option. It returns a list of
all Elastic Beanstalk-managed platform versions supported in the region. The list uses short platform
version names, and some platform version variants might be combined. Add the --verbose option to
get a detailed list with full names and all variants listed separately.
Options
Name Description
1030
AWS Elastic Beanstalk Developer Guide
eb platform
Name Description
OR • Ready
• Failed
--status STATUS
• Deleting
• Creating
Eb platform logs
Display logs from the builder environment for a platform version.
Options
Name Description
version The version of the platform for which logs are displayed. If omitted,
display logs from the current version.
Eb platform status
Display the status of the a platform version.
Options
Name Description
version The version of the platform for which the status is retrieved. If
omitted, display the status of the current version.
Eb platform use
Select a different platform from which new versions are built.
Options
Name Description
platform Specifies platform as the active version for this workspace. This
value is required.
1031
AWS Elastic Beanstalk Developer Guide
eb platform
Syntax
eb platform list
eb platform select
eb platform show
Options
Name Description
Example 1
The following example lists the names of all configurations for all platforms that Elastic Beanstalk
supports.
$ eb platform list
docker-1.5.0
glassfish-4.0-java-7-(preconfigured-docker)
glassfish-4.1-java-8-(preconfigured-docker)
go-1.3-(preconfigured-docker)
go-1.4-(preconfigured-docker)
iis-7.5
iis-8
iis-8.5
multi-container-docker-1.3.3-(generic)
node.js
php-5.3
php-5.4
php-5.5
python
python-2.7
python-3.4
python-3.4-(preconfigured-docker)
ruby-1.9.3
ruby-2.0-(passenger-standalone)
ruby-2.0-(puma)
ruby-2.1-(passenger-standalone)
ruby-2.1-(puma)
ruby-2.2-(passenger-standalone)
ruby-2.2-(puma)
tomcat-6
tomcat-7
tomcat-7-java-6
tomcat-7-java-7
tomcat-8-java-8
Example 2
The following example prompts you to choose from a list of platforms and the version that you want to
deploy for the specified platform.
$ eb platform select
1032
AWS Elastic Beanstalk Developer Guide
eb printenv
Select a platform.
1) PHP
2) Node.js
3) IIS
4) Tomcat
5) Python
6) Ruby
7) Docker
8) Multi-container Docker
9) GlassFish
10) Go
(default is 1): 5
Example 3
The following example shows information about the current default platform.
$ eb platform show
Current default platform: Python 2.7
New environments will be running: 64bit Amazon Linux 2014.09 v1.2.0 running Python 2.7
eb printenv
Description
Prints all the environment properties in the command window.
Syntax
eb printenv
eb printenv environment-name
Options
Name Description
Output
If successful, the command returns the status of the printenv operation.
Example
The following example prints environment properties for the specified environment.
1033
AWS Elastic Beanstalk Developer Guide
eb restore
$ eb printenv
Environment Variables:
PARAM1 = Value1
eb restore
Description
Rebuilds a terminated environment, creating a new environment with the same name, ID, and
configuration. The environment name, domain name, and application version must be available for use
in order for the rebuild to succeed.
Syntax
eb restore
eb restore environment_id
Options
Name Description
Output
The EB CLI displays a list of terminated environments that are available to restore.
Example
$ eb restore
Select a terminated environment to restore
1034
AWS Elastic Beanstalk Developer Guide
eb scale
eb scale
Description
Scales the environment to always run on a specified number of instances, setting both the minimum and
maximum number of instances to the specified number.
Syntax
eb scale number-of-instances
Options
Name Description
Output
If successful, the command updates the number of minimum and maximum instances to run to the
specified number.
Example
The following example sets the number of instances to 2.
$ eb scale 2
2018-07-11 21:05:22 INFO: Environment update is starting.
2018-07-11 21:05:27 INFO: Updating environment tmp-dev's configuration settings.
2018-07-11 21:08:53 INFO: Added EC2 instance 'i-5fce3d53' to Auto Scaling Group 'awseb-
e-2cpfjbra9a-stack-AWSEBAutoScalingGroup-7AXY7U13ZQ6E'.
2018-07-11 21:08:58 INFO: Successfully deployed new configuration to environment.
2018-07-11 21:08:59 INFO: Environment update completed successfully.
eb setenv
Description
Sets environment properties (p. 590) for the default environment.
Syntax
eb setenv key=value
You can include as many properties as you want, but the total size of all properties cannot exceed
4096 bytes. You can delete a variable by leaving the value blank. See Configuring environment
properties (p. 592) for limits.
1035
AWS Elastic Beanstalk Developer Guide
eb ssh
Note
If the value contains a special character, you must escape that character by preceding it with a
\ character.
Options
Name Description
Output
If successful, the command displays that the environment update succeeded.
Example
The following example sets the environment variable ExampleVar.
$ eb setenv ExampleVar=ExampleValue
2018-07-11 21:05:25 INFO: Environment update is starting.
2018-07-11 21:05:29 INFO: Updating environment tmp-dev's configuration settings.
2018-07-11 21:06:50 INFO: Successfully deployed new configuration to environment.
2018-07-11 21:06:51 INFO: Environment update completed successfully.
The following command sets multiple environment properties. It adds the environment property named
foo and sets its value to bar, changes the value of the JDBC_CONNECTION_STRING property, and
deletes the PARAM4 and PARAM5 properties.
eb ssh
Description
Note
This command does not work with environments running Windows Server instances.
Connect to a Linux Amazon EC2 instance in your environment using Secure Shell (SSH). If an
environment has multiple running instances, EB CLI prompts you to specify which instance you want to
connect to. To use this command, SSH must be installed on your local machine and available from the
command line. Private key files must be located in a folder named .ssh under your user directory, and
the EC2 instances in your environment must have public IP addresses.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
connects to instances in the custom environment.
SSH keys
If you have not previously configured SSH, you can use the EB CLI to create a key when running
eb init. If you have already run eb init, run it again with the --interactive option and select
Yes and Create New Keypair when prompted to set up SSH. Keys created during this process
will be stored in the proper folder by the EB CLI.
1036
AWS Elastic Beanstalk Developer Guide
eb ssh
This command temporarily opens port 22 in your environment's security group for incoming traffic
from 0.0.0.0/0 (all IP addresses) if no rules for port 22 are already in place. If you have configured your
environment's security group to open port 22 to a restricted CIDR range for increased security, the EB CLI
will respect that setting and forgo any changes to the security group. To override this behavior and force
the EB CLI to open port 22 to all incoming traffic, use the --force option.
See Security groups (p. 503) for information on configuring your environment's security group.
Syntax
eb ssh
eb ssh environment-name
Options
Name Description
--instance
or
--number
-o Leave port 22 open on the security group after the SSH session
ends.
or
--keep_open
--timeout minutes Set number of minutes before the command times out.
1037
AWS Elastic Beanstalk Developer Guide
eb status
Output
If successful, the command opens an SSH connection to the instance.
Example
The following example connects you to the specified environment.
$ eb ssh
Select an instance to ssh into
1) i-96133799
2) i-5931e053
(default is 1): 1
INFO: Attempting to open port 22.
INFO: SSH port 22 open.
The authenticity of host '54.191.45.125 (54.191.45.125)' can't be established.
RSA key fingerprint is ee:69:62:df:90:f7:63:af:52:7c:80:60:1b:3b:51:a9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '54.191.45.125' (RSA) to the list of known hosts.
__| __|_ )
_| ( / Amazon Linux AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-ami/2014.09-release-notes/
No packages needed for security; 1 packages available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-31-8-185 ~]$ ls
[ec2-user@ip-172-31-8-185 ~]$ exit
logout
Connection to 54.191.45.125 closed.
INFO: Closed port 22 on ec2 instance security group
eb status
Description
Provides information about the status of the environment.
If the root directory contains a platform.yaml file specifying a custom platform, this command also
provides information about the builder environment.
Syntax
eb status
eb status environment-name
Options
Name Description
--verbose
1038
AWS Elastic Beanstalk Developer Guide
eb swap
Name Description
Output
If successful, the command returns the following information about the environment:
• Environment name
• Application name
• Deployed application version
• Environment ID
• Platform
• Environment tier
• CNAME
• Time the environment was last updated
• Status
• Health
If you use verbose mode, EB CLI also provides you with the number of running Amazon EC2 instances.
Example
The following example shows the status for the environment tmp-dev.
$ eb status
Environment details for: tmp-dev
Application name: tmp
Region: us-west-2
Deployed Version: None
Environment ID: e-2cpfjbra9a
Platform: 64bit Amazon Linux 2014.09 v1.0.9 running PHP 5.5
Tier: WebServer-Standard-1.0
CNAME: tmp-dev.elasticbeanstalk.com
Updated: 2014-10-29 21:37:19.050000+00:00
Status: Launching
Health: Grey
eb swap
Description
Swaps the environment's CNAME with the CNAME of another environment (for example, to avoid
downtime when you update your application version).
Note
If you have more than two environments, you are prompted to select the name of the
environment that is currently using your desired CNAME from a list of environments. To
suppress this, you can specify the name of the environment to use by including the -n option
when you run the command.
Syntax
eb swap
1039
AWS Elastic Beanstalk Developer Guide
eb tags
eb swap environment-name
Note
The environment-name is the environment for which you want a different CNAME. If you
don't specify environment-name as a command line parameter when you run eb swap, EB CLI
updates the CNAME of the default environment.
Options
Name Description
Output
If successful, the command returns the status of the swap operation.
Examples
The following example swaps the environment tmp-dev with live-env.
$ eb swap
Select an environment to swap with.
1) staging-dev
2) live-env
(default is 1): 2
2018-07-11 21:05:25 INFO: swapEnvironmentCNAMEs is starting.
2018-07-11 21:05:26 INFO: Swapping CNAMEs for environments 'tmp-dev' and 'live-env'.
2018-07-11 21:05:30 INFO: 'tmp-dev.elasticbeanstalk.com' now points to 'awseb-e-j-
AWSEBLoa-M7U21VXNLWHN-487871449.us-west-2.elb.amazonaws.com'.
2018-07-11 21:05:30 INFO: Completed swapping CNAMEs for environments 'tmp-dev' and
'live-env'.
The following example swaps the environment tmp-dev with the environment live-env but does not
prompt you to enter or select a value for any settings.
eb tags
Description
Add, delete, update, and list tags of an Elastic Beanstalk resource.
1040
AWS Elastic Beanstalk Developer Guide
eb tags
For details about resource tagging in Elastic Beanstalk, see Tagging Elastic Beanstalk application
resources (p. 392).
Syntax
eb tags [environment-name] [--resource ARN] -l | --list
You can combine the --add, --update, and --delete subcommand options in a single command. At
least one of them is required. You can't combined any of these three subcommand options with --list.
Without any additional arguments, all of these commands list or modify tags of the default environment
in the current directory's application. With an environment-name argument, the commands list or
modify tags of that environment. With the --resource option, the commands list or modify tags
of any Elastic Beanstalk resource – an application, an environment, an application version, a saved
configuration, or a custom platform version. Specify the resource by its Amazon Resource Name (ARN).
Options
None of these options are required. If you run eb create without any options, you are prompted to enter
or select a value for each setting.
Name Description
or
--list
--region region
1041
AWS Elastic Beanstalk Developer Guide
eb tags
Name Description
For the list of values you can specify for this option, see AWS
Elastic Beanstalk Endpoints and Quotas in the AWS General
Reference.
Output
The --list subcommand option displays a list of the resource's tags. The output shows both the tags
that Elastic Beanstalk applies by default and your custom tags.
$ eb tags --list
Showing tags for environment 'MyApp-env':
Key Value
Name MyApp-env
elasticbeanstalk:environment-id e-63cmxwjaut
elasticbeanstalk:environment-name MyApp-env
mytag tagvalue
tag2 2nd value
The --add, --update, and --delete subcommand options, when successful, don't have any output.
You can add the --verbose option to see detailed output of the command's activity.
Key Value
Examples
The following command successfully adds a tag with the key tag1 and the value value1 to the
application's default environment, and at the same time deletes the tag tag2.
The following command successfully adds a tag to a saved configuration within an application.
1042
AWS Elastic Beanstalk Developer Guide
eb terminate
tag3
The following command fails because it tries to update and delete the same key.
eb terminate
Description
Terminates the running environment so that you don't incur charges for unused AWS resources.
Using the --all option, deletes the application that the current directory was initialized to using eb
init (p. 1017). The command terminates all environments in the application. It also terminates the
application versions (p. 380) and saved configurations (p. 721) for the application, and then deletes the
application.
If the root directory contains a platform.yaml file specifying a custom platform, this command
terminates the running custom environment.
Note
You can always launch a new environment using the same version later. If you have data from
an environment that you want to preserve, set the database deletion policy to Retain before
terminating the environment. This keeps the database operational outside of Elastic Beanstalk.
After this, any Elastic Beanstalk environments must connect to it as an external database. If you
want to back up the data without keeping the database operational, set the deletion policy to
take a snapshot of the database before terminating the environment. For more information, see
Database lifecycle (p. 578) in the Configuring environments chapter of this guide.
Syntax
eb terminate
eb terminate environment-name
Options
Name Description
1043
AWS Elastic Beanstalk Developer Guide
eb upgrade
Name Description
Output
If successful, the command returns the status of the terminate operation.
Example
The following example request terminates the environment tmp-dev.
$ eb terminate
The environment "tmp-dev" and all associated instances will be terminated.
To confirm, type the environment name: tmp-dev
2018-07-11 21:05:25 INFO: terminateEnvironment is starting.
2018-07-11 21:05:40 INFO: Deleted CloudWatch alarm named: awseb-e-2cpfjbra9a-stack-
AWSEBCloudwatchAlarmHigh-16V08YOF2KQ7U
2018-07-11 21:05:41 INFO: Deleted CloudWatch alarm named: awseb-e-2cpfjbra9a-stack-
AWSEBCloudwatchAlarmLow-6ZAWH9F20P7C
2018-07-11 21:06:42 INFO: Deleted Auto Scaling group policy named:
arn:aws:autoscaling:us-east-2:11122223333:scalingPolicy:5d7d3e6b-
d59b-47c5-b102-3e11fe3047be:autoScalingGroupName/awseb-e-2cpfjbra9a-stack-
AWSEBAutoScalingGroup-7AXY7U13ZQ6E:policyName/awseb-e-2cpfjbra9a-stack-AWSEBAutoSca
lingScaleUpPolicy-1876U27JEC34J
2018-07-11 21:06:43 INFO: Deleted Auto Scaling group policy named:
arn:aws:autoscaling:us-east-2:11122223333:scalingPolicy:29c6e7c7-7ac8-46fc-91f5-
cfabb65b985b:autoScalingGroupName/awseb-e-2cpfjbra9a-stack-
AWSEBAutoScalingGroup-7AXY7U13ZQ6E:policyName/awseb-e-2cpfjbra9a-stack-AWSEBAutoSca
lingScaleDownPolicy-SL4LHODMOMU
2018-07-11 21:06:48 INFO: Waiting for EC2 instances to terminate. This may take a few
minutes.
2018-07-11 21:08:55 INFO: Deleted Auto Scaling group named: awseb-e-2cpfjbra9a-stack-
AWSEBAutoScalingGroup-7AXY7U13ZQ6E
2018-07-11 21:09:10 INFO: Deleted security group named: awseb-e-2cpfjbra9a-stack-
AWSEBSecurityGroup-XT4YYGFL7I99
2018-07-11 21:09:40 INFO: Deleted load balancer named: awseb-e-2-AWSEBLoa-AK6RRYFQVV3S
2018-07-11 21:09:42 INFO: Deleting SNS topic for environment tmp-dev.
2018-07-11 21:09:52 INFO: terminateEnvironment completed successfully.
eb upgrade
Description
Upgrades the platform of your environment to the most recent version of the platform on which it is
currently running.
If the root directory contains a platform.yaml file specifying a custom platform, this command
upgrades the environment to the most recent version of the custom platform on which it is currently
running.
Syntax
eb upgrade
eb upgrade environment-name
1044
AWS Elastic Beanstalk Developer Guide
eb use
Options
Name Description
--noroll Updates all instances without using rolling updates to keep some
instances in service during the upgrade.
Output
The command shows an overview of the change and prompts you to confirm the upgrade by typing the
environment name. If successful, your environment is updated and then launched with the most recent
version of the platform.
Example
The following example upgrades the current platform version of the specified environment to the most
recently available platform version.
$ eb upgrade
Current platform: 64bit Amazon Linux 2014.09 v1.0.9 running Python 2.7
Latest platform: 64bit Amazon Linux 2014.09 v1.2.0 running Python 2.7
WARNING: This operation replaces your instances with minimal or zero downtime. You may
cancel the upgrade after it has started by typing "eb abort".
You can also change your platform version by typing "eb clone" and then "eb swap".
eb use
Description
Sets the specified environment as the default environment.
When using Git, eb use sets the default environment for the current branch. Run this command once in
each branch that you want to deploy to Elastic Beanstalk.
Syntax
eb use environment-name
Options
Name Description
--source CodeCommit repository and branch. See Using the EB CLI with AWS
codecommit/repository- CodeCommit (p. 975).
name/branch-name
1045
AWS Elastic Beanstalk Developer Guide
Common options
Name Description
--region region
Common options
You can use the following options with all EB CLI commands.
Name Description
Type: String
Default: None
--no-verify-ssl Skip SSL certificate verification. Use this option if you have issues
using the CLI with a proxy.
You should migrate to the latest version of EB CLI 3. It can manage environments that you launched
using EB CLI 2.6 or earlier versions of EB CLI.
EB CLI introduces the commands eb create, eb deploy, eb open, eb console, eb scale, eb setenv, eb
config, eb terminate, eb clone, eb list, eb use, eb printenv, and eb ssh. In EB CLI 3.1 or later, you can
also use the eb swap command. In EB CLI 3.2 only, you can use the eb abort, eb platform, and eb
upgrade commands. In addition to these new commands, EB CLI 3 commands differ from EB CLI 2.6
commands in several cases:
1046
AWS Elastic Beanstalk Developer Guide
Migrating to EB CLI 3 and CodeCommit
• eb init – Use eb init to create an .elasticbeanstalk directory in an existing project directory and
create a new Elastic Beanstalk application for the project. Unlike with previous versions, EB CLI 3 and
later versions do not prompt you to create an environment.
• eb start – EB CLI 3 does not include the command eb start. Use eb create to create an environment.
• eb stop – EB CLI 3 does not include the command eb stop. Use eb terminate to completely terminate
an environment and clean up.
• eb push and git aws.push – EB CLI 3 does not include the commands eb push or git aws.push.
Use eb deploy to update your application code.
• eb update – EB CLI 3 does not include the command eb update. Use eb config to update an
environment.
• eb branch – EB CLI 3 does not include the command eb branch.
For more information about using EB CLI 3 commands to create and manage an application, see EB CLI
command reference (p. 989). For a walkthrough of how to deploy a sample application using EB CLI 3,
see Managing Elastic Beanstalk environments with the EB CLI (p. 968).
If you have not done so already, create a code repository in CodeCommit, as described in Migrate to
CodeCommit.
Once you have installed (p. 957) and configured (p. 964) EB CLI, you have two opportunities to
associate your application with your CodeCommit repository, including a specific branch.
• When executing eb init, such in the following example where myRepo is the name of your
CodeCommit repository and myBranch is the branch in CodeCommit.
• When executing eb deploy, such in the following example where myRepo is the name of your
CodeCommit repository and myBranch is the branch in CodeCommit.
For further information, including how to deploy incremental code updates to an Elastic Beanstalk
environment without having to re-upload your entire project, see Using the EB CLI with AWS
CodeCommit (p. 975).
1047
AWS Elastic Beanstalk Developer Guide
Converting Elastic Beanstalk API CLI scripts
Elastic Beanstalk API CLI AWS CLI AWS Tools for Windows
PowerShell
1048
AWS Elastic Beanstalk Developer Guide
Converting Elastic Beanstalk API CLI scripts
Elastic Beanstalk API CLI AWS CLI AWS Tools for Windows
PowerShell
configuration-
settings
1049
AWS Elastic Beanstalk Developer Guide
Data protection
Security is a shared responsibility between AWS and you. The Shared Responsibility Model describes this
as Security of the Cloud and Security in the Cloud.
Security of the Cloud – AWS is responsible for protecting the infrastructure that runs all of the services
offered in the AWS Cloud and providing you with services that you can use securely. Our security
responsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested and
verified by third-party auditors as part of the AWS Compliance Programs. Review the AWS Services in
Scope of AWS assurance programs for information as it relates to Elastic Beanstalk.
Security in the Cloud – Your responsibility is determined by the AWS service you are using, and other
factors including the sensitivity of your data, your organization’s requirements, and applicable laws
and regulations. This documentation is intended to help you understand how to apply the Shared
Responsibility Model when using Elastic Beanstalk.
Use the following security topics to learn more about the security tasks Elastic Beanstalk is responsible
for, and the security configurations you should consider when using Elastic Beanstalk to meet your
security and compliance objectives.
Topics
• Data protection in Elastic Beanstalk (p. 1050)
• Identity and access management for Elastic Beanstalk (p. 1052)
• Logging and monitoring in Elastic Beanstalk (p. 1055)
• Compliance validation for Elastic Beanstalk (p. 1056)
• Resilience in Elastic Beanstalk (p. 1057)
• Infrastructure security in Elastic Beanstalk (p. 1057)
• Configuration and vulnerability analysis in Elastic Beanstalk (p. 1058)
• Security best practices for Elastic Beanstalk (p. 1058)
For data protection purposes, we recommend that you protect AWS account credentials and set up
individual user accounts with AWS Identity and Access Management (IAM). That way each user is given
only the permissions necessary to fulfill their job duties. We also recommend that you secure your data
in the following ways:
1050
AWS Elastic Beanstalk Developer Guide
Data encryption
• Use advanced managed security services such as Amazon Macie, which assists in discovering and
securing personal data that is stored in Amazon S3.
• If you require FIPS 140-2 validated cryptographic modules when accessing AWS through a command
line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints,
see Federal Information Processing Standard (FIPS) 140-2.
We strongly recommend that you never put confidential or sensitive information, such as your
customers' email addresses, into tags or free-form fields such as a Name field. This includes when you
work with Elastic Beanstalk or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any
data that you enter into tags or free-form fields used for names may be used for billing or diagnostic
logs. If you provide a URL to an external server, we strongly recommend that you do not include
credentials information in the URL to validate your request to that server.
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
Topics
• Protecting data using encryption (p. 1051)
• Internetwork traffic privacy (p. 1052)
You provide some of the stored objects and send them to Elastic Beanstalk, for example, application
versions and source bundles. Elastic Beanstalk generates other objects, for example, log files. In addition
to the data that Elastic Beanstalk stores, your application can transfer and/or store data as part of its
operation.
Data protection refers to protecting data while in transit (as it travels to and from Elastic Beanstalk) and
at rest (while it is stored in AWS data centers).
Encryption in transit
You can achieve data protection in transit in two ways: encrypt the connection using Secure Sockets
Layer (SSL), or use client-side encryption (where the object is encrypted before it is sent). Both
methods are valid for protecting your application data. To secure the connection, encrypt it using SSL
whenever your application, its developers and administrators, and its end users send or receive any
objects. For details about encrypting web traffic to and from your application, see the section called
“HTTPS” (p. 734).
Client-side encryption isn't a valid method for protecting your source code in application versions
and source bundles that you upload. Elastic Beanstalk needs access to these objects, so they can't be
encrypted. Therefore, be sure to secure the connection between your development or deployment
environment and Elastic Beanstalk.
Encryption at rest
To protect your application's data at rest, learn about data protection in the storage service that your
application uses. For example, see Data Protection in Amazon RDS in the Amazon RDS User Guide, Data
Protection in Amazon S3 in the Amazon Simple Storage Service User Guide, or Encrypting Data and
Metadata in EFS in the Amazon Elastic File System User Guide.
Elastic Beanstalk doesn't turn on default encryption for the Amazon S3 bucket that it creates. This means
that by default, objects are stored unencrypted in the bucket (and are accessible only by users authorized
1051
AWS Elastic Beanstalk Developer Guide
Internetwork privacy
to read the bucket). If your application requires encryption at rest, you can configure your account's
buckets for default encryption. For more information, see Amazon S3 Default Encryption for S3 Buckets
in the Amazon Simple Storage Service User Guide.
For more information about data protection, see the AWS Shared Responsibility Model and GDPR blog
post on the AWS Security Blog.
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
For more information about Amazon VPC security, see Security in the Amazon VPC User Guide.
For more information about data protection, see the AWS Shared Responsibility Model and GDPR blog
post on the AWS Security Blog.
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
For details on working with IAM, see Using Elastic Beanstalk with AWS Identity and Access
Management (p. 854).
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write
policies yourself. It takes time and expertise to create IAM customer managed policies that provide your
team with only the permissions they need. To get started quickly, you can use our AWS managed policies.
These policies cover common use cases and are available in your AWS account. For more information
about AWS managed policies, see AWS managed policies in the IAM User Guide.
AWS services maintain and update AWS managed policies. You can't change the permissions in AWS
managed policies. Services occasionally add additional permissions to an AWS managed policy to
support new features. This type of update affects all identities (users, groups, and roles) where the policy
is attached. Services are most likely to update an AWS managed policy when a new feature is launched
or when new operations become available. Services do not remove permissions from an AWS managed
policy, so policy updates won't break your existing permissions.
Additionally, AWS supports managed policies for job functions that span multiple services. For example,
the ViewOnlyAccess AWS managed policy provides read-only access to many AWS services and
resources. When a service launches a new feature, AWS adds read-only permissions for new operations
and resources. For a list and descriptions of job function policies, see AWS managed policies for job
functions in the IAM User Guide.
1052
AWS Elastic Beanstalk Developer Guide
AWS managed policies
AWSElasticBeanstalkReadOnlyAccess
This policy has been replaced by June 17, 2021
– Deprecated AWSElasticBeanstalkReadOnly.
AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
This policy was updated to June 16, 2021
–Updated allow Elastic Beanstalk to read
attributes for EC2 Availability
Zones. It enables Elastic
Beanstalk to provide more
effective validation of your
instance type selection across
Availability Zones.
1053
AWS Elastic Beanstalk Developer Guide
AWS managed policies
1054
AWS Elastic Beanstalk Developer Guide
Logging and monitoring
The following managed policies Both of these policies now March 9, 2021
were updated: support PassRole permissions in
China AWS Regions.
• AdministratorAccess-
AWSElasticBeanstalk For more information about
AdministratorAccess-
• AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
AWSElasticBeanstalk, see
User policies (p. 879).
AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
Elastic Beanstalk added a March 3, 2021
– New policy new policy to replace the
AWSElasticBeanstalkService
managed policy.
For more information about monitoring, see Monitoring an environment (p. 770).
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
1055
AWS Elastic Beanstalk Developer Guide
Amazon EC2 instance logs
Environment notifications
You can configure your Elastic Beanstalk environment to use Amazon Simple Notification Service
(Amazon SNS) to notify you of important events that affect your application. Specify an email address
during or after environment creation to receive emails from AWS when an error occurs, or when your
environment's health changes. For more information, see Elastic Beanstalk environment notifications
with Amazon SNS (p. 600).
Third-party audit reports are available for you to download using AWS Artifact. For more information,
see Downloading Reports in AWS Artifact.
For more information about AWS compliance programs, see AWS Compliance Programs.
1056
AWS Elastic Beanstalk Developer Guide
Resilience
Your compliance responsibility when using Elastic Beanstalk is determined by the sensitivity of your
data, your organization’s compliance objectives, and applicable laws and regulations. If your use of
Elastic Beanstalk is subject to compliance with standards such as HIPAA, PCI, or FedRAMP, AWS provides
resources to help:
• Security and Compliance Quick Start Guides – Deployment guides that discuss architectural
considerations and provide steps for deploying security-focused and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – A whitepaper that describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – A collection of compliance workbooks and guides that might apply to
your industry and location.
• AWS Config – A service that assesses how well your resource configurations comply with internal
practices, industry guidelines, and regulations.
• AWS Security Hub – A comprehensive view of your security state within AWS that helps you check your
compliance with security industry standards and best practices.
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected
with low-latency, high-throughput, and highly redundant networking.
With Availability Zones, you can design and operate applications and databases that automatically fail
over between Availability Zones without interruption. Availability Zones are more highly available, fault
tolerant, and scalable than traditional single or multiple data center infrastructures.
For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.
AWS Elastic Beanstalk manages and automates the use of the AWS global infrastructure on your behalf.
When using Elastic Beanstalk, you benefit from the availability and fault tolerance mechanisms that AWS
offers.
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
You use AWS published API calls to access Elastic Beanstalk through the network. Clients must support
Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must also support
cipher suites with perfect forward secrecy (PFS), such as Ephemeral Diffie-Hellman (DHE) or Elliptic
Curve Ephemeral Diffie-Hellman (ECDHE). Most modern platforms such as Java 7 and later support these
modes.
Additionally, requests must be signed by using an access key ID and a secret access key that is associated
with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary
security credentials to sign requests.
1057
AWS Elastic Beanstalk Developer Guide
Shared responsibility model
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
For more information, see Shared responsibility model for Elastic Beanstalk platform
maintenance (p. 26).
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
For other Elastic Beanstalk security topics, see AWS Elastic Beanstalk security (p. 1050).
Your application might not require all the permissions in our managed policies. You can customize
them and grant only the permissions that are required for your environment's instances, the Elastic
Beanstalk service, and your users to perform their tasks. This is particularly relevant to user policies,
where different user roles might have different permission needs. Implementing least privilege access is
fundamental in reducing security risk and the impact that could result from errors or malicious intent.
The easiest way to keep your environment's platform up to date is to configure the environment to use
managed platform updates (p. 464).
1058
AWS Elastic Beanstalk Developer Guide
Detective security best practices
IMDSv2 is more secure, so it's a good idea to enforce the use of IMDSv2 on your instances. To enforce
IMDSv2, ensure that all components of your application support IMDSv2, and then disable IMDSv1. For
more information, see the section called “IMDS” (p. 509).
Implement monitoring
Monitoring is an important part of maintaining the reliability, security, availability, and performance of
your Elastic Beanstalk solutions. AWS provides several tools and services to help you monitor your AWS
services.
• Amazon CloudWatch metrics for Elastic Beanstalk – Set alarms for key Elastic Beanstalk metrics
and for your application's custom metrics. For details, see Using Elastic Beanstalk with Amazon
CloudWatch (p. 830).
• AWS CloudTrail entries – Track actions that might impact availability, like UpdateEnvironment
or TerminateEnvironment. For details, see Logging Elastic Beanstalk API calls with AWS
CloudTrail (p. 829).
You can use AWS Config to define rules that evaluate resource configurations for data compliance.
AWS Config rules represent the ideal configuration settings for your Elastic Beanstalk resources. If a
resource violates a rule and is flagged as noncompliant, AWS Config can alert you using an Amazon
Simple Notification Service (Amazon SNS) topic. For details, see Finding and tracking Elastic Beanstalk
resources with AWS Config (p. 847).
1059
AWS Elastic Beanstalk Developer Guide
Connectivity
Troubleshooting
This chapter provides a table of the most common Elastic Beanstalk issues and describes how to resolve
or work around them. Error messages can appear as events on the environment management page in the
console, in logs, or on the health page.
• Review recent environment events (p. 816). Messages from Elastic Beanstalk about deployment, load,
and configuration issues often appear here.
• Review recent environment change history (p. 814). Change history lists all of the configuration
changes made to your environments and includes other information, such as which IAM user made
changes and which configuration parameters were set.
• Pull logs (p. 820) to view recent log file entries. Web server logs contain information about incoming
requests and errors.
• Connect to an instance (p. 818) and check system resources.
• Roll back (p. 441) to a previous working version of the application.
• Undo recent configuration changes or restore a saved configuration (p. 617).
• Deploy a new environment. If the environment appears healthy, perform a CNAME swap (p. 449) to
route traffic to the new environment and continue to debug the earlier one.
Topics
• Connectivity (p. 1060)
• Environment creation and instance launches (p. 1061)
• Deployments (p. 1061)
• Health (p. 1061)
• Configuration (p. 1062)
• Troubleshooting Docker containers (p. 1062)
• FAQ (p. 1063)
Connectivity
Issue: Unable to connect to Amazon RDS from Elastic Beanstalk.
• Make sure RDS is in the same Region as your Elastic Beanstalk application.
• Make sure the RDS security group for your instance has an authorization for the Amazon EC2 security
group you are using for your Elastic Beanstalk environment. For instructions on how to find the name
of your EC2 security group using the AWS Management Console, see Security groups (p. 503). For more
information about configuring your EC2 security group, go to the "Authorizing Network Access to an
Amazon EC2 Security Group" section of Working with DB Security Groups in the Amazon Relational
Database Service User Guide.
• For Java, make sure the MySQL JAR file is in your WEB-INF/lib. See Adding an Amazon RDS DB instance
to your Java application environment (p. 132) for more details.
Issue: Servers that were created in the Elastic Beanstalk console do not appear in the Toolkit for Eclipse
1060
AWS Elastic Beanstalk Developer Guide
Environment creation
You can manually import servers by following the instructions at Importing existing environments into
Eclipse (p. 138).
This event occurs when Elastic Beanstalk attempts to launch an environment and encounters failures
along the way. Previous events on the Events page will alert you to the root cause of this issue.
Event: Create environment operation is complete, but with command timeouts. Try increasing the timeout
period.
Your application may take a long time to deploy if you use configuration files that run commands on the
instance, download large files, or install packages. Increase the command timeout (p. 445) to give your
application more time to start running during deployments.
This message indicates that your environment's Amazon EC2 instances did not communicate to Elastic
Beanstalk that they were launched successfully. This can occur if the instances do not have Internet
connectivity. If you configured your environment to launch instances in a private VPC subnet, ensure that
the subnet has a NAT (p. 938) to allow the instances to connect to Elastic Beanstalk.
Event: A Service Role is required in this region. Please add a Service Role option to the environment.
Elastic Beanstalk uses a service role to monitor the resources in your environment and support managed
platform updates (p. 464). See Managing Elastic Beanstalk service roles (p. 860) for more information.
Deployments
Issue: Application becomes unavailable during deployments
Because Elastic Beanstalk uses a drop-in upgrade process, there might be a few seconds of downtime.
Use rolling deployments (p. 444) to minimize the effect of deployments on your production
environments.
Your application source bundle may be too large, or you may have reached the application version
quota (p. 380).
Event: Update environment operation is complete, but with command timeouts. Try increasing the timeout
period.
Your application may take a long time to deploy if you use configuration files that run commands on the
instance, download large files, or install packages. Increase the command timeout (p. 445) to give your
application more time to start running during deployments.
Health
Event: CPU Utilization Exceeds 95.00%
Try running more instances (p. 511), or choose a different instance type (p. 497).
1061
AWS Elastic Beanstalk Developer Guide
Configuration
If your application appears to be working, make sure that your application’s health check URL is
configured correctly. If not, check the Health screen and environment logs for more information.
Your environment's load balancer may have been removed out-of-band. Only make changes to your
environment's resources with the configuration options and extensibility (p. 683) provided by Elastic
Beanstalk. Rebuild your environment or launch a new one.
Event: EC2 Instance Launch Failure. Waiting for a New EC2 Instance to Launch...
Availability for your environment's instance type may be low, or you may have reached the instance
quota for your account. Check the service health dashboard to ensure that the Elastic Compute Cloud
(Amazon EC2) service is green, or request a quota increase.
Configuration
Event: You cannot configure an Elastic Beanstalk environment with values for both the Elastic Load
Balancing Target option and Application Healthcheck URL option
The Target option in the aws:elb:healthcheck namespace is deprecated. Remove the Target
option namespace) from your environment and try updating again.
This message can be seen if you try to move a load balancer between subnets in the same Availability
Zone. Changing subnets on the load balancer requires moving it out of the original availability zone(s)
and then back into the original with the desired subnets. During the process, all of your instances will be
migrated between AZs, causing significant downtime. Instead, consider creating a new environment and
perform a CNAME swap (p. 449).
Check the syntax of the dockerrun.aws.json file using a JSON validator. Also verify the dockerfile
contents against the requirements described in Docker configuration (p. 58)
The Dockerfile or the dockerrun.aws.json file does not declare the container port. Use the
EXPOSE instruction (Dockerfile) or Ports block (dockerrun.aws.json file) to expose a port for
incoming traffic.
The dockerrun.aws.json provides an invalid EC2 key pair and/or S3 bucket for the .dockercfg
file. Or, the instance profile does not have GetObject authorization for the S3 bucket. Verify that
the .dockercfg file contains a valid S3 bucket and EC2 key pair. Grant permissions for the action
s3:GetObject to the IAM role in the instance profile. For details, go to Managing Elastic Beanstalk
instance profiles (p. 855)
Event: Activity execution failed, because: WARNING: Invalid auth configuration file
1062
AWS Elastic Beanstalk Developer Guide
FAQ
Your authentication file (config.json) is not formatted correctly. See Using images from a private
repository (p. 95)
FAQ
Question: How can I change my application URL from myapp.us-west-2.elasticbeanstalk.com to
www.myapp.com?
Question: How do I specify a specific Availability Zone for my Elastic Beanstalk application?
You can pick a specific Availability Zone by using the APIs, CLI, Eclipse plugin, or Visual Studio plugin. For
instructions about using the Elastic Beanstalk console to specify an Availability Zone, see Auto Scaling
group for your Elastic Beanstalk environment (p. 511).
To change your environment's instance type go to the environment configuration page and choose Edit
in the Instances configuration category. Then, select a new instance type and choose Apply to update
your environment. After this, Elastic Beanstalk terminates all running instances and replaces them with
new ones.
To see this information, in the navigation pane of the Elastic Beanstalk console choose Change history
to display a list of configuration changes for all environments. This list includes the date and time of
the change, the configuration parameter and value it was changed to, and the IAM user that made the
change. For more information, see Change history (p. 814).
Question: Can I prevent Amazon EBS volumes from being deleted when instances are terminated?
Instances in your environment use Amazon EBS for storage; however, the root volume is deleted when
an instance is terminated by Auto Scaling. We don'trecommend that you store state or other data on
your instances. If needed, you can prevent volumes from being deleted with the AWS CLI: $ aws ec2
modify-instance-attribute -b '/dev/sdc=<vol-id>:false as described in the AWS CLI
Reference.
AWS resources that your Elastic Beanstalk application uses might store personal information. When
you terminate an environment, Elastic Beanstalk terminates the resources that it created. Resources
you added using configuration files (p. 683) are also terminated. However, if you created AWS resources
outside of your Elastic Beanstalk environment and associated them with your application, you might
need to manually check that personal information that your application might have stored isn't retained.
Throughout this developer guide, whenever we discuss creating additional resources, we also mention
when you should consider deleting them.
1063
AWS Elastic Beanstalk Developer Guide
Sample applications
• Elastic Beanstalk API Reference A comprehensive description of all SOAP and Query APIs.
Additionally, it contains a list of all SOAP data types.
• elastic-beanstalk-samples on GitHub – A GitHub repository with Elastic Beanstalk sample
configuration files (.ebextensions). The repository's README.md file has links to additional GitHub
repositories with sample applications.
• Elastic Beanstalk Technical FAQ – The top questions developers have asked about this product.
• AWS Elastic Beanstalk Release Notes – Details about new features, updates, and fixes in Elastic
Beanstalk service, platform, console, and EB CLI releases.
• Classes & Workshops – Links to role-based and specialty courses, in addition to self-paced labs to help
sharpen your AWS skills and gain practical experience.
• AWS Developer Tools – Links to developer tools, SDKs, IDE toolkits, and command line tools for
developing and managing AWS applications.
• AWS Whitepapers – Links to a comprehensive list of technical AWS whitepapers, covering topics such
as architecture, security, and economics and authored by AWS Solutions Architects or other technical
experts.
• AWS Support Center – The hub for creating and managing your AWS Support cases. Also includes
links to other helpful resources, such as forums, technical FAQs, service health status, and AWS Trusted
Advisor.
• AWS Support – The primary webpage for information about AWS Support, a one-on-one, fast-
response support channel to help you build and run applications in the cloud.
• Contact Us – A central contact point for inquiries concerning AWS billing, account, events, abuse, and
other issues.
• AWS Site Terms – Detailed information about our copyright and trademark; your account, license, and
site access; and other topics.
Sample applications
The following are download links to the sample applications that are deployed as part of Getting started
using Elastic Beanstalk (p. 3).
Note
Some samples use features that may have been released since the release of the platform you
are using. If the sample fails to run, try updating your platform to a current version, as described
in the section called “Supported platforms” (p. 29).
• Docker – docker.zip
• Multicontainer Docker – docker-multicontainer-v2.zip
• Preconfigured Docker (Glassfish) – docker-glassfish-v1.zip
• Go – go.zip
• Corretto – corretto.zip
• Tomcat – tomcat.zip
• .NET Core on Linux – dotnet-core-linux.zip
• .NET – dotnet-asp-v1.zip
1064
AWS Elastic Beanstalk Developer Guide
Sample applications
• Node.js – nodejs.zip
• PHP – php.zip
• Python – python.zip
• Ruby – ruby.zip
1065
AWS Elastic Beanstalk Developer Guide
Custom platforms
Platform history
AWS Elastic Beanstalk platform history has moved. See Platform History in the AWS Elastic Beanstalk
Platforms document.
Topics
• Elastic Beanstalk custom platforms (p. 1066)
To create a custom platform, you build an AMI from one of the supported operating systems—Ubuntu,
RHEL, or Amazon Linux (see the flavor entry in Platform.yaml file format (p. 1073) for the exact
version numbers)—and add further customizations. You create your own Elastic Beanstalk platform using
Packer, which is an open-source tool for creating machine images for many platforms, including AMIs for
use with Amazon Elastic Compute Cloud (Amazon EC2). An Elastic Beanstalk platform comprises an AMI
configured to run a set of software that supports an application, and metadata that can include custom
configuration options and default configuration option settings.
Elastic Beanstalk manages Packer as a separate built-in platform, and you don't need to worry about
Packer configuration and versions.
You create a platform by providing Elastic Beanstalk with a Packer template, and the scripts and files
that the template invokes to build an AMI. These components are packaged with a platform definition
file (p. 1067), which specifies the template and metadata, into a ZIP archive, known as a platform
definition archive (p. 1071).
When you create a custom platform, you launch a single instance environment without an Elastic IP that
runs Packer. Packer then launches another instance to build an image. You can reuse this environment for
multiple platforms and multiple versions of each platform.
Note
Custom platforms are AWS Region specific. If you use Elastic Beanstalk in multiple Regions, you
must create your platforms separately in each Region.
In certain circumstances, instances launched by Packer are not cleaned up and have to be
manually terminated. To learn how to manually clean up these instances, see Packer instance
cleanup (p. 1072).
Users in your account can use your custom platforms by specifying a platform ARN (p. 884) during
environment creation. These ARNs are returned by the eb platform create command that you used to
create the custom platform.
1066
AWS Elastic Beanstalk Developer Guide
Creating a custom platform
Each time you build your custom platform, Elastic Beanstalk creates a new platform version. Users can
specify a platform by name to get only the latest version of the platform, or include a version number to
get a specific version.
For example, to deploy the latest version of the custom platform with the ARN MyCustomPlatformARN,
which could be version 3.0, your EB CLI command line would look like this:
eb create -p MyCustomPlatformARN
To deploy version 2.1 your EB CLI command line would look like this:
You can apply tags to a custom platform version when you create it, and edit tags of existing custom
platform versions. For details, see Tagging custom platform versions (p. 1075).
NodePlatform_Ubuntu.zip
This custom platform is based on Ubuntu 16.04 and supports Node.js 4.4.4. We use this custom
platform for the examples in this section.
NodePlatform_RHEL.zip
This custom platform is based on RHEL 7.2 and supports Node.js 4.4.4.
NodePlatform_AmazonLinux.zip
This custom platform is based on Amazon Linux 2016.09.1 and supports Node.js 4.4.4.
TomcatPlatform_Ubuntu.zip
This custom platform is based on Ubuntu 16.04 and supports Tomcat 7/Java 8.
CustomPlatform_NodeSampleApp.zip
A Node.js sample that uses express and ejs to display a static webpage.
CustomPlatform_TomcatSampleApp.zip
Download the sample platform definition archive: NodePlatform_Ubuntu.zip. This file contains a
platform definition file, Packer template, scripts that Packer runs during image creation, and scripts and
configuration files that Packer copies onto the builder instance during platform creation.
1067
AWS Elastic Beanstalk Developer Guide
Using a sample custom platform
Example NodePlatform_Ubuntu.zip
|-- builder Contains files used by Packer to create the custom platform
|-- custom_platform.json Packer template
|-- platform.yaml Platform definition file
|-- ReadMe.txt Briefly describes the sample
The platform definition file, platform.yaml, tells Elastic Beanstalk the name of the Packer template,
custom_platform.json.
version: "1.0"
provisioner:
type: packer
template: custom_platform.json
flavor: ubuntu1604
The Packer template tells Packer how to build the AMIs for the platform, using an Ubuntu AMI as a base
for the platform image for HVM instance types. The provisioners section tells Packer to copy all
files in the builder folder within the archive to the instance, and to run the builder.sh script on the
instance. When the scripts complete, Packer creates an image from the modified instance.
Elastic Beanstalk creates three environment variables that can be used to tag AMIs in Packer:
AWS_EB_PLATFORM_ARN
The sample custom_platform.json file uses these variables to define the following values that it uses
in the scripts:
The custom_platform.json file contains two properties that you have to provide values for:
source_ami and region. For details about choosing the right AMI and Region values, see Updating
Packer template in the eb-custom-platforms-samples GitHub repository.
Example custom_platform.json
{
"variables": {
"platform_name": "{{env `AWS_EB_PLATFORM_NAME`}}",
"platform_version": "{{env `AWS_EB_PLATFORM_VERSION`}}",
"platform_arn": "{{env `AWS_EB_PLATFORM_ARN`}}"
},
"builders": [
1068
AWS Elastic Beanstalk Developer Guide
Using a sample custom platform
{
...
"region": "",
"source_ami": "",
...
}
],
"provisioners": [
{...},
{
"type": "shell",
"execute_command": "chmod +x {{ .Path }}; {{ .Vars }} sudo {{ .Path }}",
"scripts": [
"builder/builder.sh"
]
}
]
}
The scripts and other files that you include in your platform definition archive will vary greatly
depending on the modifications that you want to make to the instance. The sample platform includes
the following scripts:
• 00-sync-apt.sh – Commented out: apt -y update. We commented out the command because
it prompts the user for input, which breaks the automated package update. This might be an Ubuntu
issue. However, running apt -y update is still recommended as a best practice. For this reason, we
left the command in the sample script for reference.
• 01-install-nginx.sh – Installs nginx.
• 02-setup-platform.sh – Installs wget, tree, and git. Copies hooks and logging
configurations (p. 820) to the instance, and creates the following directories:
• /etc/SampleNodePlatform – Where the container configuration file is uploaded during
deployment.
• /opt/elasticbeanstalk/deploy/appsource/ – Where the 00-unzip.sh script uploads
application source code during deployment (see the Platform script tools (p. 42) section for
information about this script).
• /var/app/staging/ – Where application source code is processed during deployment.
• /var/app/current/ – Where application source code runs after processing.
• /var/log/nginx/healthd/ – Where the enhanced health agent (p. 779) writes logs.
• /var/nodejs – Where the Node.js files are uploaded during deployment.
Use the EB CLI to create your first custom platform with the sample platform definition archive.
~$ mkdir ~/custom-platform
3. Extract NodePlatform_Ubuntu.zip to the directory, and then change to the extracted directory.
~$ cd ~/custom-platform
~/custom-platform$ unzip ~/NodePlatform_Ubuntu.zip
~/custom-platform$ cd NodePlatform_Ubuntu
4. Edit the custom_platform.json file, and provide values for the source_ami and region
properties. For details, see Updating Packer template.
1069
AWS Elastic Beanstalk Developer Guide
Using a sample custom platform
5. Run eb platform init (p. 1030) and follow the prompts to initialize a platform repository.
This command also creates the directory .elasticbeanstalk in the current directory and adds
the configuration file config.yml to the directory. Don't change or delete this file, because Elastic
Beanstalk relies on it when creating the custom platform.
By default, eb platform init uses the name of the current folder as the name of the custom
platform, which would be custom-platform in this example.
6. Run eb platform create (p. 1028) to launch a Packer environment and get the ARN of the custom
platform. You'll need this value later when you create an environment from the custom platform.
The EB CLI shows event output of the Packer environment until the build is complete. You can exit
the event view by pressing Ctrl+C.
7. You can check the logs for errors using the eb platform logs (p. 1031) command.
8. You can check on the process later with eb platform events (p. 1029).
9. Check the status of your platform with eb platform status (p. 1031).
When the operation completes, you have a platform that you can use to launch an Elastic Beanstalk
environment.
You can use the custom platform when creating an environment from the console. See The create new
environment wizard (p. 409).
1070
AWS Elastic Beanstalk Developer Guide
Platform definition archive contents
~$ mkdir custom-platform-app
~$ cd ~/custom-platform-app
~/custom-platform-app$ eb init
...
The platform definition file is a YAML-formatted file that must be named platform.yaml and be in the
root of your platform definition archive. See Creating a custom platform (p. 1067) for a list of required
and optional keys supported in a platform definition file.
You don't need to name the Packer template in a specific way, but the name of the file must match the
provisioner template specified in the platform definition file. See the official Packer documentation for
instructions on creating Packer templates.
The other files in your platform definition archive are scripts and files used by the template to customize
an instance before creating an AMI.
Place scripts that you want hooks to trigger in one of the subfolders of the /opt/elasticbeanstalk/
hooks/ folder.
Warning
Using custom platform hooks on managed platforms isn't supported. Custom platform hooks
are designed for custom platforms. On Elastic Beanstalk managed platforms they might work
differently or have some issues, and behavior might differ across platforms. On Amazon Linux
1071
AWS Elastic Beanstalk Developer Guide
Packer instance cleanup
AMI platforms (preceding Amazon Linux 2), they might still work in useful ways in some cases;
use them with caution.
Custom platform hooks are a legacy feature that exists on Amazon Linux AMI platforms. On
Amazon Linux 2 platforms, custom platform hooks in the /opt/elasticbeanstalk/hooks/
folder are entirely discontinued. Elastic Beanstalk doesn't read or execute them. Amazon Linux
2 platforms support a new kind of platform hooks, specifically designed to extend Elastic
Beanstalk managed platforms. You can add custom scripts and programs directly to a hooks
directory in your application source bundle. Elastic Beanstalk runs them during various instance
provisioning stages. For more information, expand the Platform Hooks section in the section
called “Extending Linux platforms” (p. 31).
The appdeploy, configdeploy, and restartappserver folders contain pre, enact, and post
subfolders. In each phase of an operation, all scripts in the pre folder are run in alphabetical order, then
those in the enact folder, and then those in the post folder.
When an instance is launched, Elastic Beanstalk runs preinit, appdeploy, and postinit, in
this order. On subsequent deployments to running instances, Elastic Beanstalk runs appdeploy
hooks. configdeploy hooks are run when a user updates instance software configuration settings.
restartappserver hooks are run only when the user initiates an application server restart.
When your scripts encounter errors, they can exit with a non-zero status and write to stderr to fail
the operation. The message that you write to stderr will appear in the event that is output when
the operation fails. Elastic Beanstalk also captures this information in the log file /var/log/eb-
activity.log If you don't want to fail the operation, return 0 (zero). Messages that you write to
stderr or stdout appear in the deployment logs (p. 820), but won't appear in the event stream unless
the operation fails.
1072
AWS Elastic Beanstalk Developer Guide
Platform.yaml format
version: "version-number"
provisioner:
type: provisioner-type
template: provisioner-template
flavor: provisioner-flavor
metadata:
maintainer: metadata-maintainer
description: metadata-description
operating_system_name: metadata-operating_system_name
operating_system_version: metadata-operating_system_version
programming_language_name: metadata-programming_language_name
programming_language_version: metadata-programming_language_version
framework_name: metadata-framework_name
framework_version: metadata-framework_version
option_definitions:
- namespace: option-def-namespace
option_name: option-def-option_name
description: option-def-description
default_value: option-def-default_value
option_settings:
- namespace: "option-setting-namespace"
option_name: "option-setting-option_name"
value: "option-setting-value"
version-number
Required. The type of builder used to create the custom platform. Must be packer.
provisioner-template
Optional. The base operating system used for the AMI. One of the following:
amazon (default)
Amazon Linux. If not specified, the latest version of Amazon Linux when the platform is created.
1073
AWS Elastic Beanstalk Developer Guide
Platform.yaml format
rhel7
RHEL 7
rhel6
RHEL 6
metadata-maintainer
Optional. Contact information for the person who owns the platform (100 characters).
metadata-description
Optional. Name of the platform's operating system (50 characters). This value is available when
filtering the output for the ListPlatformVersions API.
metadata-operating_system_version
Optional. Name of the web framework used by the platform (50 characters).
metadata-framework_version
Optional. The option's name (100 characters). You can define up to 50 custom configuration options
that the platform provides to users.
option-def-description
Optional. Default value used when the user doesn't specify one.
options_definitions:
- namespace: "aws:elasticbeanstalk:container:custom:application"
option_name: "NPM_START"
description: "Default application startup command"
default_value: "node application.js"
option-setting-namespace
1074
AWS Elastic Beanstalk Developer Guide
Tagging custom platform versions
option-setting-option_name
Optional. Name of the option. You can specify up to 50 options provided by Elastic
Beanstalk (p. 632).
option-setting-value
option_settings:
- namespace: "aws:elasticbeanstalk:application:environment"
option_name: "TEST"
value: "This is a test"
You can specify tags when you create a custom platform version. In an existing custom platform version,
you can add or remove tags, and update the values of existing tags. You can add up to 50 tags to each
custom platform version.
With the AWS CLI or other API-based clients, add tags by using the --tags parameter on the create-
platform-version command.
If you use the EB CLI to update your custom platform version, use eb tags (p. 1040) to add, update,
delete, or list tags.
For example, the following command lists the tags in a custom platform version.
The following command updates the tag mytag1 and deletes the tag mytag2.
1075
AWS Elastic Beanstalk Developer Guide
Tagging custom platform versions
For a complete list of options and more examples, see eb tags (p. 1040).
With the AWS CLI or other API-based clients, use the list-tags-for-resource command to list the tags of a
custom platform version.
Use the update-tags-for-resource command to add, update, or delete tags in a custom platform version.
Specify both tags to add and tags to update in the --tags-to-add parameter of update-tags-for-
resource. A nonexisting tag is added, and an existing tag's value is updated.
Note
To use some of the EB CLI and AWS CLI commands with an Elastic Beanstalk custom platform
version, you need the custom platform version's ARN. You can retrieve the ARN by using the
following command.
Use the --filters option to filter the output down to your custom platform's name.
1076