

# Deploying Ruby applications with Elastic Beanstalk
<a name="create_deploy_Ruby"></a>

This chapter provides instructions for configuring and deploying your Ruby web application to AWS Elastic Beanstalk. Elastic Beanstalk makes it easy to deploy, manage, and scale your Ruby 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.

This chapter also provides step-by-step instructions for deploying a sample application to Elastic Beanstalk using the EB CLI, and then updating the application to use the [Rails](http://rubyonrails.org/) and [Sinatra](http://www.sinatrarb.com/) web application frameworks.

The topics in this chapter assume that you have some knowledge of Elastic Beanstalk environments. If you haven't used Elastic Beanstalk before, try the [getting started tutorial](GettingStarted.md) to learn the basics.

**Topics**
+ [Setting up your Ruby development environment for Elastic Beanstalk](ruby-development-environment.md)
+ [Using the Elastic Beanstalk Ruby platform](create_deploy_Ruby.container.md)
+ [Deploying a rails application to Elastic Beanstalk](ruby-rails-tutorial.md)
+ [Deploying a sinatra application to Elastic Beanstalk](ruby-sinatra-tutorial.md)
+ [Adding an Amazon RDS DB instance to your Ruby Elastic Beanstalk environment](create_deploy_Ruby.rds.md)

# Setting up your Ruby development environment for Elastic Beanstalk
<a name="ruby-development-environment"></a>

This chapter provides instructions to set up a Ruby 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. 

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.

**Topics**
+ [Installing Ruby](#ruby-development-environment-ruby)
+ [Installing the AWS SDK for Ruby](#ruby-development-environment-sdk)
+ [Installing an IDE or text editor](#ruby-development-environment-ide)

## Installing Ruby
<a name="ruby-development-environment-ruby"></a>

Install GCC if you don't have a C compiler. On Ubuntu, use `apt`.

```
~$ sudo apt install gcc
```

On Amazon Linux, use `yum`.

```
~$ sudo yum install gcc
```

Install RVM to manage Ruby language installations on your machine. Use the commands at [rvm.io](https://rvm.io/) to get the project keys and run the installation script.

```
~$ gpg2 --recv-keys key1 key2
~$ curl -sSL https://get.rvm.io | bash -s stable
```

This script installs RVM in a folder named `.rvm` in your user directory, and modifies your shell profile to load a setup script whenever you open a new terminal. Load the script manually to get started.

```
~$ source ~/.rvm/scripts/rvm
```

Use `rvm get head` to get the latest version.

```
~$ rvm get head
```

View the available versions of Ruby.

```
~$ rvm list known
```

Check [Ruby](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.ruby) in the *AWS Elastic Beanstalk Platforms* document to find the latest version of Ruby available on an Elastic Beanstalk platform. Install that version.

```
~$ rvm install 3.2
```

Test your Ruby installation.

```
~$ ruby --version
```

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

If you need to manage AWS resources from within your application, install the AWS SDK for Ruby. For example, with the SDK for Ruby, you can use Amazon DynamoDB (DynamoDB) to store user and session information without creating a relational database.

Install the SDK for Ruby and its dependencies with the `gem` command.

```
$ gem install aws-sdk
```

Visit the [AWS SDK for Ruby homepage](https://aws.amazon.com/sdk-for-ruby/) for more information and installation instructions.

## Installing an IDE or text editor
<a name="ruby-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 Ruby development, try Aptana and RubyMine and see which works best for you.
+  [Install Aptana](https://github.com/aptana/studio3) 
+  [RubyMine](https://www.jetbrains.com/ruby/) 

**Note**  
An IDE might add files to your project folder that you might not want to commit to source control. To prevent committing these files to source control, use `.gitignore` or your source control tool's equivalent.

If you just want to begin coding and don't need all of the features of an IDE, consider [installing Sublime Text](http://www.sublimetext.com/).

# Using the Elastic Beanstalk Ruby platform
<a name="create_deploy_Ruby.container"></a>

This topic describes how to configure, build, and run your Ruby applications on Elastic Beanstalk.

AWS Elastic Beanstalk supports a number of platform branches for different versions of the Ruby programming language. See [Ruby](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.ruby) in the *AWS Elastic Beanstalk Platforms* document for a full list.

The Ruby web application can run behind an NGINX proxy server under a Puma application server. If you use RubyGems, you can include a [`Gemfile`](ruby-platform-gemfile.md) in your source bundle to install packages during deployment.

**Application server configuration**  
Elastic Beanstalk installs the Puma application server based on the Ruby platform branch that you choose when you create your environment. For more information about the components provided with the Ruby platform versions, see [Supported Platforms](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.ruby) in the *AWS Elastic Beanstalk Platforms* guide.

You can configure your application with your own provided Puma server. This provides the option to use a version of Puma other than the one pre-installed with the Ruby platform branch. You can also configure your application to use a different application server, such as Passenger. To do so, you must include and customize a `Gemfile` in your deployment. You're also required to configure a `Procfile` to start the application server. For more information see *[Configuring the application process with a Procfile](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ruby-platform-procfile.html)**.*

**Other configuration options**  
Elastic Beanstalk provides [configuration options](command-options.md) that you can use to customize the software that runs on the Amazon Elastic Compute Cloud (Amazon EC2) instances in your Elastic Beanstalk environment. You can configure environment variables needed by your application, enable log rotation to Amazon S3, and map folders in your application source that contain static files to paths served by the proxy server. The platform also predefines some common environment variables related to Rails and Rack for ease of discovery and use.

Configuration options are available in the Elastic Beanstalk console for [modifying the configuration of a running environment](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.

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

## Configuring your Ruby environment
<a name="create-deploy_Ruby.container.CON"></a>

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 access the software configuration settings for 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 **Updates, monitoring, and logging** configuration category, choose **Edit**.

### Log options
<a name="create_deploy_Ruby.container.console.logoptions"></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="create_deploy_Ruby.container.console.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).

By default, the proxy server in a Ruby environment is configured to serve static files as follows:
+ Files in the `public` folder are served from the `/public` path and the domain root (`/` path).
+ Files in the `public/assets` subfolder are served from the `/assets` path.

The following examples illustrate how the default configuration works:
+ If your application source contains a file named `logo.png` in a folder named `public`, the proxy server serves it to users from `subdomain.elasticbeanstalk.com/public/logo.png` and `subdomain.elasticbeanstalk.com/logo.png`.
+ If your application source contains a file named `logo.png` in a folder named `assets` inside the `public` folder, the proxy server serves it from `subdomain.elasticbeanstalk.com/assets/logo.png`.

You can configure additional mappings for static files. For more information, see [Ruby configuration namespaces](#ruby-namespaces) later in this topic.

**Note**  
For platform versions prior to *Ruby 2.7 AL2 version 3.3.7*, the default Elastic Beanstalk nginx proxy server configuration doesn't support serving static files from the domain root (`subdomain.elasticbeanstalk.com/`). This platform version was released on October 21, 2021. For more information see [New platform versions - Ruby](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2021-10-21-linux.html#release-2021-10-21-linux.platforms.ruby) in the *AWS Elastic Beanstalk Release Notes*.

### Environment properties
<a name="create_deploy_Ruby.env.console.ruby.envprops"></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.

The Ruby platform defines the following properties for environment configuration:
+  **BUNDLE\$1WITHOUT** – A colon-separated list of groups to ignore when [installing dependencies](http://bundler.io/bundle_install.html) from a [Gemfile](http://bundler.io/v1.15/man/gemfile.5.html).
+ **BUNDLER\$1DEPLOYMENT\$1MODE** – Set to `true` (the default) to install dependencies in [deployment mode](https://bundler.io/man/bundle-install.1.html#DEPLOYMENT-MODE) using Bundler. Set to `false` to run `bundle install` in development mode.
**Note**  
This environment property isn't defined on Amazon Linux AMI Ruby platform branches (preceding Amazon Linux 2).
+  **RAILS\$1SKIP\$1ASSET\$1COMPILATION** – Set to `true` to skip running [http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets](http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets) during deployment.
+  **RAILS\$1SKIP\$1MIGRATIONS** – Set to `true` to skip running [http://guides.rubyonrails.org/active_record_migrations.html#running-migrations](http://guides.rubyonrails.org/active_record_migrations.html#running-migrations) during deployment.
+  **RACK\$1ENV** – Specify the environment stage for Rack. For example, `development`, `production`, or `test`.

Inside the Ruby environment running in Elastic Beanstalk, environment variables are accessible using the `ENV` object. For example, you could read a property named `API_ENDPOINT` to a variable with the following code:

```
endpoint = ENV['API_ENDPOINT']
```

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

## Ruby configuration namespaces
<a name="ruby-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*.

You can use the `aws:elasticbeanstalk:environment:proxy:staticfiles` namespace to configure the environment proxy to serve static files. You define mappings of virtual paths to application directories.

The Ruby platform doesn't define any platform-specific namespaces. Instead, it defines environment properties for common Rails and Rack options.

The following configuration file specifies a static files option that maps a directory named `staticimages` to the path `/images`, sets each of the platform defined environment properties, and sets an additional environment property named `LOGGING`.

**Example .ebextensions/ruby-settings.config**  

```
option_settings:
  aws:elasticbeanstalk:environment:proxy:staticfiles:
    /images: staticimages
  aws:elasticbeanstalk:application:environment:
    BUNDLE_WITHOUT: test
    BUNDLER_DEPLOYMENT_MODE: true
    RACK_ENV: development
    RAILS_SKIP_ASSET_COMPILATION: true
    RAILS_SKIP_MIGRATIONS: true
    LOGGING: debug
```

**Note**  
The `BUNDLER_DEPLOYMENT_MODE` environment property and the `aws:elasticbeanstalk:environment:proxy:staticfiles` namespace aren't defined on Amazon Linux AMI Ruby platform branches (preceding Amazon Linux 2).

Elastic Beanstalk provides many configuration options for customizing your environment. In addition to configuration files, you can also set configuration options using the console, saved configurations, the EB CLI, or the AWS CLI. See [Configuration options](command-options.md) for more information.

# Installing packages with a Gemfile on Elastic Beanstalk
<a name="ruby-platform-gemfile"></a>

To use RubyGems to install packages that your application requires, include a `Gemfile` file in the root of your project source.

**Example Gemfile**  

```
source "https://rubygems.org"
gem 'sinatra'
gem 'json'
gem 'rack-parser'
```

When a `Gemfile` file is present, Elastic Beanstalk runs `bundle install` to install dependencies. For more information, see the [Gemfiles](https://bundler.io/man/gemfile.5.html) and [Bundle](https://bundler.io/man/bundle.1.html) pages on the Bundler.io website.

**Note**  
You can use a different version of Puma besides the default that's pre-installed with the Ruby platform. To do so, include an entry in a `Gemfile` that specifies the version. You can also specify a different application server, such as Passenger, by using a customized `Gemfile`.  
For both of these cases you're required to configure a `Procfile` to start the application server.  
For more information see *[Configuring the application process with a Procfile](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ruby-platform-procfile.html)**.* 

# Configuring the application process with a Procfile on Elastic Beanstalk.
<a name="ruby-platform-procfile"></a>

To specify the command that starts your Ruby application, include a file called `Procfile` at the root of your source bundle.

**Note**  
Elastic Beanstalk doesn't support this feature on Amazon Linux AMI Ruby platform branches (preceding Amazon Linux 2). Platform branches with names containing *with Puma* or *with Passenger*, regardless of their Ruby versions, precede Amazon Linux 2 and don't support the `Procfile` feature.

For details about writing and using a `Procfile`, see [Buildfile and Procfile](platforms-linux-extend.build-proc.md).

When you don't provide a `Procfile`, Elastic Beanstalk generates a default `Procfile`. If your `Gemfile` includes Puma, Elastic Beanstalk assumes you want to use your provided version of Puma and generates the following default `Procfile`.

```
web: bundle exec puma -C /opt/elasticbeanstalk/config/private/pumaconf.rb
```

If your `Gemfile` does not include Puma, Elastic Beanstalk assumes you're using the pre-installed Puma application server and generates the following default `Procfile`. On Amazon Linux 2 Ruby platform branches, Elastic Beanstalk always generates the following default `Procfile` if you don't provide a `Procfile`.

```
web: puma -C /opt/elasticbeanstalk/config/private/pumaconf.rb
```

**Note**  
On [October 10, 2024](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2024-10-10-al2-10-2024-retire.html), the last Ruby Amazon Linux 2 platform branches were retired. All currently [supported Ruby platform branches](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.ruby) are based on Amazon Linux 2023. For information about migration, see [Migration from Amazon Linux 2 to Amazon Linux 2023](using-features.migration-al.generic.from-al2.md).

If you want to use the Passenger application server, use the following example files to configure your Ruby environment to install and use Passenger.

1. Use this example file to install Passenger.  
**Example Gemfile**  

   ```
   source 'https://rubygems.org'
   gem 'passenger'
   ```

1. Use this example file to instruct Elastic Beanstalk to start Passenger.  
**Example Procfile**  

   ```
   web: bundle exec passenger start /var/app/current --socket /var/run/puma/my_app.sock
   ```

**Note**  
You don't have to change anything in the configuration of the nginx proxy server to use Passenger. To use other application servers, you might need to customize the nginx configuration to properly forward requests to your application.

# Deploying a rails application to Elastic Beanstalk
<a name="ruby-rails-tutorial"></a>

Rails is an open source, model-view-controller (MVC) framework for Ruby. This tutorial walks you through the process of generating a Rails application and deploying it to an AWS Elastic Beanstalk environment.

**Topics**
+ [Prerequisites](#ruby-rails-tutorial-prereqs)
+ [Basic Elastic Beanstalk knowledge](#ruby-rails-tutorial-prereqs-basic)
+ [Launch an Elastic Beanstalk environment](#ruby-rails-tutorial-launch)
+ [Install rails and generate a website](#ruby-rails-tutorial-generate)
+ [Configure rails settings](#ruby-rails-tutorial-configure)
+ [Deploy your application](#ruby-rails-tutorial-deploy)
+ [Cleanup](#ruby-rails-tutorial-cleanup)
+ [Next steps](#ruby-rails-tutorial-nextsteps)

## Prerequisites
<a name="ruby-rails-tutorial-prereqs"></a>

## Basic Elastic Beanstalk knowledge
<a name="ruby-rails-tutorial-prereqs-basic"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

### Command line
<a name="ruby-rails-tutorial-prereqs-cmdline"></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.

### Rails dependencies
<a name="ruby-rails-tutorial-prereqs-railsreqs"></a>

The Rails framework 6.1.4.1 has the following dependencies. Be sure you have all of them installed.
+ **Ruby 2.5.0 or newer** – For installation instructions, see [Setting up your Ruby development environment for Elastic Beanstalk](ruby-development-environment.md).

  In this tutorial we use Ruby 3.0.2 and the corresponding Elastic Beanstalk platform version.
+ **Node.js** – For installation instructions, see [Installing Node.js via package manager](https://nodejs.org/en/download/package-manager/).
+ **Yarn** – For installation instructions, see [Installation](https://yarnpkg.com/lang/en/docs/install/) on the *Yarn* website.

## Launch an Elastic Beanstalk environment
<a name="ruby-rails-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **Ruby** platform and accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using 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.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **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*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Install rails and generate a website
<a name="ruby-rails-tutorial-generate"></a>

Install Rails and its dependencies with the `gem` command.

```
~$ gem install rails
Fetching: concurrent-ruby-1.1.9.gem
Successfully installed concurrent-ruby-1.1.9
Fetching: rack-2.2.3.gem
Successfully installed rack-2.2.3
...
```

Test your Rails installation.

```
~$ rails --version
Rails 6.1.4.1
```

Use `rails new` with the name of the application to create a new Rails project.

```
~$ rails new ~/eb-rails
```

Rails creates a directory with the name specified, generates all of the files needed to run a sample project locally, and then runs bundler to install all of the dependencies (Gems) defined in the project's Gemfile.

**Note**  
This process installs the latest Puma version for the project. This version might be different from the version that Elastic Beanstalk provides on the Ruby platform version of your environment. To see the Puma versions provided by Elastic Beanstalk, see [Ruby Platform History](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platform-history-ruby.html) in the *AWS Elastic Beanstalk Platforms guide*. For more information about the latest Puma version, see the [Puma.io](http://puma.io) website. If there’s a mismatch between the two Puma versions, use one of the following options:  
Use the Puma version installed by the prior `rails new` command. In this case you must add a `Procfile` for the platform to use your own provided Puma server version. For more information, see [Configuring the application process with a Procfile on Elastic Beanstalk.](ruby-platform-procfile.md).
Update the Puma version to be consistent with the version pre-installed on your environment’s Ruby platform version. To do so, modify the Puma version in the [Gemfile](ruby-platform-gemfile.md#ruby-platform-gemfile.title) located in the root of your project source directory. Then run `bundle update`. For more information see the [bundle update](https://bundler.io/man/bundle-update.1.html) page on the Bundler.io website. 

Test your Rails installation by running the default project locally.

```
~$ cd eb-rails
~/eb-rails$ rails server
=> Booting Puma
=> Rails 6.1.4.1 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.5.2 (ruby 3.0.2-p107) ("Zawgyi")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 77857
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
...
```

Open `http://localhost:3000` in a web browser to see the default project in action.

![\[The default rails site development page.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/ruby-rails-default.png)


This page is only visible in development mode. Add some content to the front page of the application to support production deployment to Elastic Beanstalk. Use `rails generate` to create a controller, route, and view for your welcome page. 

```
~/eb-rails$ rails generate controller WelcomePage welcome
      create  app/controllers/welcome_page_controller.rb
       route  get 'welcome_page/welcome'
      invoke  erb
      create    app/views/welcome_page
      create    app/views/welcome_page/welcome.html.erb
      invoke  test_unit
      create    test/controllers/welcome_page_controller_test.rb
      invoke  helper
      create    app/helpers/welcome_page_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/welcome_page.coffee
      invoke    scss
      create      app/assets/stylesheets/welcome_page.scss.
```

This gives you all you need to access the page at `/welcome_page/welcome`. Before you publish the changes, however, change the content in the view and add a route to make this page appear at the top level of the site. 

Use a text editor to edit the content in `app/views/welcome_page/welcome.html.erb`. For this example, you'll use `cat` to simply overwrite the content of the existing file. 

**Example app/views/welcome\$1page/welcome.html.erb**  

```
<h1>Welcome!</h1>
<p>This is the front page of my first Rails application on Elastic Beanstalk.</p>
```

 Finally, add the following route to `config/routes.rb`: 

**Example config/routes.rb**  

```
Rails.application.routes.draw do
  get 'welcome_page/welcome'
  root 'welcome_page#welcome'
```

This tells Rails to route requests to the root of the website to the welcome page controller's welcome method, which renders the content in the welcome view (`welcome.html.erb`).

In order for Elastic Beanstalk to successfully deploy the application on the Ruby platform, we need to update `Gemfile.lock`. Some dependencies of `Gemfile.lock ` might be platform specific. Therefore, we need to add **platform ruby** to `Gemfile.lock` so that all required dependencies are installed with the deployment.

**Example**  

```
~/eb-rails$ bundle lock --add-platform ruby
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Writing lockfile to /Users/janedoe/EBDPT/RubyApps/eb-rails-doc-app/Gemfile.lock
```

## Configure rails settings
<a name="ruby-rails-tutorial-configure"></a>

Use the Elastic Beanstalk console to configure Rails with environment properties. Set the `SECRET_KEY_BASE` environment property to a string of up to 256 alphanumeric characters.

Rails uses this property to create keys. Therefore you should keep it a secret and not store it in source control in plain text. Instead, you provide it to Rails code on your environment through an environment property.

**To configure environment variables 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. Scroll down to **Runtime environment variables**.

1. Select **Add environment variable**.

1. For **Source** select **Plain text**.
**Note**  
The **Secrets Manager** and **SSM Parameter Store** values in the drop-down are for configuring environment variables as secrets to store sensitive data, such as credentials and API keys. For more information, see [Using Elastic Beanstalk with AWS Secrets Manager and AWS Systems Manager Parameter Store](AWSHowTo.secrets.md). 

1. Enter the **Environment variable name** and **Environment variable value** pairs.

1. If you need to add more variables repeat **Step 6** through **Step 8**.

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

Now you're ready to deploy the site to your environment.

## Deploy your application
<a name="ruby-rails-tutorial-deploy"></a>

Create a [source bundle](applications-sourcebundle.md) containing the files created by Rails. The following command creates a source bundle named `rails-default.zip`.

```
~/eb-rails$ zip ../rails-default.zip -r * .[^.]*
```

Upload the source bundle to Elastic Beanstalk to deploy Rails to your environment.

**To deploy a source bundle**

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. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Cleanup
<a name="ruby-rails-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the 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. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

## Next steps
<a name="ruby-rails-tutorial-nextsteps"></a>

For more information about Rails, visit [rubyonrails.org](https://rubyonrails.org/).

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Deploying a sinatra application to Elastic Beanstalk
<a name="ruby-sinatra-tutorial"></a>

This walkthrough shows how to deploy a simple [Sinatra](http://www.sinatrarb.com/) web application to AWS Elastic Beanstalk.

## Prerequisites
<a name="ruby-sinatra-tutorial-prereqs"></a>

This tutorial assumes you have knowledge of the basic Elastic Beanstalk operations and the Elastic Beanstalk console. If you haven't already, follow the instructions in [Learn how to get started with Elastic Beanstalk](GettingStarted.md) to launch your first Elastic Beanstalk environment.

To follow the procedures in this guide, you will need a command line terminal or shell to run commands. Commands are shown in listings preceded by a prompt symbol (\$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.

Sinatra 2.1.0 requires Ruby 2.3.0 or newer. In this tutorial we use Ruby 3.0.2 and the corresponding Elastic Beanstalk platform version. Install Ruby by following the instructions at [Setting up your Ruby development environment for Elastic Beanstalk](ruby-development-environment.md).

## Launch an Elastic Beanstalk environment
<a name="ruby-sinatra-tutorial-launch"></a>

Use the Elastic Beanstalk console to create an Elastic Beanstalk environment. Choose the **Ruby** platform and accept the default settings and sample code.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console using 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.

1. For **Application code**, choose **Sample application**.

1. Choose **Review and launch**.

1. Review the available options. Choose the available option you want to use, and when you're ready, choose **Create app**.

Environment creation takes about 5 minutes and creates the following resources:
+ **EC2 instance** – An Amazon Elastic Compute Cloud (Amazon EC2) virtual machine configured to run web apps on the platform that you choose.

  Each platform runs a specific set of software, configuration files, and scripts to support a specific language version, framework, web container, or combination of these. Most platforms use either Apache or NGINX as a reverse proxy that sits in front of your web app, forwards requests to it, serves static assets, and generates access and error logs.
+ **Instance security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the load balancer reach the EC2 instance running your web app. By default, traffic isn't allowed on other ports.
+ **Load balancer** – An Elastic Load Balancing load balancer configured to distribute requests to the instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet.
+ **Load balancer security group** – An Amazon EC2 security group configured to allow inbound traffic on port 80. This resource lets HTTP traffic from the internet reach the load balancer. By default, traffic isn't allowed on other ports.
+ **Auto Scaling group** – An Auto Scaling group configured to replace an instance if it is terminated or becomes unavailable.
+ **Amazon S3 bucket** – A storage location for your source code, logs, and other artifacts that are created when you use Elastic Beanstalk.
+ **Amazon CloudWatch alarms** – Two CloudWatch alarms that monitor the load on the instances in your environment and that are triggered if the load is too high or too low. When an alarm is triggered, your Auto Scaling group scales up or down in response.
+ **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*.
**Domain security**  
To augment the security of your Elastic Beanstalk applications, the *elasticbeanstalk.com* domain is registered in the [Public Suffix List (PSL)](https://publicsuffix.org/).  
If you ever need to set sensitive cookies in the default domain name for your Elastic Beanstalk applications, we recommend that you use cookies with a `__Host-` prefix for increased security. This practice defends your domain against cross-site request forgery attempts (CSRF). For more information see the [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) page in the Mozilla Developer Network.

All of these resources are managed by Elastic Beanstalk. When you terminate your environment, Elastic Beanstalk terminates all the resources that it contains.

**Note**  
The Amazon S3 bucket that Elastic Beanstalk creates is shared between environments and is not deleted during environment termination. For more information, see [Using Elastic Beanstalk with Amazon S3](AWSHowTo.S3.md).

## Write a basic sinatra website
<a name="ruby-sinatra-tutorial-generate"></a>

**To create and deploy a sinatra application**

1. Create a configuration file named **config.ru** with the following contents.  
**Example config.ru**  

   ```
   require './helloworld'
   run Sinatra::Application
   ```

1. Create a Ruby code file named **helloworld.rb** with the following contents.  
**Example helloworld.rb**  

   ```
   require 'sinatra'
   get '/' do
     "Hello World!"
   end
   ```

1. Create a **Gemfile** with the following contents.  
**Example Gemfile**  

   ```
   source 'https://rubygems.org'
   gem 'sinatra'
   gem 'puma'
   ```

1. Run bundle install to generate the `Gemfile.lock`  
**Example**  

   ```
   ~/eb-sinatra$ bundle install
   Fetching gem metadata from https://rubygems.org/....
   Resolving dependencies...
   Using bundler 2.2.22
   Using rack 2.2.3
   ...
   ```

1. In order for Elastic Beanstalk to successfully deploy the application on the Ruby platform, we need to update `Gemfile.lock`. Some dependencies of `Gemfile.lock ` might be platform specific. Therefore, we need to add **platform ruby** to `Gemfile.lock` so that all required dependencies are installed with the deployment.  
**Example**  

   ```
   ~/eb-sinatra$ bundle lock --add-platform ruby
   Fetching gem metadata from https://rubygems.org/....
   Resolving dependencies...
   Writing lockfile to /Users/janedoe/EBDPT/RubyApps/eb-sinatra/Gemfile.lock
   ```

1. Create a Procfile with the following contents.  
**Example Procfile**  

   ```
   web: bundle exec puma -C /opt/elasticbeanstalk/config/private/pumaconf.rb
   ```

## Deploy your application
<a name="ruby-sinatra-tutorial-deploy"></a>

Create a [source bundle](applications-sourcebundle.md) containing the your source files. The following command creates a source bundle named `sinatra-default.zip`.

```
~/eb-sinatra$ zip ../sinatra-default.zip -r * .[^.]*
```

Upload the source bundle to Elastic Beanstalk to deploy Sinatra to your environment.

**To deploy a source bundle**

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. On the environment overview page, choose **Upload and deploy**.

1. Use the on-screen dialog box to upload the source bundle.

1. Choose **Deploy**.

1. When the deployment completes, you can choose the site URL to open your website in a new tab.

## Cleanup
<a name="ruby-sinatra-tutorial-cleanup"></a>

After you finish working with the demo code, you can terminate your environment. Elastic Beanstalk deletes all related AWS resources, such as [Amazon EC2 instances](using-features.managing.ec2.md), [database instances](using-features.managing.db.md), [load balancers](using-features.managing.elb.md), security groups, and [alarms](using-features.alarms.md#using-features.alarms.title). 

Removing resources does not delete the Elastic Beanstalk application, so you can create new environments for your application at any time.

**To terminate your Elastic Beanstalk environment from the 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. Choose **Actions**, and then choose **Terminate environment**.

1. Use the on-screen dialog box to confirm environment termination.

## Next steps
<a name="ruby-sinatra-tutorial-nextsteps"></a>

For more information about Sinatra, visit [sinatrarb.com](http://sinatrarb.com/).

As you continue to develop your application, you'll probably want a way to manage environments and deploy your application without manually creating a .zip file and uploading it to the Elastic Beanstalk console. The [Elastic Beanstalk Command Line Interface](eb-cli3.md) (EB CLI) provides easy-to-use commands for creating, configuring, and deploying applications to Elastic Beanstalk environments from the command line.

Finally, if you plan on using your application in a production environment, you will want to [configure a custom domain name](customdomains.md) for your environment and [enable HTTPS](configuring-https.md) for secure connections.

# Adding an Amazon RDS DB instance to your Ruby Elastic Beanstalk environment
<a name="create_deploy_Ruby.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 gathered and modified by your application. The database can be coupled to your environment and managed by Elastic Beanstalk, or it can be created as decoupled and managed externally by another service. In these instructions the database is coupled to your environment and managed by Elastic Beanstalk. For more information about integrating an Amazon RDS with Elastic Beanstalk, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

**Topics**
+ [Adding a DB instance to your environment](#ruby-rds-create)
+ [Downloading an adapter](#ruby-rds-drivers)
+ [Connecting to a database](#ruby-rds-connect)

## Adding a DB instance to your environment
<a name="ruby-rds-create"></a>

**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 a database instance coupled with an Elastic Beanstalk environment, see [Adding a database to your Elastic Beanstalk environment](using-features.managing.db.md).

## Downloading an adapter
<a name="ruby-rds-drivers"></a>

Add the database adapter to your project's [gem file](ruby-platform-gemfile.md).

**Example Gemfile – Rails with MySQL**  

```
source 'https://rubygems.org'
gem 'puma'
gem 'rails', '~> 6.1.4', '>= 6.1.4.1'
gem 'mysql2'
```

**Common adapter gems for Ruby**
+ **MySQL** – [https://rubygems.org/gems/mysql2](https://rubygems.org/gems/mysql2) 
+ **PostgreSQL** – [https://rubygems.org/gems/pg](https://rubygems.org/gems/pg) 
+ **Oracle** – [https://rubygems.org/gems/activerecord-oracle_enhanced-adapter](https://rubygems.org/gems/activerecord-oracle_enhanced-adapter) 
+ **SQL Server** – [https://rubygems.org/gems/activerecord-sqlserver-adapter](https://rubygems.org/gems/activerecord-sqlserver-adapter) 

## Connecting to a database
<a name="ruby-rds-connect"></a>

Elastic Beanstalk provides connection information for attached DB instances in environment properties. Use `ENV['VARIABLE']` to read the properties and configure a database connection.

**Example config/database.yml – Ruby on rails database configuration (MySQL)**  

```
production:
  adapter: mysql2
  encoding: utf8
  database: <%= ENV['RDS_DB_NAME'] %>
  username: <%= ENV['RDS_USERNAME'] %>
  password: <%= ENV['RDS_PASSWORD'] %>
  host: <%= ENV['RDS_HOSTNAME'] %>
  port: <%= ENV['RDS_PORT'] %>
```