Skip to content Skip to sidebar Skip to footer

Building and Uploading a Rails App With Elastic Beanstalk

When writing an application, one of the major issues you have to think about is how the application will be shared with the rest of the world.

One common arroyo has been to launch on Heroku. It's easy to prepare and is fully managed. But, it's also mutual for teams to driblet Heroku afterwards. As their traffic grows, Heroku becomes too expensive and inflexible.

What if information technology were possible to deploy a new application with Heroku-like ease without giving up the flexibility and cost-savings that you go from a more general-purpose platform like AWS? It is possible, using Rubberband Beanstalk -- a service from AWS.

In this commodity, I'thou going to walk you lot through setting upwards a Rails 6 application and running it on AWS using Elasticbeanstalk as the compute base and RDS (Relational Database Service) - in item, the Postgres service - as the information store.

At the finish of this tutorial, you should be able to do the post-obit:

  1. Set up a Runway 6 app with a few routes and run it locally.
  2. Create an AWS business relationship.
  3. Gear up and deploy an app to Elasticbeanstalk using the free-tier resources.

Let's dive in.

What are Elasticbeanstalk and RDS?

To go a articulate idea of what Elasticbeanstalk is and the problem it solves, first, let'southward talk about Amazon's EC2 offering.

EC2 stands for Elastic Compute Deject two. This service allows you lot to provision VPCs, which are basically merely computers, running whichever OS you choose (e.g., Ubuntu). Your app will then live inside this computer and access its resources, such equally the file system and RAM, to deliver its tasks. In the cease, your app will run similar to how information technology runs on your local automobile, only in a machine endemic by Amazon and accessible via the internet using Amazon's infrastructure.

Now, imagine a user named Alice, who has provisioned an example on EC2. Alice volition need to do the following:

  • Set a security group to permit requests to her app.
  • Set up a load balancer.
  • SSH into the instance, set up upwardly her app and environment secrets, and and then on.

While this gives you lot total control of your machine and what and how it runs, sometimes, you want to focus on the app and not the infrastructure. This is where Elasticbeanstalk comes in.

Elasticbeanstalk provides a CLI that makes information technology easier to practice all this and will automate most of it, such as creating security groups and load balancers. While the underlying infrastructure is still EC2, a layer of abstraction is added on meridian of it, with a visual dashboard that allows you to set up environment variables, databases, and auto-scaling, equally well as obtain logs and perform other functions, in a very simple style.

What is Track?

Many tools can exist used to get a web application up and running. Usually, the library or framework you end upward using is by and large dictated past the language in which it is programmed.

If your language of choice happens to be Ruby, a pop framework you tin can choose to employ is Rails (officially called Ruby on Rails). Rails was created at Basecamp in 2003, and over the years, it has evolved into a full-featured and very mature framework that includes nigh anything you can retrieve of to build a modern spider web app.

Some of the things you can build with rail include something as unproblematic as a personal blog to something as complex equally Airbnb and Github. I am sure yous are familiar with these ii companies, and aye, they do run on Rails!

Although this article uses examples of deploying a Rail app to AWS, almost of the master concepts remain the same regardless of the linguistic communication and framework used, such as Python/Django or PHP/Laravel.

Setting upwardly Rails

Note that the commands depicted volition piece of work on a UNIX/Linux-based system out of the box. If you lot are on Windows, consider using the Windows Subsystem for Linux and/or Microsoft Windows Terminal.

For starters, verify your Cherry version:

Anything 2.five.0 and to a higher place is good to go. If not, go hither to get the latest version. I have version 2.6.5 installed.

If everything looks okay with your Ruby installation, go ahead and install Runway.

Once that command runs, confirm your Rail version:

If y'all see anything above half-dozen.0.0, and so you're good to get for the rest of this tutorial.

Setting up Postgres

We volition be using Postgres DB as our information shop for this tutorial. Here is an excellent guide to installing it on any platform.

Adding and Running Our Code

We will build a simple API to store picture information, such as the name, year of release, and genre. The API will but accept 2 endpoints, GET & Post, for demonstration purposes.

Create a new Runway API app with the following command:

            runway new movie-api              --api              --database              =postgresql                      

One time the above command runs successfully, brand sure to modify the directory to the projection binder created before running the next commands.

So, we can run the post-obit command to generate our model:

            rails generate model Picture name:string year:integer genre:string                      

Now let's gear up up the database and run migrations:

If these two commands are successful, you should be able to see a new migration in the db/migrate folder with code like to the following:

                          class              CreateMovies              <              ActiveRecord              ::              Migration              [              6.0              ]              def              change              create_table              :movies              do              |              t              |              t              .              string              :name              t              .              integer              :yr              t              .              string              :genre              t              .              timestamps              end              stop              end                      

