How to set up an RDS database for Rails on EC2

This is part 5 of my series on how to deploy a Ruby on Rails application to AWS. If you found this page via search, I recommend starting from the beginning.

Overview of this step

This is the final step. First we’ll create an RDS database in the AWS console, then we’ll create our actual Rails application database.

Just before we cross the finish line we’ll precompile our assets as the very last step.

1. Create the database

Go to the RDS page in your AWS console. Click Create database.

On the next page, choose PostgreSQL.

Scroll down and select Free tier. If you’re following along with my hello_world repo, set the database name to hello-world. For a password, put whatever you want.

Leave everything else at its default. Click Create database at the bottom.

2. Connect Rails with your RDS database

If you’re using my hello_world app, make note of what’s in config/database.yml under production. If you’re using your own app, set the production section of your app’s config/database.yml to match what’s below.

The above config code reads environment variable values. Elsewhere we need to set environment variable values.

In our nginx config file, /etc/nginx/sites-enabled/default, we need to add the following, under the server section. This will allow nginx to read our env var values.

If you don’t know where to find your endpoint URL, it can be found under Connectivity & security on the detail page for your RDS database, as pictured below.

In addition to nginx being able to read our env var values, we also need the terminal to be aware of our env var values. Unfortunately I don’t know of a way to satisfy both nginx and the terminal in a way that doesn’t involve duplication. To bring the env var values into the terminal, add the following to /home/ubuntu/.bash_profile.

Now execute ~/.bash_profile and echo a value to verify that the env vars have been successfully set.

3. Create the app’s database

Even though we’ve created the RDS database, we still need to create the actual Rails database instance. (The RDS database is more like a container.)

Unfortunately this won’t work. We get an error about Yarn packages. We need to address this, and in order to address this we need to install Yarn.

And now, finally, we can actually create the database.

4. Precompile assets

Before we check what’s in the browser, let’s tail the logs.

If the database steps were successful, we should now be past any database-related errors. The error we see should be related to assets not being precompiled.

This is easily fixed by running the rails assets:precompile command.

5. Verify success

When you visit your EC2 instance’s URL in the browser, it should now actually work!

If you try to add a person via the form, that should actually work too!

Congratulations. You now have a working Rails application on AWS.