how-to-deploy-a-full-stack-application-using-nestjs-and-postgresql-on-aws.html

How to Deploy a Full-Stack Application Using NestJS and PostgreSQL on AWS

Deploying a full-stack application can seem like a daunting task, especially if you're new to cloud services. However, with the right tools and knowledge, you can seamlessly deploy your application using NestJS and PostgreSQL on AWS. In this guide, we’ll take you through the entire process step-by-step, ensuring that you have all the coding examples and insights you need to succeed.

What is NestJS?

NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It uses TypeScript by default and is heavily inspired by Angular, which makes it an excellent choice for developers familiar with front-end frameworks.

Key Features of NestJS

  • Modular Architecture: Easily manage your application’s structure.
  • Dependency Injection: Enhance code reusability and testability.
  • Rich Ecosystem: Integrates seamlessly with various libraries and tools.
  • Microservices Support: Build distributed systems with ease.

What is PostgreSQL?

PostgreSQL is an advanced open-source relational database management system (RDBMS) known for its reliability, feature robustness, and performance. It supports various data types and offers powerful querying capabilities.

Why Use PostgreSQL?

  • ACID Compliance: Ensures reliable transactions.
  • Extensibility: Add custom functions and data types.
  • JSON Support: Handle unstructured data easily.

Use Cases

Using NestJS with PostgreSQL is ideal for applications that require robust back-end services and reliable data management, such as:

  • E-commerce platforms
  • Real-time chat applications
  • Data analytics dashboards
  • Content management systems (CMS)

Prerequisites

Before we dive into the deployment process, make sure you have the following:

  • An AWS account
  • Basic knowledge of TypeScript and Node.js
  • PostgreSQL installed locally for development

Step-by-Step Deployment Guide

Step 1: Set Up Your NestJS Application

First, let’s create a new NestJS application. Open your terminal and run the following commands:

npm i -g @nestjs/cli
nest new my-nest-app
cd my-nest-app

Step 2: Install PostgreSQL Dependencies

To connect your NestJS application to PostgreSQL, you need to install the necessary packages:

npm install @nestjs/typeorm typeorm pg

Step 3: Configure TypeORM

Create a new file named ormconfig.json in the root directory of your NestJS application. This file will hold your PostgreSQL connection settings:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "your_username",
  "password": "your_password",
  "database": "your_database",
  "synchronize": true,
  "logging": true,
  "entities": ["dist/**/*.entity{.ts,.js}"]
}

Step 4: Create a Sample Entity

Next, let’s create a sample entity. In your src folder, create a directory named entities and add a new file called user.entity.ts:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

Step 5: Set Up Your Application Module

Now, modify your app.module.ts to include TypeORM and your newly created entity:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot(),
    TypeOrmModule.forFeature([User]),
  ],
})
export class AppModule {}

Step 6: Create a RESTful API

Let’s create a simple controller to handle API requests for the User entity. Create a file named user.controller.ts in the src folder:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Controller('users')
export class UserController {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  @Post()
  create(@Body() user: User) {
    return this.usersRepository.save(user);
  }

  @Get()
  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }
}

Step 7: Testing Locally

Run your application locally to test the API:

npm run start

You can use tools like Postman or curl to test your endpoints.

Step 8: Deploying on AWS

Now that your application is ready, let’s deploy it on AWS. Here’s how:

  1. Create an EC2 Instance:
  2. Go to the AWS Management Console and launch a new EC2 instance using an Amazon Linux or Ubuntu image.
  3. Set up security groups to allow HTTP (port 80) and SSH (port 22) access.

  4. Install Node.js and PostgreSQL:

  5. SSH into your EC2 instance: bash ssh -i your-key.pem ec2-user@your-ec2-public-ip
  6. Install Node.js and PostgreSQL: bash sudo yum update sudo yum install -y nodejs npm postgresql

  7. Clone Your Repository:

  8. Clone your NestJS application from your version control (e.g., GitHub): bash git clone your-repo-url cd your-app

  9. Install Dependencies:

  10. Run: bash npm install

  11. Run Your Application:

  12. Start your application using a process manager like PM2: bash npm install -g pm2 pm2 start dist/main.js

Step 9: Setting Up PostgreSQL on AWS RDS

  1. Create an RDS Instance:
  2. Navigate to the RDS service in the AWS console and create a new PostgreSQL instance.
  3. Set the security group to allow traffic from your EC2 instance.

  4. Update ormconfig.json:

  5. Update the configuration file with your RDS instance details.

Step 10: Troubleshooting Common Issues

  • Database Connection Errors: Ensure that your RDS instance is accessible from your EC2 instance.
  • CORS Issues: If your API is not accessible, check your CORS configuration in the NestJS application.

Conclusion

Deploying a full-stack application using NestJS and PostgreSQL on AWS provides a scalable and efficient way to manage your application. By following the steps outlined in this guide, you can set up your application and database in the cloud, ensuring that you’re well-equipped to handle production traffic. Now it's time to dive deeper into coding and refining your application for optimal performance!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.