We will then become alee and add together the controller logic code for our API endpoints:

            rails thousand controller api/Movies                      

Then, add the following code to the file app/controllers/movies_controller.rb:

                          grade              Api::MoviesController              <              ApplicationController              # GET /movies              def              evidence              @movies              =              Picture show              .              all              render              json:                            @movies              finish              # POST /movies              def              create              @movie              =              Picture              .              new              (              movie_params              )              if              @moving-picture show              .              relieve              render              json:                            @movie              else              return              fault:                            {              mistake:                            'Failed to add together movie record'              },              status:                            400              end              finish              private              def              movie_params              params              .              crave              (              :movie              ).              permit              (              :proper noun              ,              :year              ,              :genre              )              end              end                      

Permit's set up up the routes. This code goes into config/routes.rb.

                          Rails              .              application              .              routes              .              draw              do              # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html              namespace              :api              practise              resource              :movies              end              terminate                      

At this betoken, you tin run a sanity check using the rails routes control to verify that everything is working properly. You should see output containing something similar to the following: Routes

Earlier running our server, allow's add some seed data to db/seeds.rb:

                          # This file should contain all the record creation needed to seed the database with its default values.              # The data can then exist loaded with the Rails db:seed command (or created alongside the database with db:setup).              movies              =              Film              .              create              ([              {              name:                            'Star Wars'              ,              year:                            1977              ,              genre:                            'SCI-FI'              },              {              proper noun:                            'Lord of the Rings'              ,              year:                            2001              ,              genre:                            'Fantasy'              }              ])                      

Run the following control to add together the data to the DB:

You can at present run the API with the following command:

If you navigate to http://127.0.0.1:3000/api/movies, you lot should see our seed data:

                          [                                          {                                          "id"              :                                          1              ,                                          "name"              :                                          "Star Wars"              ,                                          "yr"              :                                          1977              ,                                          "genre"              :                                          "SCI-FI"              ,                                          "created_at"              :                                          "2020-01-01T10:04:56.100Z"              ,                                          "updated_at"              :                                          "2020-01-01T10:04:56.100Z"                                          },                                          {                                          "id"              :                                          two              ,                                          "proper noun"              :                                          "Lord of the Rings"              ,                                          "yr"              :                                          2001              ,                                          "genre"              :                                          "Fantasy"              ,                                          "created_at"              :                                          "2020-01-01T10:04:56.108Z"              ,                                          "updated_at"              :                                          "2020-01-01T10:04:56.108Z"                                          }                                          ]                                                  

Creating Your AWS Business relationship

For starters, go to this website. If you don't have an account yet, or yous haven't signed into one from your browser, you lot should see a folio similar to this:

AWS Home Page

Go ahead and click the orangish Create an AWS Account push on the superlative-right corner (or if you have an account, sign into your console). Once y'all have filled in the signup class (make sure to selection Account Type as Personal when filling in your address), yous'll be dropped right into the console. Don't forget to verify your email accost!

Don't worry if things wait overwhelming. The UI is quite simple to navigate once y'all know where you want to go.

Set upwards an IAM User

The next matter we demand to do is fix an IAM user. This volition give us admission to API keys we can utilize to SSH and access our resources from outside AWS.

It is too a good idea to have a separate IAM user with access to only the resources the user needs instead of using the default admin credentials for security purposes.

On the abode folio, search for IAM and navigate to the IAM home page. IAM Search

On the IAM homepage, under IAM Resources, click on Users: 0. IAM Resources

After that, click Add User. You can fill out the user proper noun of your choice and so select the checkbox for Programmatic access. Programmatic Access

On the next screen, select Attach existing policies directly and so apply the search box to search for AdministratorAccess. Administrator Access

On the side by side page, add together a name tag and then yous tin identify your user later from the listing of IAM credentials: tags

Finally, on the review page, click on Create User.

On the side by side page, download the CSV file using your credentials. We will need them for the final part.

Once you have the file chosen credentials.csv, y'all can open it in whatsoever spreadsheet app or editor to run across the values in it. Nosotros are more often than not interested in Access key ID and Undercover accesss key.

The last affair you need to do is to become to your Dwelling house folder and create a folder chosen .aws. Inside this folder, identify a file called config. Detect that the folder name starts with a . and the file has no extension. The full path should be something similar /Users/your-user/.aws/config.

If you are unable to create the .aws folder and config file, y'all can skip information technology for now. The important matter is to take the CSV file with your credentials on hand for later on use.

Identify the following into the config file:

            [contour eb-cli] region = usa-eastward-1 aws_access_key_id = your-aws-access-key-id aws_secret_access_key = your-aws-secret-access-primal                      

You can find your AWS region on the summit-correct corner of the AWS business relationship page when y'all sign in.

