Featured Image
Software Development

Complete guide to deploying your React app on AWS EC2 for global accessibility

Go global with your React Application! If you start hosting your app on Amazon Web Services (AWS), the number of opportunities with Elastic Compute Cloud (EC2) will rise steeply. The flexible and scalable cloud infrastructure of AWS EC2, combined with the robust JavaScript library of the React app, renders empowered and dynamic user interfaces. This dynamic collaboration perfectly aligns with the needs of a worldwide audience.

In this article, you will learn step-by-step how to install a React app on an AWS EC2 instance. The details provided in this guide include setting up the EC2 instance, configuring it for React app installation, and hosting your website for users to access. Therefore, by following the instructions provided here, you will have a completely operational React app running on an AWS EC2 instance, ready to be accessed by global users. Let’s get on with this and understand how to deploy your React app to EC2! 

Introduction to AWS and EC2

Amazon Web Services is a revolutionary cloud computing platform that has transformed the way developers and businesses alike deploy, manage, and scale their apps. AWS offers a diverse set of services. Amazon Elastic Compute Cloud i.e., EC2, stands out prominently among those as it is recognized as a fundamental building block.

What is AWS?

Amazon’s AWS is a cloud computing platform that offers a wide array of cloud services, including computing power, storage, databases, machine learning, and much more. Its design supports scalability and is extremely flexible. Its cost-effective solutions are found helpful across a range of organizations of almost all sizes, whether it’s a startup, mid-size firm, or an enterprise. AWS’s significant proposition comes in the form of its all-inclusive collection of tools and resources that can meet any kind of computing and infrastructure requirements.

Why choose AWS?

Now comes the question, why should one choose AWS over any other counterpart for hosting their applications, such as React web apps? Here are some reasons that might tell you the perfect why:

Scalability: AWS is quite accommodating when it comes to scalability. It is also able to manage the resources between high scale and low as per the demand. So let’s say for an app, if you have to manage a sudden surge in traffic or reduce costs for a sudden drop in demand, AWS will prove to be advantageous. 

Flexibility: AWS offers flexible solutions to design your infrastructure to suit your exact requirements. This becomes possible with its wide range of services and configurations. The choices can be made based on your app’s requirements of the operating system, instance type, and storage options.

Reliability: AWS supports a global network of data centers and manages the redundancy, thereby, guaranteeing high accessibility and consistency for your apps. With this measure, your React app can be accessible to the global audience with minimal downtime.

Security: The security features and compliance certifications of AWS provide robust safety. You can execute identity and access management, encryption, and security groups as a precautionary measure for your resources’ safety.

What is Amazon EC2?

Amazon EC2 is a part of the AWS family. It is a web service that enables you to rent virtual servers, which are known as instances, in the cloud. Each EC2 instance offers sturdy computing capacity, thus allowing you to run applications seamlessly, as well as to host websites and execute several computing tasks without actually investing in any physical hardware.

Why EC2 for hosting React apps?

EC2 is the most appropriate choice for hosting React applications owing to its amazing features, including flexible approach and scalability. You can effortlessly install your React app on an EC2 instance, set configuration as per your specifications, and enable its accessibility to global users. Whether you’re creating a small-scale portfolio site or a complex web app, AWS EC2 has all the resources and capabilities you need.

Prerequisites

Before beginning installation process, keep the below checklist ready: 

  • An AWS account
  • Basic knowledge of React, npm and AWS EC2
  • A React app ready for deployment
  • SSH client software (for connecting to the EC2 instance)

Setting up an AWS EC2 Instance

Launch an EC2 instance and ensure it has the necessary security group rules to allow inbound SSH traffic on port 22, as well as inbound HTTP traffic on port 80 and HTTPS traffic on port 443. For example, I have selected the Ubuntu operating system and t2.micro architecture

Preparing your React app for deployment

Before you get on with deploying your React app, it is important to keep a checklist ready and make necessary preparations. Install all the necessary dependencies, thereby generating a production-ready build. Also, conduct a thorough local testing beforehand.

Deploying your React app on EC2

We will transfer your React app to the EC2 instance, build its infrastructure, and complete its configuration over a web server (such as Nginx) to serve the app. Here are the necessary steps to ensure a successful deployment:

Transferring your app to the EC2 Instance
– SSH into your EC2 instance using the public IP or DNS., for example, ssh -i PrivateKey.pem ubuntu@ec2–xx–xx–xxx–xxx.eu-west-2.compute.amazonaws.com
– Install Git, Node.js, and npm on the instance.
– Change to the desired directory: cd /project_repo
– Copy your Git repository to the local directory: git clone <repository_url>

Deploy all the dependencies and create the React app
– Navigate to the project directory: cd <repository_directory>
– Install dependencies: npm install
– Compile the React app: npm run build

Setting up a web server (e.g., Nginx)
Install Nginx on your EC2 instance: sudo apt-get install nginx Refer to this link for the whole installation and activation process.

Steps to configure Nginx for deployment

To verify if Nginx is enabled and running on an Amazon Linux instance, you can use the following commands:

  1. Start the Nginx
    - sudo service nginx start
    This command will start the Nginx service, if it’s not already running.
  1. Check the status of Nginx
    - sudo service nginx status
    Running this command will display the current status of the Nginx service. If Nginx is active and running, the output will indicate that.

If Nginx is running successfully, the status command will display something similar to:
* nginx is running

On the other hand, if Nginx is not running, the output will indicate that it is not active or running.

nginx active(running)

– You can test Nginx by running the following command in the terminal: curl localhost

