![]() |
How to Deploy a NestJS Application to AWS: A Complete Step-by-Step Guide |
Deploying a NestJS application to AWS ensures scalability, reliability, and global availability. AWS offers multiple services that you can leverage for deployment, such as EC2, Elastic Beanstalk, and AWS Lambda. This guide walks you through deploying a NestJS app using an EC2 instance for maximum control over the deployment process.
Prerequisites
Before you begin, ensure you have:
- A NestJS application ready for deployment.
- An AWS account.
- Basic knowledge of AWS services like EC2 and Route 53.
- Installed AWS CLI on your local machine.
1. Setting Up Your NestJS Application
- Build Your NestJS App
- Configure the Environment
.env
file for environment-specific variables:- Package Your App
2. Preparing the AWS Environment
Launching an EC2 Instance
- Log in to the AWS Management Console.
- Navigate to EC2 and click on Launch Instance.
- Configure the following:
- AMI: Choose Amazon Linux 2 or Ubuntu.
- Instance Type: Select
t2.micro
(free-tier eligible). - Key Pair: Generate a new key pair or utilize an existing one to securely enable SSH access to your instance.
- Storage: Allocate sufficient storage (e.g., 8GB).
Configuring Security Groups
- Modify your instance's security group to allow inbound traffic for necessary services and protocols:
- Add rules to enable HTTP traffic on port 80 and HTTPS traffic on port 443 for public access to your application.
- Configure an inbound rule to permit SSH (port 22) connections exclusively from your current IP address to maintain secure remote access.
3. Deploying the NestJS Application
Installing Dependencies on EC2
- SSH into your EC2 instance:
- Update the instance and install Node.js:
- Install
pm2
to manage the NestJS application:
Uploading Your Application Code
- Use SCP to transfer your zipped application to the EC2 instance:
- SSH into the instance and extract the code:
- Install the dependencies:
4. Configuring and Running the Application
- Set Up Environment Variables
.env
file on the EC2 instance with your variables.- Run the Application with PM2
- Configure NGINX as a Reverse Proxy
Edit the NGINX configuration:
Add the following configuration:
Restart NGINX:
5. Setting Up a Domain and SSL
Domain Configuration- Use AWS Route 53 or another domain registrar to point your domain to your EC2 instance.
Use Certbot to obtain free SSL certificates:
Set up automatic certificate renewal:
Add the following line:
Congratulations! Your NestJS application is now deployed to AWS and accessible via your domain. This setup ensures scalability, reliability, and security for your application. For further optimizations, consider using AWS services like RDS for databases and CloudWatch for monitoring.