

# Deploying Java applications with Elastic Beanstalk
<a name="create_deploy_Java"></a>

This chapter provides instructions for configuring and deploying your Java applications to AWS Elastic Beanstalk. Elastic Beanstalk makes it easy to deploy, manage, and scale your Java web applications using Amazon Web Services.

You can deploy your application in just a few minutes using the Elastic Beanstalk Command Line Interface (EB CLI) or by using the Elastic Beanstalk console. 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.

Follow the [QuickStart for Java](java-quickstart.md) for step-by-step instructions to create and deploy a *Hello World* Java web application with the EB CLI. If you're interested in step-by-step instructions to create a simple *Hello World* Java JSP application to deploy with the EB CLI to our Tomcat based platform, try the [QuickStart for Java on Tomcat](tomcat-quickstart.md).

**The Java platform branches**  
AWS Elastic Beanstalk supports two platforms for Java applications.
+ **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](java-tomcat-platform.md).
+ **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 in the source bundle that you deploy to Elastic Beanstalk. For more information, see [The Java SE platform](java-se-platform.md).

Recent branches of both the Tomcat and Java SE platforms are based on Amazon Linux 2 and later, and use *Corretto*—the AWS Java SE distribution. The names of these platform branches include the word *Corretto* instead of *Java*.

For a list of current platform versions, see [Tomcat](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.java) and [Java SE](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.javase) in the *AWS Elastic Beanstalk Platforms* guide.