Create RDS DB

We volition at present become alee and create the Postgres DB with which our app will be communicating. Like to IAM, yous tin apply the searchbox on the home folio to search for RDS and navigate to information technology.

On the abode folio of RDS, click on Create database. rds

On the next page, select Standard Create; then, under Engine Options, select PostgreSQL. DB Create

Every bit yous continue scrolling, option Free tier nether Templates, and under Settings, allow the DB example identifier exist motion picture-api. You can leave the Master username as postgres, but get ahead and add a countersign. DB Settings

Skip over the sections DB case size, Storage, and Availability & immovability. Nether Connectivity, select Boosted connectivity configuration and set Publicly accessible to Yes and VPC Security group to Create new. Connectivity.

Continue and skip over Database authentication. Under Additional configuration, brand sure to add the Initial database proper noun; movie_api_db will do. Once set, skip everyting else and click Create Database at the bottom of the page.

Lastly, back on the RDS dashboard, click on the default grouping under VPC Security groups on the right column: Security Group

At the bottom of the next page, select Entering and edit the rules to await equally follows: Inbound rules

Also, brand certain the Outbound rules look like the following: Outbound rules

Create Elasticbeanstalk App

Navigate to the elastic beanstalk abode page and click Create New Application. Elasticbeanstalk

Fill up out the new application class equally necessary. Application

You will and then run across a folio with the message No environments currently be for this application. Create one now. Click on Create 1 now.

Adjacent, select Web server surroundings. Web server env

In the next section, change the Environment name to product-env. Get out the Domain blank. And so, under Base of operations Configuration, select Preconfigured platform and choose Red from the dropdown. Y'all can exit Application code on Sample application; then, go alee and click Create environs. This will take some time, so exist patient. Base config

In one case done, you should meet a folio that looks like this: Production Env

Find the URL provided afterwards the surround ID. Click on it to check out the default Ruby app on elasticbeanstalk. Very soon, your API volition be running on the same URL.

Brand Your App Fix for Deployment

To brand the app ready for deployment, we need to first configure our web server.

Since Rails ships with Puma, a production-ready web server, as its default server, you can directly edit the config file at config/puma.rb.

Edit your file to look similar the following:

                          max_threads_count              =              ENV              .              fetch              (              "RAILS_MAX_THREADS"              )              {              five              }              min_threads_count              =              ENV              .              fetch              (              "RAILS_MIN_THREADS"              )              {              max_threads_count              }              threads              min_threads_count              ,              max_threads_count              # Specifies the `port` that Puma will listen on to receive requests; default is 3000.              #              port              ENV              .              fetch              (              "PORT"              )              {              3000              }              # Specifies the `environment` that Puma will run in.              #              environment              ENV              .              fetch              (              "RAILS_ENV"              )              {              "development"              }              # Specifies the `pidfile` that Puma will use.              pidfile              ENV              .              fetch              (              "PIDFILE"              )              {              "tmp/pids/server.pid"              }              # Specifies the number of `workers` to boot in clustered fashion.              # Workers are forked web server processes. If using threads and workers together,              # the concurrency of the application would be max `threads` * `workers.`              # Workers practice not work on JRuby or Windows (both of which do not support              # processes).              #              workers              ENV              .              fetch              (              "WEB_CONCURRENCY"              )              {              2              }              # <------ uncomment this line              # Use the `preload_app!` method when specifying a `workers` number.              # This directive tells Puma to first boot the application and load code              # earlier forking the application. This takes advantage of Re-create On Write              # process behavior and then workers utilise less memory.              #              preload_app!              # <------ uncomment this line              # Allow Puma to be restarted by the `Rail restart` control.              plugin              :tmp_restart                      

Likewise, edit the bottom of config/database.yml past commenting out the existing production config and using this instead:

                          production              :              url              :              <%= ENV['DATABASE_URL'] %>                      

Lastly, become to your Elasticbeanstalk console on AWS, select the production-env surround, and and so become to Configuration.

On the configuration overview screen, click on Modify for the Software portion:

Configuration Overview.

Next, add DATABASE_URL and RAILS_ENV, and then click on 'Apply':

EB env vars

Annotation that your DB URL is congenital using the Endpoint you took note of earlier from the RDS dashboard. Information technology is in the format of postgresql://postgres:YOURPASSWORD@ENDPOINT:5432/movie_api_db. If you do not recollect the password you chose, you can change information technology in the Modify department of your DB's RDS dashboard.

Manual Deployment

This is as elementary as creating a zippo file of your app from the command line so uploading it on your Elasticbeanstalk console.

Outset of all, cd into the project binder. To create a zip file, you can and then run the following control:

deploy_1.cipher will be the name of the zip folder created, and it will appear in your project directory, forth with the other files. Done? Excellent. On to AWS.

