Deployment: Deploying a NestJS Application
Deploying a NestJS application to a cloud platform (e.g., AWS, Google Cloud, Azure) or a containerized environment (e.g., Docker, Kubernetes).
Deploying NestJS to AWS
Introduction
This document provides a comprehensive guide on deploying a NestJS application to Amazon Web Services (AWS). We'll cover different deployment strategies, including EC2, Elastic Beanstalk, and ECS, providing step-by-step instructions for each approach. This guide assumes you have a basic understanding of NestJS and AWS.
What is AWS?
Amazon Web Services (AWS) is a suite of cloud computing services that offers a wide range of tools and resources, including compute, storage, databases, and more. AWS allows you to run your applications in the cloud, providing scalability, reliability, and cost-effectiveness.
Deploying to AWS (Example Scenario: Elastic Beanstalk)
Let's consider an example where we want to deploy our NestJS application using AWS Elastic Beanstalk. Elastic Beanstalk is a Platform-as-a-Service (PaaS) that simplifies the process of deploying and managing web applications. It handles the underlying infrastructure, allowing you to focus on your code.
In this scenario, we will:
- Create a NestJS application (if you don't already have one).
- Configure the application for production.
- Create an Elastic Beanstalk environment.
- Deploy the application to Elastic Beanstalk.
- Configure environment variables and other settings.
This example showcases the general process. The specifics may vary depending on your application and the AWS services you choose.
Step-by-Step Guide: Deploying a NestJS Application to AWS
This section provides a detailed, step-by-step guide for deploying a NestJS application to AWS. We'll focus on deploying to AWS Elastic Beanstalk for simplicity and ease of use.
Prerequisites
- An AWS account.
- The AWS CLI installed and configured. AWS CLI Installation Guide
- Node.js and npm (or yarn) installed locally.
- A NestJS application.
1. Prepare your NestJS Application for Production
First, ensure your NestJS application is configured for a production environment.
- Build your application: Run the following command in your NestJS project directory:
This will create anpm run build
dist
folder containing the compiled JavaScript files. - Configure
main.ts
for production: In yoursrc/main.ts
file, configure the application to listen on the correct port and potentially use a different environment configuration. For example:import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { Logger } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); const port = process.env.PORT || 3000; // Use environment variable for port await app.listen(port); Logger.log(`Application listening on port ${port}`); } bootstrap();
- Create a
.platform
directory (Elastic Beanstalk specific): Elastic Beanstalk uses a.platform
directory at the root of your application to customize the environment. Create the directory and the necessary files within it.Create the following directory structure:
.platform/ ├── nginx/ │ └── conf.d/ │ └── elasticbeanstalk.conf └── nodejs/ └── node_modules/
- Configure Nginx (
.platform/nginx/conf.d/elasticbeanstalk.conf
): This file configures Nginx to proxy requests to your Node.js application. This is crucial for handling HTTP requests and routing them to your NestJS application. Replace `dist/main.js` with the location of your compiled main file, and use the PORT that is set by Elastic Beanstalk.upstream nodejs { server 127.0.0.1:$PORT; keepalive 256; } server { listen 80; server_name _; access_log /var/log/nginx/access.log main; location / { proxy_pass http://nodejs; proxy_set_header Connection ""; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { alias /var/app/current/public; # Serve static files from the public folder if you have one expires 30d; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
- Create a
package.json
script (optional but recommended): Add a start script to yourpackage.json
that uses `node` to run your compiled JavaScript. This makes deployment easier."scripts": { "build": "nest build", "start:prod": "node dist/main.js" // Important for Elastic Beanstalk }
- (Important!) Create or Modify .ebignore file: Add `node_modules` and any development-only files to the `.ebignore` file. This drastically reduces the size of the deployment package and speeds up deployment.
node_modules/ src/ test/ .gitignore .git/
2. Create an Elastic Beanstalk Environment
- Navigate to the Elastic Beanstalk console in the AWS Management Console.
- Create a new application. Give it a name and description.
- Create a new environment. Choose the "Web server environment" tier.
- Select a Platform: Choose "Node.js". Select the appropriate platform branch. Generally, selecting the latest stable version is a good practice.
- Choose an environment type: Select "Single instance" for testing or "Load balanced, auto scaling" for production. Load balanced, auto scaling is recommended for production because it automatically scales your application based on traffic.
- Configure Environment:
- Application code: You'll upload your code in a later step.
- Presets: Choose a pre-configured environment if applicable. Otherwise, leave as default.
- Configure service access: This step lets you specify which AWS resources your EB environment can access.
- Network, Security, and Database: You can configure the VPC, subnets, security groups, and database settings.
- Review and launch.
3. Deploy Your Application
- Create a zip archive of your application. Go to the root of your NestJS project and run:
This creates a zip file namedzip -r deploy.zip . -x "*.git*" -x "node_modules/*"
deploy.zip
containing your application code, excluding thenode_modules
directory and git related files to keep the zip size manageable. Using .ebignore is highly recommended. - Upload the zip file to Elastic Beanstalk. In the Elastic Beanstalk console, navigate to your environment and click "Upload and Deploy". Select the
deploy.zip
file and click "Deploy".
Alternatively, use the AWS CLI:
aws elasticbeanstalk create-application-version --application-name "YourAppName" --version-label "v1" --source-bundle S3Bucket="your-s3-bucket",S3Key="path/to/deploy.zip"
aws elasticbeanstalk update-environment --environment-name "YourEnvironmentName" --version-label "v1"
Replace `"YourAppName"`, `"YourEnvironmentName"`, `"your-s3-bucket"`, and `"path/to/deploy.zip"` with your actual values. This assumes you've uploaded your `deploy.zip` to an S3 bucket. Using S3 is often preferable for larger deployment packages. 4. Configure Environment Variables
You'll likely need to configure environment variables for your application, such as database connection strings or API keys.
- In the Elastic Beanstalk console, navigate to your environment.
- Go to "Configuration" > "Software".
- Under "Environment properties", add your environment variables.
- Click "Apply". Elastic Beanstalk will restart your application with the new environment variables.
5. Access Your Application
Once the deployment is complete, Elastic Beanstalk will provide a URL for your application. You can access your application by visiting this URL in your browser.
Other Deployment Strategies
While Elastic Beanstalk is a convenient option, you can also deploy your NestJS application to AWS using other services:
- EC2 (Elastic Compute Cloud): You have full control over the server environment. You'll need to install Node.js, Nginx, and configure the server yourself. This provides the most flexibility but requires more management. Typically, you'd use a tool like PM2 to manage the NestJS process and keep it running.
- ECS (Elastic Container Service): Deploy your application in a Docker container. This is a good option if you're already using Docker or want more control over the container environment.
- EKS (Elastic Kubernetes Service): Similar to ECS, but uses Kubernetes for container orchestration. This is suitable for complex deployments.
- Serverless Functions (AWS Lambda): While less common for full NestJS applications, you could potentially use serverless functions for specific parts of your application, often combined with API Gateway.
Each deployment strategy has its own advantages and disadvantages, so choose the one that best suits your needs and technical expertise.
Conclusion
Deploying a NestJS application to AWS can be achieved using various services, each offering different levels of control and complexity. This guide has focused on using Elastic Beanstalk, which provides a simplified deployment experience. Consider your specific needs and technical expertise when choosing the best deployment strategy for your application.