The above command will display the HTML file with the “Welcome to Nginx” text. Additionally, you can open your web browser and enter the public IP address of your EC2 instance (you can find this IP in the EC2 instance details). By doing so, you should be able to see the same ‘Welcome to Nginx’ page, which is the HTML file we accessed earlier using the curl command.

To change the root path of the server in the Nginx configuration file, follow these steps:

– Remove the default Nginx configuration: sudo rm /etc/nginx/sites-enabled/default

– Create a new Nginx configuration file: sudo nano /etc/nginx/sites-available/react-app

– You can check out this tutorial to generate an SSL certificate for HTTPS using certbot:

https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-22-04

– Once you get the certificate key and crt file, you can put that under the server block of HTTPS (443).


server {
  listen 80;
  server_name your_domain.com;

  location / {
      root /var/www/html;
      index index.html;
      try_files $uri $uri/ /index.html;
  }
}

server {
  listen 443 ssl;
  server_name your_domain.com;

  ssl_certificate /path/to/your/ssl_certificate.crt;
  ssl_certificate_key /path/to/your/private_key.key;

  location / {
      root /var/www/html;
      index index.html;
      try_files $uri $uri/ /index.html;
  }
}

Finally, save the configuration file and complete the work of the text editor. Exit once done. Remember to use sudo before the text editor command to have the necessary permissions to modify the file.

Create a symbolic link from the sites-available directory to the sites-enabled directory: sudo ln -s /etc/nginx/sites-available/react-app /etc/nginx/sites-enabled/

After making these changes, you can restart the Nginx service for the new configuration to take effect: sudo service nginx restart

Now, Nginx will use the updated root path for serving web content. Ensure that the specified path exists and contains the necessary files for your website or application.

To deploy your project’s build folder to the Nginx web server, follow these steps:

  1. Change the directory to your project’s root directory using the command:
    cd <project_dir>

Replace <project_dir> with the actual path to your project’s root directory.

  1. Copy the contents of the build folder to the Nginx default root directory using the scp command: sudo scp -r build/* /var/www/html


This command recursively copies the contents of the build folder to the /var/www/html directory. Before proceeding, make sure that you have the necessary permissions to implement this operation.

  1. After copying the build files, you can open a web browser and enter the public IP address of your server. This IP address can be found in the EC2 instance details.
  1. By doing so, you should be able to see your built application running in the browser. Nginx will serve the files located in the /var/www/html directory.

Make sure that your project’s build folder contains the necessary files for your application to run properly. Adjust the paths and commands according to your specific project structure and requirements.

Also read: Comparing Amazon RDS and Amazon EC2 for PostgreSQL Databases

Accessing your deployed React app

  • Check your EC2 instance’s security group settings to ensure that inbound HTTP (port 80) and HTTPS (port 443) traffic is allowed.
  • Access your React application by navigating to the domain name or public IP address associated with your EC2 instance in a web browser. The application should be accessible and functioning correctly.
Running React App on EC2 Instance

Running React App on EC2 Instance

Also read: Learn Everything About Code Smells: Types, Refactoring & Best Practices

Security best practices

In the current times, it is pertinent to ensure that your applications are secure. While installing your React app on AWS EC2, you should follow all the security best practices to safeguard your data, infrastructure, and user information. 

Identity and access management: Identity and Access management is one of the key priorities whilst managing security layers. To achieve this successfully incorporate IAM roles and policies to regulate control and access to your EC2 instances and AWS resources. Also, allocate permissions according to the principle of least privilege to enhance safety. This way, the users and applications will only have access to the essential resources for their tasks.

Network security: A full-fledged configuration of security groups and network access control lists will regulate inbound and outbound traffic as well as make it work in coherence with your EC2 instances. It is important to use Virtual Private Cloud features to quarantine your instances whenever you are not in a secure network setting, especially in any public network or internet based environments.

Data encryption: Encryption is necessary for data whether it is in static state or dynamic. AWS comes in handy for this as it has many useful tools like AWS Key Management Service for managing encryption keys and keeping data confidential to maintain security levels.

Backup and disaster recovery: It is critical that you include automation for backups and also induce disaster recovery plans to safeguard data availability. This ensures safety in instances of unexpected failures. For this, you can utilize services like Amazon S3 that become valuable for data storage and backup.

Security audits and penetration testing: Regular monitoring of AWS environment is important to keep security threats under check. Conduct thorough and detailed audits at consistent frequency for security compliance. Also, for detecting vulnerabilities, administer penetration testing. This will give you a heads’ up before any security threat occurs.

By complying with the above-mentioned security best practices, you can accentuate the protection of your React app to a remarkable level. Security should always be one of your primary objectives while deploying applications in the cloud.

Also read: A Guide to Integrating Augmented Reality into Flutter

Conclusion

We have included all the steps with great detail in this guide to help you complete the deployment process for your React app on an AWS EC2 instance. The instructions shared here will not only assist you in setup of EC2 instance but also help you access your deployed app in great detail. While you are conducting setup, do not forget to monitor your EC2 instance. Also, it is pertinent that you stay updated with security patches and automate your back up process for safeguarding data. If you follow this guide, it will help you with coherent functionality.

If you have queries, require any further assistance, or want to know how we can help you take advantage of the full potential of AWS for your projects, feel free to reach out. We specialize in cloud solutions like AWS and offer expert React development services to help you in your journey.

author
Shrey Soni
Shrey is a versatile and talented individual who enjoys learning new things and challenging himself, both personally and professionally. A curious and creative thinker who is always looking for ways to expand his horizons.