From the Dashboard of Elasticbeanstalk, click on Upload and Deploy:

Upload and Deploy

You can change the version label to something more meaningful:

Version label

Once Elasticbeanstalk has finished updating the environment, you lot can visit your environment URL to see your API running! You lot tin utilise a free service, such as this, to send some requests and populate your DB on AWS.

Deployment with EB CLI

The Elasticbeanstalk CLI makes most of what you have had to do manually upwards to this point quite easy to accomplish with a few commands. I'll testify yous how to set it upwardly and use information technology on our current projection. This all depends on having your IAM user fix correctly, so make sure everything from that step is okay or that you lot have the CSV with your credentials gear up.

For well-nigh computers, you should already have Python installed. Installation will, therefore, exist every bit easy equally the following:

            pip              install              awsebcli              --user                      

On MacOS, you can also employ:

Yous tin can read more about installation here.

In one case the installation is finished, cd to your project folder and run eb init.

Follow the prompts equally per your AWS environment. Select a region past entering the right number selection:

            Select a default region ane)              u.s.a.-east-ane : US East              (N. Virginia)              two)              us-west-1 : The states W              (N. California)              iii)              us-westward-2 : United states West              (Oregon)              4)              eu-west-1 : European union              (Ireland)              5)              eu-cardinal-1 : European union              (Frankfurt)              vi)              ap-south-1 : Asia Pacific              (Mumbai)              7)              ap-southeast-1 : Asia Pacific              (Singapore)              eight)              ap-southeast-2 : Asia Pacific              (Sydney)              9)              ap-northeast-i : Asia Pacific              (Tokyo)              10)              ap-northeast-2 : Asia Pacific              (Seoul)              eleven)              sa-eastward-one : S America              (Sao Paulo)              12)              cn-due north-1 : China              (Beijing)              13)              cn-northwest-i : Prc              (Ningxia)              xiv)              us-eastward-2 : United states East              (Ohio)              15)              ca-central-1 : Canada              (Cardinal)              16)              european union-west-2 : European union              (London)              17)              european union-west-iii : EU              (Paris)                      

For the Scarlet version portion, select the relevant version using Puma:

            1)              Red 2.6              (Passenger Standalone)              2)              Ruby 2.6              (Puma)              3)              Ruby ii.5              (Passenger Standalone)              4)              Ruby 2.5              (Puma)              5)              Ruby 2.4              (Passenger Standalone)              6)              Blood-red 2.4              (Puma)              7)              Red 2.three              (Passenger Standalone)              8)              Red ii.3              (Puma)              9)              Ruby 2.2              (Rider Standalone)              10)              Ruby 2.2              (Puma)              11)              Ruby 2.i              (Rider Standalone)              12)              Ruby-red 2.1              (Puma)              13)              Ruby 2.0              (Passenger Standalone)              xiv)              Blood-red 2.0              (Puma)              fifteen)              Ruby i.9.3                      

I picked two.

Become through the rest of the prompts and select 'no' to using CodeCommit and 'no' to set up SSH.

If you did not prepare up the AWS config, the CLI will prompt you for your AWS keys. Add them every bit required.

Once this is done, the CLI will go out. You can then run commands, such as eb condition, to check the status of the app we deployed.

            Environment details              for: production-env   Application proper noun: movie-api   Region: united states of america-e-2   Deployed Version: Deploy 2-2   Environment ID: e-mab3kjy6pp   Platform: arn:aws:elasticbeanstalk:us-east-2::platform/Puma with Cherry-red two.6 running on 64bit Amazon Linux/two.eleven.i   Tier: WebServer-Standard-i.0   CNAME: production-env.qnbznvpp2t.us-east-2.elasticbeanstalk.com   Updated: 2020-01-22 23:37:17.183000+00:00   Status: Prepare   Wellness: Green                      

To deploy a new version, simply run eb deploy.

And, that'south it! You can read more well-nigh other CLI commands yous can effort out hither

Summary

In this tutorial, nosotros take learned how to set a simple Track API, how to fix AWS resource, such as Elasticbeanstalk and RDS, and how to deploy the app to use them.

We also covered how to utilise the Elasticbeanstalk CLI to automate deployments to our cloud app. You have now learned how to become from a working app on your local machine to a working app shared with the world on AWS.

Honeybadger has your back when it counts.

We're the only mistake tracker that combines exception monitoring, uptime monitoring, and cron monitoring into a single, simple to employ platform. Our mission: to tame production and brand y'all a meliorate, more than productive developer.

Acquire more than

vanoverpophe1936.blogspot.com

Source: https://www.honeybadger.io/blog/rails-6-aws-elastic-beanstalk/

Post a Comment for "Building and Uploading a Rails App With Elastic Beanstalk"