Menu
AWS Elastic Beanstalk
Developer Guide (API Version 2010-12-01)

Adding an Amazon RDS Database to Your Elastic Beanstalk Environment

With Amazon Relational Database Service (Amazon RDS), you can quickly and easily provision and maintain a database in the cloud. For more information about Amazon RDS, see http://aws.amazon.com/rds/.

This topic explains how you can use Amazon RDS and MySQL Connector/J with your Elastic Beanstalk Java application.

To use Amazon RDS from your Elastic Beanstalk application, you need to do the following:

  1. Create an Amazon RDS DB instance.

  2. Download and install MySQL Connector/J.

  3. Establish a database connection in your code by using the connectivity information for your Amazon RDS DB instance.

  4. Deploy your application to Elastic Beanstalk.

This topic walks you through the following:

  • Using a new Amazon RDS DB instance with your application

  • Using an existing Amazon RDS DB instance with your application

Creating an RDS DB Instance to Use with a Java Application

This topic walks you through creating a RDS DB instance and using it with your Java application.

  1. Open the Elastic Beanstalk console.

  2. Navigate to the management console for your environment.

  3. Choose Configuration.

  4. Under Data Tier, choose Create a new RDS database.

  5. Enter a user name and password, and then choose Apply. Elastic Beanstalk updates your environment to include the new RDS DB instance and provides connection information to the web container as environment properties.

  6. Download and install MySQL Connector/J for your development environment. For download and installation instructions, see http://dev.mysql.com/downloads/connector/j.

  7. Copy the MySQL Connector/J .jar file into the project's WebContent/WEB-INF/lib directory.

  8. Open the context (right click) menu on WebContent/WEB-INF/lib/mysql_connector_java_5.1.34_bin.jar, and choose Add to Build Path to add the library to the classpath.

  9. Test the database connection by adding the following code to the main view of your Java web application (index.jsp).

    <%@ 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) {}
      }
    %>
  10. Place the following code in the body of the html portion of the index.jsp file to display the results:

    <p>Established connection to RDS. Read first two rows: <%= results %></p>

  11. In the Package Explorer, open the context (right-click) menu, and choose Run As, Run on Server.

  12. If your project is not configured to always deploy to the same environment, choose the environment that your application is currently running on, and then choose Finish.

For more information on getting started using MySQL Connector/J to access your MySQL database, see http://dev.mysql.com/doc/connector-j/en/index.html.

Using an Existing RDS DB Instance with Java

With Amazon RDS, you can quickly and easily provision and maintain a MySQLserver instance in the cloud. This topic explains how you can use Amazon RDS and MySQL Connector/J with your Elastic Beanstalk application.

To use an existing RDS DB instance with your a Java application

  1. Create an Elastic Beanstalk environment. Do not create a new RDS DB instance with the environment.

  2. Configure your Amazon RDS DB security group to allow access from the Amazon EC2 security group used by your Elastic Beanstalk application. For instructions on how to find the name of your EC2 security group using the AWS Management Console, see Security Groups. For more information, go to the "Authorizing Network Access to an Amazon EC2 Security Group" section of Working with DB Security Groups in the Amazon Relational Database Service User Guide.

  3. Download and install MySQL Connector/J for your development environment. For download and installation instructions, see http://dev.mysql.com/downloads/connector/j.

  4. Create a Java database connectivity (JDBC) connection string that includes your RDS DB instance's public DNS name, port number, database name, and login credentials. The following example shows a JDBC connection string that connects to the employees database on an RDS instance at mydbinstance.abcdefghijkl.us-west-2.rds.example.com using port 3306, with the user name sa, and the password mypassword.

    
    jdbc:mysql://mydbinstance.abcdefghijkl.us-west-2.rds.example.com:3306/employees?user=sa&password=mypassword
  5. Set the JDBC_CONNECTION_STRING environment property in your environment configuration. For instructions, see Configuring Your AWS Elastic Beanstalk Java Environment.

  6. Retrieve the JDBC connection string from the system property passed to your server instance by Elastic Beanstalk and use MySQL Connector/J to access your Amazon RDS database. The following example shows how to retrieve the JDBC_CONNECTION_STRING custom environment property in a Java Server Page (JSP).

    <p>
        The JDBC_CONNECTION_STRING environment variable is:
        <%= System.getProperty("JDBC_CONNECTION_STRING") %>
    </p>

    For more information on getting started using the MySQL Connector/J to access your MySQL database, see http://dev.mysql.com/doc/connector-j/en/index.html.

  7. Copy the MySQL Connector/J .jar file into the Tomcat WEB-INF/lib directory.

  8. Deploy the application to your Elastic Beanstalk environment.

Note

To load the JDBC drive, you must load it explicitly using Class.forName(<driverClassName>) prior to the call to DriverManager.getConnection() in the Java code.

Troubleshooting Database Connections

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

Reviewing Logs

You can view all of 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, and 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 web page 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 above example, the application tries to create the table every time the page loads, resulting 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

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

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

  1. Open the Elastic Beanstalk console.

  2. Navigate to the management console for your environment.

  3. Choose Configuration.

  4. Under Network Tier, in the RDS section, choose Edit (the gear icon).

  5. Next to the DB endpoint, choose View in RDS Console.

  6. On the RDS Dashboard instance details page, under Security and Network, choose the security group starting with rds- next to Security Groups.

    Note

    The database might have multiple entries labelled Security Groups. Use the first, which starts with awseb, only if you have an older account that does not have a default VPC.

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

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

  9. Choose Save. The changes take effect immediately.

Return to the Elastic Beanstalk configuration details for your environment and note the endpoint. You will use the domain name to connect to the RDS DB instance.

Install the MySQL client and initiate a connection to the database on port 3306. In Windows, install MySQL Workbench from the MySQL home page and follow the prompts.

In Linux, install the MySQL client using the package manager for your distribution. The following example works on Ubuntu and other Debian derivatives:

// Install My SQL 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 have been created, and other information.

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