Deploying A NodeJS App With Elastic Beanstalk
Tags: javascript, aws, node, elasticbeanstalk
Published: 2023-07-05 07:18:11

Managing applications on the cloud can be a complex task, especially when it involves handling multiple environments, scaling, and deploying updates. However, there's a solution that can alleviate these challenges: AWS Elastic Beanstalk. This service provided by Amazon Web Services offers a user-friendly platform for deploying, managing, and scaling applications in the AWS Cloud.

In this tutorial, we will delve into the fundamentals of Elastic Beanstalk and guide you through the process of deploying a NodeJS app connected to an RDS database. Let's begin!

Introduction to AWS Elastic Beanstalk

AWS Elastic Beanstalk is a fully managed service designed to simplify the deployment, management, and scaling of applications on AWS. It takes care of provisioning the necessary resources, including EC2 instances, RDS databases, and load balancers.

Elastic Beanstalk handles the deployment, monitoring, and maintenance tasks of your applications, enabling you to focus on coding and delivering new features.

One of the advantages of Elastic Beanstalk is that it leverages CloudFormation to provision resources. The great news is that you don't have to write CloudFormation templates yourself. Elastic Beanstalk takes care of it automatically.

Now that we have a basic understanding of Elastic Beanstalk, let's explore the process of deploying a NodeJS app with a RDS connection.

Preparing the NodeJS Source Code
Before deploying our app to Elastic Beanstalk, we need to perform a few steps. Although it took me hours to figure this out, I'll guide you through the process, and you'll be able to deploy your app in about 10 minutes.

Deploying Your Own App
First, ensure that your `package.json` file includes the `start` command, and that this command is configured to run your app. By default, Beanstalk executes `npm start`, and if it cannot find it, an error will be thrown.

![package.json file with start command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrhyuscnept1j2c4c0af.png)
package.json file with start command

Configuring environment variables is a crucial aspect when working with AWS Elastic Beanstalk, particularly when it comes to RDS connections. It is important to adhere to the pre-defined naming conventions set by AWS. For more detailed information, you can refer to this article provided by AWS.

To illustrate this point, let's consider a quick example. When configuring the hostname for the RDS, you must use the specific environment variable designated as `RDS_HOSTNAME`. If you use a different variable name, such as `DB_HOSTNAME`, your application will be unable to establish a connection.

In the AWS Elastic Beanstalk console, you have the flexibility to define custom environment variables according to your specific requirements.

Here's an example of how your DB connection configuration should be structured:

![Elastic Beanstalk DB configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvji7kpbulbgtsmqjypo.png)
Elastic Beanstalk DB configuration

Elastic Beanstalk (EBS) by default runs on port 8080. So we have to configure our app to run on port 8080. It's always a best practice to add the port number in environment variables and configure it in the EBS console.

![Elastic Beanstalk port](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7p1gc6jdb2gd3zjdja2j.png)
Elastic Beanstalk port

In order for Elastic Beanstalk to read our environment variables, we should add a file called `.ebextensions` in the project root directory with the following code:
```
commands:
    setvars:
        command: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export \(.key)=\"\(.value)\""' > /etc/profile.d/sh.local
packages:
    yum:
        jq: []
```
.ebextension to get env variables

Install the dependencies by executing npm install and zip your code along with node_modules by executing the following command:
```
zip [filename].zip -r ./
```

Remember the zipped file should contain all files and subdirectories in the root folder and should not be inside any other folders. This is because Elastic Beanstalk will check for the `package.json` file in the root folder and it'll throw an error if it can't find it.

Now our app is ready, let's create the Elastic Beanstalk application.


Creating an Elastic Beanstalk Application

Step 1: Configuring Your Environment

To create an Elastic Beanstalk app, follow these steps:

Open the AWS Management Console and select Elastic Beanstalk from the Services menu. Click on the "Create Application" button. Choose the "Web server environment" option then
Provide a name for your application.


![Getting started with AWS Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iazwxna1f36wovnngiwj.png)
Getting started with AWS Elastic Beanstalk

![Give your application a name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghsoyd4ueae7g2lq5vtd.png)
Give your application a name

Choose `Managed platform` in "Platform type", and `Node.js` in "Platform", and leave the rest as it is.

Then choose `Upload your code` in the "Application code" section and upload the zip file.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntfo3c3wtvu1o5hv7icr.png)

![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s63e5eog28jfdie9n8f.png)
Screenshot of the above selections

Then set the version label to `1` and choose `Single instance` in the "Presets" section and click Next.

**Note:** Prefer `High availability` for production environment.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ky2qi1nfucc8auk8vj6l.png)
More setup config

Step 2: Configuring Service Access

In this section, we will configure the necessary IAM roles for Elastic Beanstalk and EC2. Follow these steps:

For the service role, select "Create and use a new service role." This will automatically create a new role with the required permissions.

If you wish to SSH into your EC2 instance via the terminal, create a key-value pair and select it. If not, you can skip this step.

Create an IAM role with the following permissions: 

- AWSElasticBeanstalkWebTier
- AWSElasticBeanstalkWorkerTier
- AWSElasticBeanstalkMulticontainerDocker

Add the created role to the "EC2 instance profile."

Proceed to the next step.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4opagry4ecproyjq8ibz.png)
Configure service access screen

Step 3: Set up networking, database, and tags
Now, turn on the Enable database toggle and choose mysql Engine. Fill out the other fields based on your needs.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5a30mlvch5lwspsmbtx.png)
Filling out the other options

Be super careful while selecting the "Database deletion policy". As I'm creating the sample app I selected the Delete option which will delete the database when the Elastic Beanstalk application is deleted.

If you're working on a production database, it's always a best practice to choose the Create Snapshot or Retain option.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irbd7ik6eu7esvez8t6u.png)
Database deletion policy

Step 4: Configure instance traffic and scaling
You don't need to change anything here unless you particularly need it. If you're building this sample app, leave the fields with default values. By default Elastic Beanstalk will create an Amazon Linux machine.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0sxdzl8x39ure5izht2.png)
You can leave the default values unless you need someting in particular.

Step 5: Configure updates, monitoring and logging
Choose `Basic` in "Health reporting" and uncheck Managed updates activation.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ia3ksytklcvbj9qgsv4m.png)
More config

Add your environment variables and click Next.


![Elastic Beanstalk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/751mfw18u2nju8kzsat1.png)
Add environment variables

Finally, review all your configurations and proceed with next. It takes time to provision the RDS, so feel free to grab a glass of coffee


![Elastic Beanstalk Configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgqf6w2v9mfr33c3msco.png)
Review config and proceed when ready.

Once you have completed all the necessary configurations, you should observe that the health status of your Elastic Beanstalk application turns green, indicating a successful deployment. Additionally, a domain URL will be generated for your application, which you can use to access it.

Celebrate the achievement of a successful deployment with the green health status 🎉, and rejoice as you receive your generated domain URL 🥳.


![Elastic Beanstalk App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5yxngqbalrh0tnqwjj6.png)
Success!

![Elastic Beanstalk App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmae5gvqfh7npwxglx2k.png)
When you hit the domain-url/ you should see your application load fine.

Conclusion
In this article, we've successfully deployed a NodeJS app with an RDS connection using AWS Elastic Beanstalk. This powerful service simplifies the deployment and management process, allowing you to focus on developing and scaling your applications.

If you are stuck at any point feel free to drop your comments below. I'll be happy to help.

Hope you enjoyed reading this article!