**AWS tools**  
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](java-development-environment.md#java-development-environment-sdk) 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 prefer to manage your applications from the command line, install the [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) and use it to create, monitor, and manage your Elastic Beanstalk environments. 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.

**Topics**
+ [

# QuickStart: Deploy a Java application to Elastic Beanstalk
](java-quickstart.md)
+ [

# QuickStart: Deploy a Java JSP web application for Tomcat to Elastic Beanstalk
](tomcat-quickstart.md)
+ [

# Setting up your Java development environment
](java-development-environment.md)
+ [

# More Elastic Beanstalk example applications and tutorials for Java
](java-getstarted.md)
+ [

# Using the Elastic Beanstalk Tomcat platform
](java-tomcat-platform.md)
+ [

# Using the Elastic Beanstalk Java SE platform
](java-se-platform.md)
+ [

# Adding an Amazon RDS DB instance to your Java Elastic Beanstalk environment
](java-rds.md)
+ [

# Java tools and resources
](create_deploy_Java.resources.md)

# QuickStart: Deploy a Java application to Elastic Beanstalk
<a name="java-quickstart"></a>

This QuickStart tutorial walks you through the process of creating a Java application and deploying it to an AWS Elastic Beanstalk environment.

**Not for production use**  
Examples are intended for demonstration only. Do not use example applications in production.

**Topics**
+ [

## Your AWS account
](#java-quickstart-aws-account)
+ [

## Prerequisites
](#java-quickstart-prereq)
+ [

## Step 1: Create a Java application
](#java-quickstart-create-app)
+ [

## Step 2: Run your application locally
](#java-quickstart-run-local)
+ [

## Step 3: Deploy your Java application with the EB CLI
](#java-quickstart-deploy)
+ [

## Step 4: Run your application on Elastic Beanstalk
](#java-quickstart-run-eb-ap)
+ [

## Step 5: Clean up
](#java-tutorial-cleanup)
+ [

## AWS resources for your application
](#java-quickstart-eb-resources)
+ [

## Next steps
](#java-quickstart-next-steps)
+ [

## Deploy with the Elastic Beanstalk console
](#java-quickstart-console)

## Your AWS account
<a name="java-quickstart-aws-account"></a>

If you're not already an AWS customer, you need to create an AWS account. Signing up enables you to access Elastic Beanstalk and other AWS services that you need.

If you already have an AWS account, you can move on to [Prerequisites](#java-quickstart-prereq).

### Create an AWS account
<a name="java-quickstart-aws-account-procedure"></a>

#### Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

#### Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

## Prerequisites
<a name="java-quickstart-prereq"></a>

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 (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

### EB CLI
<a name="java-quickstart-prereq.ebcli"></a>

This tutorial uses the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing and configuring the EB CLI, see [Install EB CLI with setup script (recommended)](eb-cli3.md#eb-cli3-install)and [Configure the EB CLI](eb-cli3-configuration.md).

### Java and Maven
<a name="java-quickstart-prereq.runtime"></a>

If you don't have Amazon Corretto installed on your local machine, you can install it by following the [ installation instructions](https://docs.aws.amazon.com/corretto/latest/corretto-21-ug/amazon-linux-install.html) in the *Amazon Corretto User Guide*.

Verify your Java installation by running the following command.

```
~$ java -version 
```

This tutorial uses Maven. Follow the [download](https://maven.apache.org/download.cgi) and [installation](https://maven.apache.org/install.html) instructions on the Apache Maven Project website. For more information about Maven see the [Maven Users Centre](https://maven.apache.org/users/index.html) on the Apache Maven Project website.

Verify your Maven installation by running the following command.

```
~$ mvn -v
```

## Step 1: Create a Java application
<a name="java-quickstart-create-app"></a>

Create a project directory.

```
~$ mkdir eb-java
~$ cd eb-java
```

Next, create an application that you'll deploy using Elastic Beanstalk. We'll create a "Hello World" RESTful web service.

This example uses the [Spring Boot](https://spring.io/projects/spring-boot) framework. This application opens a listener on port 5000. Elastic Beanstalk forward requests to your application on port 5000 by default.

Create the following files:

This file creates a simple Spring Boot application.

**Example `~/eb-java/src/main/java/com/example/Application.java`**  

```
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
```

This file creates a mapping that returns a String that we define here.

**Example `~/eb-java/src/main/java/com/example/Controller.java`**  

```
package com.example;
    
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
    
@RestController
public class Controller {
    
    @GetMapping("/")
    public String index() {
       return "Hello Elastic Beanstalk!";
    }
}
```

This file defines the Maven project configuration.

**Example `~/eb-java/pom.xml`**  

```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.3</version>
  </parent>

  <groupId>com.example</groupId>
  <artifactId>BeanstalkJavaExample</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <java.version>21</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>
```

This properties file overrides the default port to be 5000. This is the default port that Elastic Beanstalk sends traffic to for Java applications.

**Example `~/eb-java/application.properties`**  

```
server.port=5000
```

## Step 2: Run your application locally
<a name="java-quickstart-run-local"></a>

Package your application with the following command:

```
~/eb-java$ mvn clean package
```

Run your application locally with the following command:

```
~/eb-java$ java -jar target/BeanstalkJavaExample-1.0-SNAPSHOT.jar
```

While the application is running, navigate to `http://127.0.0.1:5000/` in your browser. You should see the text “Hello Elastic Beanstalk\$1”.

## Step 3: Deploy your Java application with the EB CLI
<a name="java-quickstart-deploy"></a>

Before deploying your Java application to Elastic Beanstalk, let’s clean the build application from your directory and create a [Buildfile](java-se-buildfile.md) and a [Procfile](java-se-procfile.md) to control how the application is built and run on your Elastic Beanstalk environment.

**To prepare and configure for application deployment**

1. Clean the built application.

   ```
   ~/eb-java$ mvn clean
   ```

1. Create your `Buildfile`.  
**Example `~/eb-java/Buildfile`**  

   ```
   build: mvn clean package
   ```

   This `Buildfile` specifies the command used to build your application. If you don’t include a `Buildfile` for a Java application, Elastic Beanstalk doesn't attempt to build your application.

1. Create your `Procfile`.  
**Example `~/eb-java/Procfile`**  

   ```
   web: java -jar target/BeanstalkJavaExample-1.0-SNAPSHOT.jar
   ```

   This `Procfile` specifies the command used to run your application. If you don’t include a `Procfile` for a Java application, Elastic Beanstalk assumes there is one JAR file in the root of your source bundle and tries to run it with the `java -jar` command.

 Now that you have set up the configuration files to build and start your application, you're ready to deploy it. 

**To create an environment and deploy your Java application**

1. Initialize your EB CLI repository with the **eb init** command. 

   ```
   ~/eb-java eb init -p corretto java-tutorial --region us-east-2
           
   Application java-tutorial has been created.
   ```

   This command creates an application named `java-tutorial` and configures your local repository to create environments with the latest Java platform version.

1. (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-java$ 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**.

1. Create an environment and deploy your application to it with **eb create**. Elastic Beanstalk automatically builds a zip file for your application and starts it on port 5000.

   ```
   ~/eb-java$ eb create java-env
   ```

   It takes about five minutes for Elastic Beanstalk to create your environment.

## Step 4: Run your application on Elastic Beanstalk
<a name="java-quickstart-run-eb-ap"></a>

When the process to create your environment completes, open your website with **eb open**.

```
~/eb-java eb open
```

Congratulations\$1 You've deployed a Java application with Elastic Beanstalk\$1 This opens a browser window using the domain name created for your application.

## Step 5: Clean up
<a name="java-tutorial-cleanup"></a>

You can terminate your environment when you finish working with your application. Elastic Beanstalk terminates all AWS resources associated with your environment.

To terminate your Elastic Beanstalk environment with the EB CLI run the following command.

```
~/eb-java$ eb terminate
```

## AWS resources for your application
<a name="java-quickstart-eb-resources"></a>

You just created a single instance application. It serves as a straightforward sample application with a single EC2 instance, so it doesn't require load balancing or auto scaling. For single instance applications Elastic Beanstalk creates the following AWS resources:
+ **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.
+ **CloudFormation stack** – Elastic Beanstalk uses 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 [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+  **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.

## Next steps
<a name="java-quickstart-next-steps"></a>

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. You can also explore your new environment using the Elastic Beanstalk console. For detailed steps, see [Explore your environment](GettingStarted.md#GettingStarted.Explore) in the *Getting started* chapter of this guide.

**Try more tutorials**  
If you'd like to try other tutorials with different example applications, see [Sample applications and tutorials](java-getstarted.md).

After you deploy a sample application or two and are ready to start developing and running Java applications locally, see [Setting up your Java development environment](java-development-environment.md). 

## Deploy with the Elastic Beanstalk console
<a name="java-quickstart-console"></a>

You can also use the Elastic Beanstalk console to launch the sample application. For detailed steps, see [Create an example application](GettingStarted.md#GettingStarted.CreateApp) in the *Getting started* chapter of this guide.

# QuickStart: Deploy a Java JSP web application for Tomcat to Elastic Beanstalk
<a name="tomcat-quickstart"></a>

This tutorial walks you through the process of creating a simple Java web application using JavaServer Pages (JSPs). If you'd like to bundle multiple web applications in the form of WAR files in a single Elastic Beanstalk environment, see [Bundling multiple WAR files for Tomcat environments](java-tomcat-multiple-war-files.md).

**Not for production use**  
Examples are intended for demonstration only. Do not use example applications in production.

**Topics**
+ [

## Your AWS account
](#tomcat-quickstart-aws-account)
+ [

## Prerequisites
](#tomcat-quickstart-prereq)
+ [

## Step 1: Create a Java JSP application
](#tomcat-quickstart-create-app)
+ [

## Step 2: Deploy your Java JSP application with the EB CLI
](#tomcat-quickstart-deploy)
+ [

## Step 3: Run your application on Elastic Beanstalk
](#tomcat-quickstart-run-eb-ap)
+ [

## Step 4: Clean up
](#go-tutorial-cleanup)
+ [

## AWS resources for your application
](#tomcat-quickstart-eb-resources)
+ [

## Next steps
](#tomcat-quickstart-next-steps)
+ [

## Deploy with the Elastic Beanstalk console
](#tomcat-quickstart-console)

## Your AWS account
<a name="tomcat-quickstart-aws-account"></a>

If you're not already an AWS customer, you need to create an AWS account. Signing up enables you to access Elastic Beanstalk and other AWS services that you need.

If you already have an AWS account, you can move on to [Prerequisites](#tomcat-quickstart-prereq).

### Create an AWS account
<a name="tomcat-quickstart-aws-account-procedure"></a>

#### Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

#### Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

## Prerequisites
<a name="tomcat-quickstart-prereq"></a>

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 (\$1) and the name of the current directory, when appropriate.

```
~/eb-project$ this is a command
this is output
```

On Linux and macOS, you can use your preferred shell and package manager. On Windows you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.

### EB CLI
<a name="tomcat-quickstart-prereq.ebcli"></a>

This tutorial uses the Elastic Beanstalk Command Line Interface (EB CLI). For details on installing and configuring the EB CLI, see [Install EB CLI with setup script (recommended)](eb-cli3.md#eb-cli3-install) and [Configure the EB CLI](eb-cli3-configuration.md).

## Step 1: Create a Java JSP application
<a name="tomcat-quickstart-create-app"></a>

Create a project directory.

```
~$ mkdir eb-tomcat
~$ cd eb-tomcat
```

Next, create an application that you'll deploy using Elastic Beanstalk. We'll create a "Hello World" web application.

Create a simple JSP file named `index.jsp`.

**Example `~/eb-tomcat/index.jsp`**  

```
<html>
  <body>
    <%out.println("Hello Elastic Beanstalk!");%>
  </body>
</html>
```

## Step 2: Deploy your Java JSP application with the EB CLI
<a name="tomcat-quickstart-deploy"></a>

Run the following commands to create an Elastic Beanstalk environment for this application.

 

**To create an environment and deploy your Java JSP application**

1. Initialize your EB CLI repository with the **eb init** command.

   ```
   ~/eb-tomcat$ eb init -p tomcat tomcat-tutorial --region us-east-2
   ```

   This command creates an application named `tomcat-tutorial` and configures your local repository to create environments with the latest Tomcat platform version.

1. (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**.

1. Create an environment and deploy your application to it with **eb create**. Elastic Beanstalk automatically builds a zip file for your application and starts it on port 5000.

   ```
   ~/eb-tomcat$ eb create tomcat-env
   ```

   It takes about five minutes for Elastic Beanstalk to create your environment.

## Step 3: Run your application on Elastic Beanstalk
<a name="tomcat-quickstart-run-eb-ap"></a>

When the process to create your environment completes, open your website with **eb open**.

```
~/eb-tomcat$ eb open
```

Congratulations\$1 You've deployed a Java JSP application with Elastic Beanstalk\$1 This opens a browser window using the domain name created for your application.

## Step 4: Clean up
<a name="go-tutorial-cleanup"></a>

You can terminate your environment when you finish working with your application. Elastic Beanstalk terminates all AWS resources associated with your environment.

To terminate your Elastic Beanstalk environment with the EB CLI run the following command.

```
~/eb-tomcat$ eb terminate
```

## AWS resources for your application
<a name="tomcat-quickstart-eb-resources"></a>

You just created a single instance application. It serves as a straightforward sample application with a single EC2 instance, so it doesn't require load balancing or auto scaling. For single instance applications Elastic Beanstalk creates the following AWS resources:
+ **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.
+ **CloudFormation stack** – Elastic Beanstalk uses 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 [CloudFormation console](https://console.aws.amazon.com/cloudformation).
+  **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.

## Next steps
<a name="tomcat-quickstart-next-steps"></a>

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. You can also explore your new environment using the Elastic Beanstalk console. For detailed steps, see [Explore your environment](GettingStarted.md#GettingStarted.Explore) in the *Getting started* chapter of this guide.

**Try more tutorials**  
If you'd like to try other tutorials with different example applications, see [Sample applications and tutorials](java-getstarted.md).

After you deploy a sample application or two and are ready to start developing and running Java applications in a local Tomcat web container, see [Setting up your Java development environment](java-development-environment.md). 

## Deploy with the Elastic Beanstalk console
<a name="tomcat-quickstart-console"></a>

You can also use the Elastic Beanstalk console to launch the sample application. For detailed steps, see [Create an example application](GettingStarted.md#GettingStarted.CreateApp) in the *Getting started* chapter of this guide.

# Setting up your Java development environment
<a name="java-development-environment"></a>

This topic provides instructions to set up a Java development environment to test your application locally prior to deploying it to AWS Elastic Beanstalk. It also references websites that provide installation instructions for useful tools.

**Topics**
+ [

## Installing the Java development kit
](#java-development-environment-jdk)
+ [

## Installing a web container
](#java-development-environment-tomcat)
+ [

## Downloading libraries
](#java-development-environment-libraries)
+ [

## Installing the AWS SDK for Java
](#java-development-environment-sdk)
+ [

## Installing an IDE or text editor
](#java-development-environment-ide)

## Installing the Java development kit
<a name="java-development-environment-jdk"></a>

Install the Java Development Kit (JDK). If you don't have a preference, get the latest version. Download the JDK at [oracle.com](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 

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.

## Installing a web container
<a name="java-development-environment-tomcat"></a>

If you don't already have another web container or framework, install a version of Tomcat that Elastic Beanstalk supports for your Amazon Linux operating system. For a list of the current versions of Apache Tomcat that Elastic Beanstalk supports, see [Tomcat](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.java) in the *AWS Elastic Beanstalk Platforms* document. Download the Tomcat version that applies to your environment from the [Apache Tomcat](http://tomcat.apache.org) website. 

## Downloading libraries
<a name="java-development-environment-libraries"></a>

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.

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](https://github.com/junit-team/junit/wiki/Download-and-Install) 
+  [Download Google Guava](https://code.google.com/p/guava-libraries/) 
+  [Download Apache Commons](http://commons.apache.org/downloads/) 

## Installing the AWS SDK for Java
<a name="java-development-environment-sdk"></a>

If you need to manage AWS resources from within your application, install the AWS SDK for Java. For example, with the AWS SDK for Java, you can use Amazon DynamoDB (DynamoDB) to share session states of Apache Tomcat applications across multiple web servers. For more information, see [Manage Tomcat Session State with Amazon DynamoDB](http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-tomcat-session-manager.html) in the AWS SDK for Java documentation.

Visit the [AWS SDK for Java home page](https://aws.amazon.com/sdk-for-java/) for more information and installation instructions.

## Installing an IDE or text editor
<a name="java-development-environment-ide"></a>

Integrated development environments (IDEs) provide a wide range of features that facilitate application development. If you haven't used an IDE for Java development, try Eclipse and IntelliJ and see which works best for you.
+  [Install Eclipse IDE for Java EE Developers](https://www.eclipse.org/downloads/) 
+  [Install IntelliJ](https://www.jetbrains.com/idea/) 

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](http://www.sublimetext.com/).

**Note**  
On May 31, 2023, the [AWS Toolkit for Eclipse](https://docs.aws.amazon.com//toolkit-for-eclipse/v1/user-guide/welcome.html) reached end of life and is no longer supported by AWS. For additional details regarding the end of life cycle for the AWS Toolkit for Eclipse, see the [README.md](https://github.com/aws/aws-toolkit-eclipse) file on the AWS Toolkit for Eclipse GitHub repository. 

# More Elastic Beanstalk example applications and tutorials for Java
<a name="java-getstarted"></a>

This section provides additional applications and tutorials. The [QuickStart for Java](java-quickstart.md) and [QuickStart for Java on Tomcat](tomcat-quickstart.md) topics located earlier in this topic walk you through launching a sample Java application with the EB CLI.

To get started with Java applications on AWS Elastic Beanstalk, all you need is an application [source bundle](applications-sourcebundle.md) to upload as your first application version and to deploy to an environment. When you create an environment, Elastic Beanstalk allocates all of the AWS resources needed to run a scalable web application.

## Launching an environment with a sample Java application
<a name="java-getstarted-samples"></a>

Elastic Beanstalk provides single page sample applications for each platform as well as more complex examples that show the use of additional AWS resources such as Amazon RDS and language or platform-specific features and APIs.

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.

 


**Samples**  

|  Name  |  Supported versions  |  Environment type  |  Source  |  Description  | 
| --- | --- | --- | --- | --- | 
|  Tomcat (single page)  |  All *Tomcat with Corretto* platform branches  |  Web Server Worker  |   [tomcat.zip](samples/tomcat.zip)   |  Tomcat web application with a single page (`index.jsp`) configured to be displayed at the website root. For [worker environments](using-features-managing-env-tiers.md), 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. If you [enable X-Ray integration](environment-configuration-debugging.md) on an environment running this sample, the application shows additional content regarding X-Ray and provides an option to generate debug information that you can view in the X-Ray console.  | 
|  Corretto (single page)  |  Corretto 11 Corretto 8  |  Web Server  |  [corretto.zip](samples/corretto.zip)  |  Corretto application with `Buildfile` and `Procfile` configuration files. If you [enable X-Ray integration](environment-configuration-debugging.md) on an environment running this sample, the application shows additional content regarding X-Ray and provides an option to generate debug information that you can view in the X-Ray console.  | 
|  Scorekeep  | Java 8 | Web Server | [Clone the repo at GitHub.com](https://github.com/awslabs/eb-java-scorekeep) |  *Scorekeep* is a RESTful web API that uses the Spring framework to provide an interface for creating and managing users, sessions, and games. The API is bundles with an Angular 1.5 web app that consumes the API over HTTP. 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`. Scorekeep also includes an `xray` branch that shows how to instrument a Java application for use with AWS X-Ray. It shows instrumentation of incoming HTTP requests with a servlet filter, automatic and manual AWS SDK client instrumentation, recorder configuration, and instrumentation of outgoing HTTP requests and SQL clients. See the readme for instructions or use the [AWS X-Ray getting started tutorial](https://docs.aws.amazon.com/xray/latest/devguide/xray-gettingstarted.html) to try the application with X-Ray.  | 
|  Does it Have Snakes?  | Tomcat 8 with Java 8 | Web Server | [Clone the repo at GitHub.com](https://github.com/awslabs/eb-tomcat-snakes) |  *Does it Have Snakes?* is a Tomcat web application that shows the use of Elastic Beanstalk configuration files, Amazon RDS, JDBC, PostgreSQL, Servlets, JSPs, Simple Tag Support, Tag Files, Log4J, Bootstrap, and Jackson. The source code for this project includes a minimal build script that compiles the servlets and models into class files and packages the required files into a Web Archive that you can deploy to an Elastic Beanstalk environment. See the readme file in the project repository for full instructions.  | 
| Locust Load Generator | Java 8 | Web Server | [Clone the repo at GitHub.com](https://github.com/awslabs/eb-locustio-sample) |  Web application that you can use to load test another web application running in a different Elastic Beanstalk environment. Shows the use of `Buildfile` and `Procfile` files, DynamoDB, and [Locust](http://locust.io/), an open source load testing tool.  | 

Download any of the sample applications and deploy it to Elastic Beanstalk by following these steps:

**To launch an environment with an application (console)**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Applications**. Select an existing application in the list. You can also choose to create one, following the instructions in [Managing applications](applications.md).

1. On the application overview page, choose **Create environment**.

   This launches the **Create environment** wizard. The wizard provides a set of steps for you to create a new environment.

1. For **Environment tier**, choose the **Web server environment** or **Worker environment** [environment tier](concepts.md#concepts-tier). You can't change an environment's tier after creation.
**Note**  
The [.NET on Windows Server platform](create_deploy_NET.md) doesn't support the worker environment tier.

   The **Application information** fields default, based on the application that you previously chose.

   In the **Environment information** grouping the **Environment name** defaults, based on the application name. If you prefer a different environment name you can enter another value in the field. You can optionally enter a **Domain** name; otherwise Elastic Beanstalk autogenerates a value. You can also optionally enter an **Environment description.**

1. For **Platform**, select the platform and platform branch that match the language your application uses.
**Note**  
Elastic Beanstalk supports multiple [versions](concepts.platforms.md) 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. For information about supported platform versions, see [Elastic Beanstalk supported platforms](concepts.platforms.md).

1. For **Application code**, you have several choices to proceed.
   + To launch the default sample application without supplying the source code, choose **Sample application**. This action chooses the single page application that Elastic Beanstalk provides for the platform you previously selected.
   + If you downloaded a sample application from this guide, or you have your own source code for an application, do the following steps.

     1. Select **Upload your code**.

     1. Next choose **Local file**, then under **Upload application**, select **Choose file**.

     1. Your client machine's operating system will present you with an interface to select the local file that you downloaded. Select the source bundle file and continue.

1. Your choice for **Presets** depends on your purpose for the environment.
   + If you're creating a sample environment to learn about Elastic Beanstalk or a development environment, choose **Single instance (free tier eligible)**.
   + If you're creating a production environment or an environment to learn more about load balancing, choose one of the **High availability** options.

1. Choose **Next**.

**To configure service access**  
Next, you need two roles. A *service role* allows Elastic Beanstalk to monitor your EC2 instances and upgrade you environment’s platform. An *EC2 instance profile* role permits tasks such as writing logs and interacting with other services.

**To create or select the Service role**

1. If you have previously created a **Service role** and would like to choose an existing one, select the value from the **Service role** drop-down and skip the remainder of these steps to create a Service role.

1. If you don't see any values listed for **Service role**, or you'd like to create a new one, continue with the next steps.

1. For **Service role**, choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Use case**, choose **Elastic Beanstalk – Environment**.

1. Choose **Next**.

1. Verify that **Permissions policies** include the following, then choose **Next**:
   + `AWSElasticBeanstalkEnhancedHealth`
   + `AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy`

1. Choose **Create role**.

1. Return to the **Configure service access** tab, refresh the list, then select the newly created service role.

**To create or select an EC2 instance profile**

1. If you have previously created an **EC2 instance profile** and would like to choose an existing one, select the value from the **EC2 instance profile** drop-down and skip the remainder of these steps to create an EC2 instance profile.

1. If you don't see any values listed for **EC2 instance profile**, or you'd like to create a new one, continue with the next steps.

1. Choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Use case**, choose** Elastic Beanstalk – Compute**.

1. Choose **Next**.

1. Verify that **Permissions policies** include the following, then choose **Next**:
   + `AWSElasticBeanstalkWebTier`
   + `AWSElasticBeanstalkWorkerTier`
   + `AWSElasticBeanstalkMulticontainerDocker`

1. Choose **Create role**.

1. Return to the **Configure service access** tab, refresh the list, then select the newly created EC2 instance profile.

**To finish configuring and creating your application**

1. (Optional) If you previously created an EC2 key pair, you can select it from the **EC2 key pair** field dropdown. You would use it to securely log in to the Amazon EC2 instance that Elastic Beanstalk provisions for your application. If you skip this step, you can always create and assign an EC2 key pair after the environment is created. For more information, see [EC2 key pair](using-features.managing.security.md#using-features.managing.security.keypair).

1. Choose **Skip to Review** on the **Configure service access** page.

1. The **Review** page displays a summary of all your choices.

   To further customize your environment, choose **Edit** next to the step that includes any items you want to configure. You can set the following options only during environment creation:
   + Environment name
   + Domain name
   + Platform version
   + Processor
   + Load balancer type
   + 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
   + VPC

   For details on all available settings, see [The create new environment wizard](environments-create-wizard.md).

1. Choose **Submit** at the bottom of the page to initialize the creation of your new environment.

## Next steps
<a name="java-getstarted-next"></a>

After you have an environment running an application, you can [deploy a new version](using-features.deploy-existing-version.md) 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](java-development-environment.md) to set up a Java development environment with all of the tools and libraries that you will need.

# Using the Elastic Beanstalk Tomcat platform
<a name="java-tomcat-platform"></a>

This topic describes how to configure, build, and run your Java applications that run on the Elastic Beanstalk Tomcat platform.

The AWS Elastic Beanstalk Tomcat platform is a set of [platform versions](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.java) 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.

Configuration options are available in the Elastic Beanstalk console for [modifying the configuration of a running environment](environment-configuration-methods-after.md). To avoid losing your environment's configuration when you terminate it, you can use [saved configurations](environment-configuration-savedconfig.md) to save your settings and later apply them to another environment.

To save settings in your source code, you can include [configuration files](ebextensions.md). 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](#java-tomcat-namespaces) 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](java-tomcat-proxy.md) in your source bundle to extend the Elastic Beanstalk proxy configuration or overwrite it completely.

**Note**  
Elastic Beanstalk supports [nginx](https://www.nginx.com/) (the default) and [Apache HTTP Server](https://httpd.apache.org/) 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](https://httpd.apache.org/docs/2.2/). Apache (latest) is the default on these older platform branches.   
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

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](java-tomcat-platform-directorystructure.md).

To run multiple applications on the same web server, you can [bundle multiple WAR files](java-tomcat-multiple-war-files.md) 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](command-options.md).

For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see [Extending Elastic Beanstalk Linux platforms](platforms-linux-extend.md).

**Topics**
+ [

## Configuring your Tomcat environment
](#java-tomcat-options)
+ [

## Tomcat configuration namespaces
](#java-tomcat-namespaces)
+ [

# Bundling multiple WAR files for Tomcat environments
](java-tomcat-multiple-war-files.md)
+ [

# Structuring your project folder
](java-tomcat-platform-directorystructure.md)
+ [

# Configuring the proxy server
](java-tomcat-proxy.md)

## Configuring your Tomcat environment
<a name="java-tomcat-options"></a>

The Elastic Beanstalk Tomcat platform provides a few platform-specific options in addition to the standard options that all platforms have. These options enable you to configure the Java virtual machine (JVM) that runs on your environment's web servers, and define system properties that provide information configuration strings to your application.

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.

**To configure your Tomcat environment in the Elastic Beanstalk console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

### Container options
<a name="java-tomcat-options-container"></a>

You can specify these platform-specific options:
+ **Proxy server** – The proxy server to use on your environment instances. By default, nginx is used.

### JVM container options
<a name="java-tomcat-options-jvm"></a>

The heap size in the Java virtual machine (JVM) determines how many objects your application can create in memory before *[garbage collection](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/introduction.html)* occurs. You can modify the** Initial JVM Heap Size** (`-Xms option`) and a **Maximum JVM Heap Size **(`-Xmx` option). A larger initial heap size allows more objects to be created before garbage collection occurs, but it also means that the garbage collector will take longer to compact the heap. The maximum heap size specifies the maximum amount of memory the JVM can allocate when expanding the heap during heavy activity.

**Note**  
The available memory depends on the Amazon EC2 instance type. For more information about the EC2 instance types available for your Elastic Beanstalk environment, see [Instance Types](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the *Amazon Elastic Compute Cloud User Guide for Linux Instances*.

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`) option. This setting applies only to Java 7 and earlier. This option was deprecated in JDK 8 and superseded by the **MaxMetaspace Size** (`-XX:MaxMetaspaceSize`) option.

**Important**  
JDK 17 removed support of the Java `-XX:MaxPermSize` option. Usage of this option with an environment running on an Elastic Beanstalk platform branch with Corretto 17 will result in an error. Elastic Beanstalk released its first platform branch running Tomcat with Corretto 17 on [July 13, 2023](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2023-07-13-al2023.html).  
For more information see the following resources.  
Oracle Java documentation website: [Removed Java Options](https://docs.oracle.com/en/java/javase/17/docs/specs/man/java.html#removed-java-options) 
Oracle Java documentation website: *Class Metadata* section in [ Other Considerations](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/considerations.html)

For more information about Elastic Beanstalk platforms and their components, see [Supported Platforms](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html) in the *AWS Elastic Beanstalk Platforms* guide.

### Log options
<a name="java-tomcat-options-logs"></a>

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 are copied to the Amazon S3 bucket associated with your application.

### Static files
<a name="java-tomcat-options-staticfiles"></a>

To improve performance, you can use the **Static files** section to 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 [Serving static files](environment-cfg-staticfiles.md).

### Environment properties
<a name="java-tomcat-options-properties"></a>

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\$1CONNECTION\$1STRING 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 Elastic Beanstalk environment](java-rds.md).

For Tomcat platform versions released prior to [March 26, 2025](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2025-03-26-windows.html), environment variables are accessible using `System.getProperty()`. For example, you could read a property named `API_ENDPOINT` from a variable with the following code.

```
String endpoint = System.getProperty("API_ENDPOINT");
```

Tomcat platform versions released on or after [March 26, 2025](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2025-03-26-windows.html), can also use `System.getenv` to access plaintext environment variables. You can continue to use `System.getProperty` to access plaintext environment variables. However, [environment variables stored as secrets](AWSHowTo.secrets.env-vars.md) are only available using `System.getenv`. For example, you could read an environment variable named `API_KEY` with the following code.

```
String apiKey = System.getenv("API_KEY");
```

**Important**  
The addition of `System.getenv()` access for environment variables in Tomcat platform versions released on or after [March 26, 2025](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2025-03-26-windows.html) may cause unexpected behavior in applications that give environment variables precedence over Java system properties or when explicitly switching from `System.getProperty()` to `System.getenv()`.  
Since system properties (passed via command line) require shell escaping for special characters while environment variables do not, values may be resolved differently when using environment variables instead of Java system properties.  
If your application is affected, consider:  
Removing escape characters from your environment property values when using `System.getenv()`
Configuring your application to explicitly use `System.getProperty()`
Testing your application thoroughly when upgrading to ensure consistent behavior

See [Environment variables and other software settings](environments-cfg-softwaresettings.md) for more information.

## Tomcat configuration namespaces
<a name="java-tomcat-namespaces"></a>

You can use a [configuration file](ebextensions.md) to set configuration options and perform other instance configuration tasks during deployments. Configuration options can be [platform specific](command-options-specific.md) or apply to [all platforms](command-options-general.md) in the Elastic Beanstalk service as a whole. Configuration options are organized into *namespaces*.

The Tomcat platform supports options in the following namespaces, in addition to the [options supported for all Elastic Beanstalk environments](command-options-general.md):
+ `aws:elasticbeanstalk:container:tomcat:jvmoptions` – Modify JVM settings. Options in this namespace correspond to options in the management console, as follows:
  + `Xms` – **JVM command line options**
  + `JVM Options` – **JVM command line options**
+ `aws:elasticbeanstalk:environment:proxy` – Choose the environment's proxy server.

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
    JVM Options: '-Xmn128m'
  aws:elasticbeanstalk:application:environment:
    API_ENDPOINT: mywebapi.zkpexsjtmd.us-west-2.elasticbeanstalk.com
  aws:elasticbeanstalk:environment:proxy:
    ProxyServer: apache
```

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](command-options.md) for more information.

## The Amazon Linux AMI (preceding Amazon Linux 2) Tomcat platform
<a name="tomcat.alami"></a>

If your Elastic Beanstalk Tomcat environment uses an Amazon Linux AMI platform version (preceding Amazon Linux 2), read the additional information in this section.

**Notes**  
The information in this topic only applies to platform branches based on Amazon Linux AMI (AL1). AL2023/AL2 platform branches are incompatible with previous Amazon Linux AMI (AL1) platform versions and *require different configuration settings*.
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

### Tomcat configuration namespaces — Amazon Linux AMI (AL1)
<a name="tomcat.alami.namespaces"></a>

The Tomcat Amazon Linux AMI platform supports additional options in the following namespaces:
+ `aws:elasticbeanstalk:container:tomcat:jvmoptions` – In addition to the options mentioned earlier on this page for this namespace, older Amazon Linux AMI platform versions also support:
  + `XX:MaxPermSize` – **Maximum JVM permanent generation size**
+ `aws:elasticbeanstalk:environment:proxy` – In addition to choosing the proxy server, also configure response compression.

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
```

### Include Elastic Beanstalk configurations files — Amazon Linux AMI (AL1)
<a name="java-tomcat-ebextensions"></a>

To deploy `.ebextensions` configuration files, include them in your application source. For a single application, add your `.ebextensions` to a compressed WAR file by running the following command:

**Example**  

```
zip -ur your_application.war .ebextensions
```

For an application requiring multiple WAR files, see [Bundling multiple WAR files for Tomcat environments](java-tomcat-multiple-war-files.md) for further instructions.

# Bundling multiple WAR files for Tomcat environments
<a name="java-tomcat-multiple-war-files"></a>

If your web app comprises multiple web application components, you can simplify deployments and reduce operating costs by running components in a single environment, instead of running a separate environment for each component. This strategy is effective for lightweight applications that don't require a lot of resources, and for development and test environments.

To deploy multiple web applications to your environment, combine each component's web application archive (WAR) files into a single [source bundle](applications-sourcebundle.md).

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 [Extending Elastic Beanstalk Linux platforms](platforms-linux-extend.md).

**To launch an environment (console)**

1. Open the Elastic Beanstalk console with this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application, or the Docker platform for container-based applications.

1. For **Application code**, choose **Upload your code**.

1. Choose **Local file**, choose **Choose file**, and then open the source bundle.

1. Choose **Review and launch**.

1. Review the available settings, and then choose **Create app**.

For information about creating source bundles, see [Create an Elastic Beanstalk application source bundle](applications-sourcebundle.md).

# Structuring your project folder
<a name="java-tomcat-platform-directorystructure"></a>

To work when deployed to a Tomcat server, compiled Java Platform Enterprise Edition (*Java EE*) web application archives (WAR files) must be structured according to certain [guidelines](https://docs.oracle.com/javaee/7/tutorial/packaging003.htm). Your project directory doesn't have to meet the same standards, but it's a good idea to structure it in the same way to simplify compiling and packaging. Structuring your project folder like the WAR file contents also helps you understand how files are related and how they behave on a web server.

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
    |   |-- tlds        - Tag Library Descriptor files
    |   `-- web.xml     - Deployment Descriptor
    |-- com             - Uncompiled classes
    |-- css             - Style sheets
    |-- images          - Image files
    |-- js              - JavaScript files
    `-- default.jsp     - JSP (JavaServer Pages) webpage
```

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](http://getbootstrap.com/), 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
```

## Building a WAR file with a shell script
<a name="java-tomcat-platform-directorystructure-building"></a>

`build.sh` is a very simple shell script that compiles Java classes, constructs a WAR file, and copies it to the Tomcat `webapps` directory for local testing.

```
cd src
javac -d WEB-INF/classes com/myapp/model/Record.java
javac -classpath WEB-INF/lib/*:WEB-INF/classes -d WEB-INF/classes com/myapp/model/Record.java
javac -classpath WEB-INF/lib/*:WEB-INF/classes -d WEB-INF/classes com/myapp/web/ListRecords.java

jar -cvf ROOT.war *.jsp images css js WEB-INF
cp ROOT.war /Library/Tomcat/webapps
mv ROOT.war ../
```

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`
<a name="java-tomcat-platform-gitignore"></a>

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.

**\$1/workspace/myapp/.gitignore**

```
*.zip
*.class
```

# Configuring the proxy server
<a name="java-tomcat-proxy"></a>

The Tomcat platform uses [nginx](https://www.nginx.com/) (the default) or [Apache HTTP Server](https://httpd.apache.org/) as the reverse proxy to relay requests from port 80 on the instance to your Tomcat web container listening on port 8080. Elastic Beanstalk provides a default proxy configuration that you can extend or override completely with your own configuration.

**Configuring the proxy server on your platform version**  
All AL2023/AL2 platforms support a uniform proxy configuration feature. For more information about configuring the proxy server on your platform versions running AL2023/AL2, see [Reverse proxy configuration](platforms-linux-extend.proxy.md). 

## Configuring the proxy on the Amazon Linux AMI (preceding Amazon Linux 2) Tomcat platform
<a name="java-tomcat-proxy.alami"></a>

If your Elastic Beanstalk Tomcat environment uses an Amazon Linux AMI platform version (preceding Amazon Linux 2), read the additional information in this section.

**Notes**  
The information in this topic only applies to platform branches based on Amazon Linux AMI (AL1). AL2023/AL2 platform branches are incompatible with previous Amazon Linux AMI (AL1) platform versions and *require different configuration settings*.
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

### Choosing a proxy server for your Tomcat environment — Amazon Linux AMI (AL1)
<a name="java-tomcat-proxy.alami"></a>

Tomcat platform versions based on Amazon Linux AMI (preceding Amazon Linux 2) use [Apache 2.4](https://httpd.apache.org/docs/2.4/) for the proxy by default. You can choose to use [Apache 2.2](https://httpd.apache.org/docs/2.2/) or [nginx](https://www.nginx.com/) by including a [configuration file](ebextensions.md) in your source code. The following example configures Elastic Beanstalk to use nginx.

**Example .ebextensions/nginx-proxy.config**  

```
option_settings:
  aws:elasticbeanstalk:environment:proxy:
    ProxyServer: nginx
```

### Migrating from Apache 2.2 to Apache 2.4 — Amazon Linux AMI (AL1)
<a name="java-tomcat-proxy-apache-migrate"></a>

If your application was developed for [Apache 2.2](https://httpd.apache.org/docs/2.2/), read this section to learn about migrating to [Apache 2.4](https://httpd.apache.org/docs/2.4/).

Starting with Tomcat platform version 3.0.0 configurations, which were released with the [Java with Tomcat platform update on May 24, 2018](https://aws.amazon.com/releasenotes/release-aws-elastic-beanstalk-platform-update-for-the-java-with-tomcat-platform-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 — Amazon Linux AMI (AL1)](#java-tomcat-proxy-apache), 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](https://httpd.apache.org/docs/current/upgrading.html) 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](ebextensions.md) 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](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

1. For **Proxy server**, choose `Apache 2.2 (deprecated)`.

1. To save the changes choose **Apply** at the bottom of the page.

![\[Choosing the proxy for a Tomcat environment in the Elastic Beanstalk console's software configuration category\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/java-tomcat-proxy-selection.png)


### Extending and overriding the default Apache configuration — Amazon Linux AMI (AL1)
<a name="java-tomcat-proxy-apache"></a>

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.

**Note**  
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, see [Reverse proxy configuration](platforms-linux-extend.proxy.md).
If you're migrating your Elastic Beanstalk application to an Amazon Linux 2 platform, be sure to also read the information in [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

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
|   `-- 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 in Elastic Beanstalk](health-enhanced.md), 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](https://httpd.apache.org/docs/2.4/mod/core.html#include), [IncludeOptional in Apache 2.4](https://httpd.apache.org/docs/2.4/mod/core.html#includeoptional), and [Include in Apache 2.2](https://httpd.apache.org/docs/2.2/mod/core.html#include).

**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.

### Extending the default nginx configuration — Amazon Linux AMI (AL1)
<a name="java-tomcat-proxy-nginx"></a>

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
```

**Notes**  
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;
  ```
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 in Elastic Beanstalk](health-enhanced.md) 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.

# Using the Elastic Beanstalk Java SE platform
<a name="java-se-platform"></a>

This topic describes how to configure, build, and run your Java applications that run on the AWS Elastic Beanstalk Java SE platform.

The Elastic Beanstalk Java SE platform is a set of [platform versions](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.javase) for Java web applications that can run on their own from a compiled JAR file. You can compile your application locally or upload the source code with a build script to compile it on-instance. Java SE platform versions are grouped into platform branches, each of which corresponds to a major version of Java.

**Note**  
Elastic Beanstalk doesn't parse your application's JAR file. Keep files that Elastic Beanstalk needs outside of the JAR file. For example, include the `cron.yaml` file of a [worker environment](using-features-managing-env-tiers.md) at the root of your application's source bundle, next to the JAR file.

Configuration options are available in the Elastic Beanstalk console for [modifying the configuration of a running environment](environment-configuration-methods-after.md). To avoid losing your environment's configuration when you terminate it, you can use [saved configurations](environment-configuration-savedconfig.md) to save your settings and later apply them to another environment.

To save settings in your source code, you can include [configuration files](ebextensions.md). 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](https://www.nginx.com/) 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](java-se-nginx.md) 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](java-se-procfile.md) 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](java-se-buildfile.md) 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.

For details about the various ways you can extend an Elastic Beanstalk Linux-based platform, see [Extending Elastic Beanstalk Linux platforms](platforms-linux-extend.md).

## Configuring your Java SE environment
<a name="java-se-options"></a>

The Java SE platform settings let you fine-tune the behavior of your Amazon EC2 instances. You can edit the Elastic Beanstalk environment's Amazon EC2 instance configuration using the Elastic Beanstalk console.

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 Java SE environment in the Elastic Beanstalk console**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Updates, monitoring, and logging** configuration category, choose **Edit**.

### Log options
<a name="java-se-options-logs"></a>

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 are copied to the Amazon S3 bucket associated with your application.

### Static files
<a name="java-se-options-staticfiles"></a>

To improve performance, you can use the **Static files** section to 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 [Serving static files](environment-cfg-staticfiles.md).

### Environment properties
<a name="java-se-options-properties"></a>

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:

```
String endpoint = System.getenv("API_ENDPOINT");
```

See [Environment variables and other software settings](environments-cfg-softwaresettings.md) for more information.

## Java SE configuration namespace
<a name="java-se-namespaces"></a>

You can use a [configuration file](ebextensions.md) to set configuration options and perform other instance configuration tasks during deployments. Configuration options can be [platform specific](command-options-specific.md) or apply to [all platforms](command-options-general.md) in the Elastic Beanstalk service as a whole. Configuration options are organized into *namespaces*.

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 [Serving static files](environment-cfg-staticfiles.md).

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](command-options.md) for more information.

## The Amazon Linux AMI (preceding Amazon Linux 2) Java SE platform
<a name="java-se.alami"></a>

If your Elastic Beanstalk Java SE environment uses an Amazon Linux AMI platform version (preceding Amazon Linux 2), read the additional information in this section.

**Notes**  
The information in this topic only applies to platform branches based on Amazon Linux AMI (AL1). AL2023/AL2 platform branches are incompatible with previous Amazon Linux AMI (AL1) platform versions and *require different configuration settings*.
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

### Java SE configuration namespaces — Amazon Linux AMI (AL1)
<a name="java-se.alami.namespaces"></a>

You can use a [configuration file](ebextensions.md) to set configuration options and perform other instance configuration tasks during deployments. Configuration options can be [platform specific](command-options-specific.md) or apply to [all platforms](command-options-general.md) in the Elastic Beanstalk service as a whole. Configuration options are organized into *namespaces*.

The Java SE platform supports one platform-specific configuration namespace in addition to the [namespaces supported by all platforms](command-options-general.md). The `aws:elasticbeanstalk:container:java:staticfiles` namespace lets you define options that map paths on your web application to folders in your application source bundle that contain static content.

For example, this [option\$1settings](ebextensions-optionsettings.md) 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](command-options.md) for more information.

# Building JARs on-server with a Buildfile
<a name="java-se-buildfile"></a>

You can build your application's class files and JAR(s) on the EC2 instances in your environment by invoking a build command from a `Buildfile` file in your source bundle.

Commands in a `Buildfile` are only run once and must terminate upon completion, whereas commands in a [Procfile](java-se-procfile.md) 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`.

For details about the placement and syntax of a `Buildfile`, see [Buildfile and Procfile](platforms-linux-extend.build-proc.md).

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](java-getstarted.md#java-getstarted-samples).

**Example Buildfile**  

```
build: mvn assembly:assembly -DdescriptorId=jar-with-dependencies
```

The Java SE platform includes the following build tools, which you can invoke from your build script:
+ `javac` – Java compiler
+ `ant` – Apache Ant
+ `mvn` – Apache Maven
+ `gradle` – Gradle

# Configuring the application process with a Procfile
<a name="java-se-procfile"></a>

If you have more than one JAR file in the root of your application source bundle, you must include a `Procfile` file that tells Elastic Beanstalk which JAR(s) to run. You can also include a `Procfile` file for a single JAR application to configure the Java virtual machine (JVM) that runs your application.

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` see [Buildfile and Procfile](platforms-linux-extend.build-proc.md).

**Example Procfile**  

```
web: java -Xms256m -jar server.jar 
cache: java -jar mycache.jar
web_foo: java -jar other.jar
```

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`](java-se-buildfile.md).

## Using a Procfile on Amazon Linux AMI (preceding Amazon Linux 2)
<a name="java-se-procfile.alami"></a>

If your Elastic Beanstalk Java SE environment uses an Amazon Linux AMI platform version (preceding Amazon Linux 2), read the additional information in this section.

**Notes**  
The information in this topic only applies to platform branches based on Amazon Linux AMI (AL1). AL2023/AL2 platform branches are incompatible with previous Amazon Linux AMI (AL1) platform versions and *require different configuration settings*.
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

### Port passing — Amazon Linux AMI (AL1)
<a name="java-se-procfile.alami.ports"></a>

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](java-se-platform.md#java-se-options) 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. 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.

# Configuring the proxy server
<a name="java-se-nginx"></a>

Elastic Beanstalk uses [nginx](https://www.nginx.com/) as the reverse proxy to map your application to your Elastic Load Balancing load balancer on port 80. Elastic Beanstalk provides a default nginx configuration that you can either extend or override completely with your own configuration.

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](java-se-platform.md#java-se-options) 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.

**Configuring the proxy server on your platform version**  
All AL2023/AL2 platforms support a uniform proxy configuration feature. For more information about configuring the proxy server on your platform versions running AL2023/AL2, see [Reverse proxy configuration](platforms-linux-extend.proxy.md). 

## Configuring the proxy on Amazon Linux AMI (preceding Amazon Linux 2)
<a name="java-se-nginx.alami"></a>

If your Elastic Beanstalk Java SE environment uses an Amazon Linux AMI platform version (preceding Amazon Linux 2), read the additional information in this section.

**Notes**  
The information in this topic only applies to platform branches based on Amazon Linux AMI (AL1). AL2023/AL2 platform branches are incompatible with previous Amazon Linux AMI (AL1) platform versions and *require different configuration settings*.
 On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. For more information about migrating to a current and fully supported Amazon Linux 2023 platform branch, see [Migrating your Elastic Beanstalk Linux application to Amazon Linux 2023 or Amazon Linux 2](using-features.migration-al.md).

### Extending and overriding the default proxy configuration — Amazon Linux AMI (AL1)
<a name="java-se-nginx.alami.extending"></a>

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 in Elastic Beanstalk](health-enhanced.md), automatic application mappings, and static files.

```
 include conf.d/elasticbeanstalk/*.conf;
```

The following example configuration from the [Scorekeep sample application](https://github.com/aws-samples/eb-java-scorekeep/) 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**  

```
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;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

  include       conf.d/*.conf;

  map $http_upgrade $connection_upgrade {
      default     "upgrade";
  }

  server {
      listen        80 default_server;
      root /var/app/current/public;

      location / {
      }git pull
      

      location /api {
          proxy_pass          http://127.0.0.1:5000;
          proxy_http_version  1.1;

          proxy_set_header    Connection          $connection_upgrade;
          proxy_set_header    Upgrade             $http_upgrade;
          proxy_set_header    Host                $host;
          proxy_set_header    X-Real-IP           $remote_addr;
          proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
      }

      access_log    /var/log/nginx/access.log main;

      client_header_timeout 60;
      client_body_timeout   60;
      keepalive_timeout     60;
      gzip                  off;
      gzip_comp_level       4;

      # Include the Elastic Beanstalk generated locations
      include conf.d/elasticbeanstalk/01_static.conf;
      include conf.d/elasticbeanstalk/healthd.conf;
  }
}
```

# Adding an Amazon RDS DB instance to your Java Elastic Beanstalk environment
<a name="java-rds"></a>

This topic provides instructions to create an Amazon RDS using the Elastic Beanstalk console. You can use an Amazon Relational Database Service (Amazon RDS) DB instance to store data that your application gathers and modifies. The database can be attached to your environment and managed by Elastic Beanstalk, or created and managed externally.

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. 

**To add a DB instance to your environment**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Database** configuration category, choose **Edit**.

1. Choose a DB engine, and enter a user name and password.

1. To save the changes choose **Apply** at the bottom of the page.

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:


| Property name | Description | Property value | 
| --- | --- | --- | 
|  `RDS_HOSTNAME`  |  The hostname of the DB instance.  |  On the **Connectivity & security** tab on the Amazon RDS console: **Endpoint**.  | 
|  `RDS_PORT`  |  The port where the DB instance accepts connections. The default value varies among DB engines.  |  On the **Connectivity & security** tab on the Amazon RDS console: **Port**.  | 
|  `RDS_DB_NAME`  |  The database name, **ebdb**.  |  On the **Configuration** tab on the Amazon RDS console: **DB Name**.  | 
|  `RDS_USERNAME`  |  The username that you configured for your database.  |  On the **Configuration** tab on the Amazon RDS console: **Master username**.  | 
|  `RDS_PASSWORD`  |  The password that you configured for your database.  |  Not available for reference in the Amazon RDS console.  | 

For more information about configuring an internal DB instance, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md). For instructions on configuring an external database for use with Elastic Beanstalk, see [Using Elastic Beanstalk with Amazon RDS](AWSHowTo.RDS.md).

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.

**Topics**
+ [

## Downloading the JDBC driver
](#java-rds-drivers)
+ [

## Connecting to a database (Java SE platforms)
](#java-rds-javase)
+ [

## Connecting to a database (Tomcat platforms)
](#java-rds-tomcat)
+ [

## Troubleshooting database connections
](#create_deploy_Java.rds.troubleshooting)

## Downloading the JDBC driver
<a name="java-rds-drivers"></a>

You will need the JAR file of the JDBC driver for the DB engine that you choose. Save the JAR file in your source code and include it in your classpath when you compile the class that creates connections to the database.

You can find the latest driver for your DB engine in the following locations:
+ **MySQL** – [MySQL Connector/J](https://dev.mysql.com/downloads/connector/j/)
+ **Oracle SE-1** – [Oracle JDBC Driver](http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html)
+ **Postgres** – [PostgreSQL JDBC Driver](https://jdbc.postgresql.org/)
+ **SQL Server** – [Microsoft JDBC Driver](https://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx)

To use the JDBC driver, call `Class.forName()` to load it before creating the connection with `DriverManager.getConnection()` in your code.

JDBC uses a connection string in the following format:

```
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:
+ `mysql` for MySQL
+ `postgresql` for PostgreSQL
+ `oracle:thin` for Oracle Thin
+ `oracle:oci` for Oracle OCI
+ `oracle:oci8` for Oracle OCI 8
+ `oracle:kprb` for Oracle KPRB
+ `sqlserver` for SQL Server

## Connecting to a database (Java SE platforms)
<a name="java-rds-javase"></a>

In a Java SE environment, use `System.getenv()` to read the connection variables from the environment. The following example code shows a class that creates a connection to a PostgreSQL database.

```
private static Connection getRemoteConnection() {
    if (System.getenv("RDS_HOSTNAME") != null) {
      try {
      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;
  }
```

## Connecting to a database (Tomcat platforms)
<a name="java-rds-tomcat"></a>

In a Tomcat environment, environment properties are provided as system properties that are accessible with `System.getProperty()`.

The following example code shows a class that creates a connection to a PostgreSQL database.

```
private static Connection getRemoteConnection() {
    if (System.getProperty("RDS_HOSTNAME") != null) {
      try {
      Class.forName("org.postgresql.Driver");
      String dbName = System.getProperty("RDS_DB_NAME");
      String userName = System.getProperty("RDS_USERNAME");
      String password = System.getProperty("RDS_PASSWORD");
      String hostname = System.getProperty("RDS_HOSTNAME");
      String port = System.getProperty("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;
  }
```

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.

```
<%@ page import="java.sql.*" %>
<%
  // Read RDS connection information from the environment
  String dbName = System.getProperty("RDS_DB_NAME");
  String userName = System.getProperty("RDS_USERNAME");
  String password = System.getProperty("RDS_PASSWORD");
  String hostname = System.getProperty("RDS_HOSTNAME");
  String port = System.getProperty("RDS_PORT");
  String jdbcUrl = "jdbc:mysql://" + hostname + ":" +
    port + "/" + dbName + "?user=" + userName + "&password=" + password;
  
  // Load the JDBC driver
  try {
    System.out.println("Loading driver...");
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver loaded!");
  } catch (ClassNotFoundException e) {
    throw new RuntimeException("Cannot find the driver in the classpath!", e);
  }

  Connection conn = null;
  Statement setupStatement = null;
  Statement readStatement = null;
  ResultSet resultSet = null;
  String results = "";
  int numresults = 0;
  String statement = null;

  try {
    // Create connection to RDS DB instance
    conn = DriverManager.getConnection(jdbcUrl);
    
    // Create a table and write two rows
    setupStatement = conn.createStatement();
    String createTable = "CREATE TABLE Beanstalk (Resource char(50));";
    String insertRow1 = "INSERT INTO Beanstalk (Resource) VALUES ('EC2 Instance');";
    String insertRow2 = "INSERT INTO Beanstalk (Resource) VALUES ('RDS Instance');";
    
    setupStatement.addBatch(createTable);
    setupStatement.addBatch(insertRow1);
    setupStatement.addBatch(insertRow2);
    setupStatement.executeBatch();
    setupStatement.close();
    
  } catch (SQLException ex) {
    // Handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
  } finally {
    System.out.println("Closing the connection.");
    if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
  }

  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();

  } catch (SQLException ex) {
    // Handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
  } finally {
       System.out.println("Closing the connection.");
      if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
  }
%>
```

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>
```

## Troubleshooting database connections
<a name="create_deploy_Java.rds.troubleshooting"></a>

**Try Amazon Q Developer CLI for AI-assisted troubleshooting**  
 Amazon Q Developer CLI can help you troubleshoot environment issues quickly. The Q CLI provides solutions by checking environment status, reviewing events, analyzing logs, and asking clarifying questions. For more information and detailed walkthroughs, see [Troubleshooting Elastic Beanstalk Environments with Amazon Q Developer CLI ](https://aws.amazon.com/blogs/devops/troubleshooting-elastic-beanstalk-environments-with-amazon-q-developer-cli/) in the AWS blogs.

If you run into issues connecting to a database from within your application, review the web container log and database.

### Reviewing logs
<a name="create_deploy_Java.rds.troubleshooting.logs"></a>

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.

### Connecting to an RDS DB Instance
<a name="create_deploy_Java.rds.troubleshooting.connecting"></a>

 You can connect directly to the RDS DB instance in your Elastic Beanstalk environment by using the MySQL client application. 

 First, open the security group to your RDS DB instance to allow traffic from your computer. 

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Database** configuration category, choose **Edit**.

1. Next to **Endpoint**, choose the Amazon RDS console link.

1. 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](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC).

1. In **Security group details**, choose the **Inbound** tab, and then choose **Edit**.

1. Add a rule for MySQL (port 3306) that allows traffic from your IP address, specified in CIDR format.

1. 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. 

```
// Install MySQL client
$ sudo apt-get install mysql-client-5.5
...
// Connect to database
$ mysql -h aas839jo2vwhwb.cnubrrfwfka8.us-west-2.rds.amazonaws.com -u username -ppassword ebdb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 117
Server version: 5.5.40-log Source distribution
...
```

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. 

```
mysql> SELECT Resource from Beanstalk;
+--------------+
| Resource     |
+--------------+
| EC2 Instance |
| RDS Instance |
+--------------+
2 rows in set (0.01 sec)
```

# Java tools and resources
<a name="create_deploy_Java.resources"></a>

There are several places you can go to get additional help when developing your Java applications.


****  

|  Resource  |  Description  | 
| --- | --- | 
|  [The AWS Java Development Forum](https://forums.aws.amazon.com/forum.jspa?forumID=70)  | Post your questions and get feedback.  | 
|  [Java Developer Center](https://aws.amazon.com/java/)  | One-stop shop for sample code, documentation, tools, and additional resources. | 