Table of contents
Deploying a Node.js application on AWS EC2 can initially seem daunting, but following a systematic approach can achieve it efficiently. This guide walks you through deploying a basic Node.js application on an AWS EC2 instance.
Prerequisites
Before we begin, ensure you have the following:
An AWS account.
Stripe API Keys (refer to the provided document).
Project Overview
We will:
Test the application locally.
Deploy it on AWS EC2.
The repository used in this project is: NodeJS-AWS-EC2.
Step-by-Step Guide
Step 1: Clone the Repository Locally
First, clone the repository to your local machine:
git clone https://github.com/nishankkoul/NodeJS-AWS-EC2.git
Step 2: Create a .env
File
Create a .env
file to store environment variables. This file is crucial for:
Separation of Configuration and Code: Keeping configuration separate from source code.
Security: Avoiding hardcoding sensitive information like API keys.
Flexibility: Easily switching configurations for different environments.
Ease of Deployment: Managing environment variables during the deployment process.
Consistency: Ensuring consistent environment variables for all developers.
Create the .env
file with the following variables:
DOMAIN
PORT
STATIC_DIR
PUBLISHABLE_KEY
SECRET_KEY
Step 3: Initialize and Start the Project
Install the dependencies and start the project:
npm install
npm run start
Access the application locally via http://localhost:3000
Step 4: Set Up an EC2 Instance
Launch an EC2 Instance:
Choose an Ubuntu Server AMI.
Select an instance type (e.g.,
t2.micro
).Configure security group to allow SSH (port 22) and HTTP (port 80) access.
Launch the instance and download the key pair for SSH access.
Connect to the EC2 Instance:
ssh -i "your-key-pair.pem" ubuntu@your-ec2-public-dns
Step 5: Deploy the Application on EC2
Clone the Repository:
git clone https://github.com/nishankkoul/NodeJS-AWS-EC2.git
cd NodeJS-AWS-EC2
Create the .env
File:
vim .env
Copy and paste the content from the local .env
file.
Install Node.js and npm:
sudo apt update
sudo apt install nodejs
sudo apt install npm
Install Dependencies and Start the Application:
npm install
npm run start
Step 6: Configure Security Group
Edit the inbound rules of the EC2 instance's security group to allow traffic on port 3000.
Step 7: Access the Application
Copy the EC2 instance's Public IPv4 address and access the application:
http://your-ec2-public-ip:3000
Congratulations, your Node.js application is now deployed on AWS EC2! For further details and updates, refer to the project repository.
Conclusion
Deploying a Node.js application on AWS EC2 involves setting up the environment, configuring security, and managing environment variables. Following these steps ensures a smooth deployment process, keeping your application secure and flexible for future updates. Happy coding!