Updated Nov 24, 202614 min read

How to Deploy a NestJS App to AWS

Run a NestJS API with Postgres on AWS, from RDS, TypeORM and ECS Fargate by hand to provisioning the database and queues from your TypeScript code.

Illustration for How to Deploy a NestJS App to AWS

To deploy a NestJS app with Postgres to AWS, run the container on ECS Fargate, put the database on RDS for PostgreSQL, connect TypeORM over SSL with credentials from Secrets Manager, and open port 5432 only to the app. Encore removes most of that work: the database is declared next to your Nest modules and provisioned in your own AWS account on deploy.

Below are both routes, plus Lambda and Elastic Beanstalk.

Which AWS option is best for a NestJS app with Postgres?

RankOptionHow it worksPostgresBest fit
1EncoreNest modules behind Encore endpoints, with the database and Pub/Sub declared in code and provisioned in your AWS accountRDS, created and migrated on deployNest apps with a database, queues or more than one environment
2ECS on Fargate (or ECS Express Mode)You build an image, push it to ECR and run it as a service behind a load balancerRDS, security groups and Secrets Manager set up by youOne containerized Nest API, with a team that owns the AWS resources in CDK or Terraform
3AWS Lambda with serverless-expressThe Express app inside Nest runs as one functionRDS plus RDS Proxy, set up by youSmall APIs with low or spiky traffic and short requests
4Elastic BeanstalkAWS runs npm start or a Procfile on EC2 instances behind a load balancerRDS created separately or attached to the environmentA single Nest app that fits one Beanstalk environment

Verdict. ECS on Fargate is the standard AWS answer and works well when someone owns the VPC, RDS, IAM and the CDK or Terraform around them. Encore ranks first for a Nest app with Postgres because the database, its migrations and the queues come from the same code that uses them, locally and in AWS. Teams bring their own agents, and Encore provides the environments, the system context and the controls, so an agent can add a module, a migration and a topic in one change.

Compare what each option covers
CapabilityEncoreECS on FargateLambda with serverless-expressElastic Beanstalk
ComputeECS Fargate or EKS, chosen per environmentECS FargateLambdaEC2 instances
PostgresDeclared in code, RDS in productionCreated separately in RDSCreated separately in RDS, usually with RDS ProxyCreated separately, or attached to the environment
Secretssecret() in code, stored in Secrets ManagerSecrets Manager ARNs in the task definitionEnvironment variables or Secrets Manager callsEnvironment properties or Secrets Manager
NetworkingVPC, load balancer and security groups set up for youYou configure VPC, ALB, security groups and rolesAPI Gateway, execution role and VPC access configured by youMostly managed, extra resources configured by you
Local developmentencore run starts Postgres, Pub/Sub and your servicesYour own Compose setup and a local PostgresEmulators, or deploy to testYour own local setup
Infrastructure codeNone to write for the declared resourcesCDK, Terraform or CLI scriptsSAM, CDK or Terraform.ebextensions and platform hooks

What does a NestJS app need on AWS?

  • A container image in Amazon ECR and something that runs it: ECS on Fargate, a Lambda function or a Beanstalk environment.
  • A VPC with public and private subnets, an Application Load Balancer and security groups between the load balancer, the tasks and the database.
  • Postgres on Amazon RDS, with its credentials stored in Secrets Manager and injected at startup.
  • IAM roles that let each task pull its image, write logs and read the secrets it needs.
  • A description of all of that in CDK or Terraform, plus a local setup that resembles it.

How do you connect NestJS to RDS Postgres with TypeORM?

On the plain AWS path, TypeORM reads the connection string from an environment variable that ECS fills from Secrets Manager. RDS for PostgreSQL 15 and later rejects unencrypted connections by default through rds.force_ssl, so pass the RDS certificate bundle instead of turning verification off. This was type-checked with NestJS 12.6, @nestjs/typeorm 12.0 and TypeORM 1.1:

// src/app.module.ts (plain AWS) import { readFileSync } from "node:fs"; import { Module } from "@nestjs/common"; import { TypeOrmModule } from "@nestjs/typeorm"; import { Order } from "./orders/order.entity"; import { OrdersModule } from "./orders/orders.module"; @Module({ imports: [ TypeOrmModule.forRootAsync({ useFactory: () => ({ type: "postgres", url: process.env.DATABASE_URL, entities: [Order], synchronize: false, // RDS certificate bundle, baked into the image. ssl: { ca: readFileSync("/app/global-bundle.pem", "utf8") }, }), }), OrdersModule, ], }) export class AppModule {}

Keep synchronize off in production and run TypeORM migrations as a one-off ECS task before each service update. The RDS instance sits in private subnets, and its security group allows port 5432 only from the security group of the ECS tasks. Most "connection timed out" errors on a first deploy come from that rule being missing.

How do you keep your Nest modules and provision AWS from the code?

Nest modules (Postgres, Pub/Sub topics) declared in code, deployed by the Encore Platform into AWS: Fargate, RDS, SNS/SQS

Encore works alongside NestJS: Nest keeps the modules, providers and TypeORM repositories, and Encore provisions the infrastructure the code declares in your own AWS or GCP account. The approach follows the NestJS guide in the Encore docs. The quickest start is the NestJS example app, with TypeORM added on top:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create orders --example=ts/nestjs$ cd orders && npm i @nestjs/typeorm typeorm

An encore.service.ts file at the root of src marks the directory as one service, and the database is one object whose schema comes from SQL files in src/migrations:

// src/db.ts import { SQLDatabase } from "encore.dev/storage/sqldb"; // Docker Postgres under `encore run`, RDS when deployed to AWS. // Encore applies the SQL files in ./migrations on every deploy. export const DB = new SQLDatabase("orders", { migrations: "./migrations" });
-- src/migrations/1_create_orders.up.sql CREATE TABLE orders ( id SERIAL PRIMARY KEY, email TEXT NOT NULL, total_cents INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

TypeORM connects through the connection string Encore provides, and synchronize stays off because Encore applies the migrations, locally and on every deploy. The entity, the service and the Nest module are ordinary TypeORM and Nest code:

// src/app.module.ts import { Module } from "@nestjs/common"; import { TypeOrmModule } from "@nestjs/typeorm"; import { DB } from "./db"; import { Order } from "./orders/order.entity"; import { OrdersModule } from "./orders/orders.module"; @Module({ imports: [ TypeOrmModule.forRoot({ type: "postgres", url: DB.connectionString, entities: [Order], // The schema comes from Encore's SQL migrations, not from TypeORM. synchronize: false, }), OrdersModule, ], }) export class AppModule {}
// src/orders/order.entity.ts import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from "typeorm"; @Entity({ name: "orders" }) export class Order { @PrimaryGeneratedColumn() id!: number; @Column() email!: string; @Column({ name: "total_cents" }) totalCents!: number; @Column({ default: "pending" }) status!: string; @CreateDateColumn({ name: "created_at", type: "timestamptz" }) createdAt!: Date; } // src/orders/orders.service.ts import { Injectable } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { Repository } from "typeorm"; import { Order } from "./order.entity"; @Injectable() export class OrdersService { constructor(@InjectRepository(Order) private readonly orders: Repository<Order>) {} create(email: string, totalCents: number): Promise<Order> { return this.orders.save(this.orders.create({ email, totalCents })); } findOne(id: number): Promise<Order | null> { return this.orders.findOneBy({ id }); } }

OrdersModule registers TypeOrmModule.forFeature([Order]) and exports OrdersService, as in any Nest app. Nest then starts as a standalone application context instead of an HTTP server, which gives Encore endpoints the same services a controller would have injected:

// src/applicationContext.ts import "reflect-metadata"; import { NestFactory } from "@nestjs/core"; import { AppModule } from "./app.module"; import { OrdersModule } from "./orders/orders.module"; import { OrdersService } from "./orders/orders.service"; // Nest boots without an HTTP server; Encore endpoints call into it. const applicationContext: Promise<{ ordersService: OrdersService }> = NestFactory.createApplicationContext(AppModule).then((app) => ({ ordersService: app.select(OrdersModule).get(OrdersService, { strict: true }), })); export default applicationContext;

Each route in the controller becomes an Encore api endpoint that calls the Nest service, and a Pub/Sub topic declared in the same file moves the confirmation email out of the request:

// src/orders/orders.api.ts import { api, APIError } from "encore.dev/api"; import { Subscription, Topic } from "encore.dev/pubsub"; import applicationContext from "../applicationContext"; interface OrderResponse { id: number; email: string; totalCents: number; status: string; } // A local broker under `encore run`, SNS with SQS when deployed to AWS. export const orderPlaced = new Topic<{ orderId: number; email: string }>("order-placed", { deliveryGuarantee: "at-least-once", }); // Encore endpoints take the place of the Nest controller; OrdersService is unchanged. export const create = api( { expose: true, method: "POST", path: "/orders" }, async (p: { email: string; totalCents: number }): Promise<OrderResponse> => { if (!p.email || p.totalCents <= 0) { throw APIError.invalidArgument("email and a positive totalCents are required"); } const { ordersService } = await applicationContext; const o = await ordersService.create(p.email, p.totalCents); await orderPlaced.publish({ orderId: o.id, email: o.email }); return { id: o.id, email: o.email, totalCents: o.totalCents, status: o.status }; }, ); // Internal only: other services look orders up by ID, and a public route would add an owner check. export const get = api( { expose: false, method: "GET", path: "/orders/:id" }, async ({ id }: { id: number }): Promise<OrderResponse> => { const { ordersService } = await applicationContext; const o = await ordersService.findOne(id); if (!o) throw APIError.notFound("order not found"); return { id: o.id, email: o.email, totalCents: o.totalCents, status: o.status }; }, ); // Delivery is at least once, so keep the handler safe to run twice per order. const _ = new Subscription(orderPlaced, "send-confirmation", { handler: async ({ orderId, email }) => { console.log("sending confirmation", orderId, email); }, });
Two endpoints and a subscriber, running the unchanged Nest OrdersService.

encore run starts Postgres in Docker, applies the migration, boots the Nest context and serves the endpoints, so the topic and subscriber run on your machine as well. The expected response looks like:

~/orders
$ encore run$ curl -X POST localhost:4000/orders -d '{"email":"ana@example.com","totalCents":4200}'{"id":1,"email":"ana@example.com","totalCents":4200,"status":"pending"}

After you connect your AWS account in the Encore dashboard and push, the next deploy creates the VPC, load balancer, Fargate service, RDS instance and SNS with SQS in that account. The preview environments that Encore hosts for each pull request run the same migrations against their own database.

With the database and the topic in the application code, an AI coding agent that adds a new Nest module can write the migration, the entity and the topic in the same change, and run the result under encore run before it reaches AWS. Nothing about the change hides in a console setting the agent cannot see.

Good to know

Nest controllers, guards and interceptors are replaced by Encore endpoints and Encore's own auth handler, so the HTTP layer is a real code change, while modules, providers, services and TypeORM repositories carry over. Existing RDS databases can be imported instead of creating new ones, and encore build docker produces a standard image if you want to run the containers yourself. The NestJS vs Encore comparison covers where the two overlap.

How do you run NestJS on ECS Fargate?

Amazon ECS

ECS on Fargate runs the Nest app as a container on capacity AWS manages. A multi-stage Dockerfile builds the app with dev dependencies, ships only dist and the production node_modules, adds the RDS certificate bundle for the TypeORM connection above, and runs as the node user that the official image already includes:

FROM node:24-slim AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build && npm prune --omit=dev FROM node:24-slim WORKDIR /app ENV NODE_ENV=production COPY --from=build --chown=node:node /app/node_modules ./node_modules COPY --from=build --chown=node:node /app/dist ./dist # Pinned by checksum; update it on purpose when AWS rotates the bundle. ADD --chmod=644 --checksum=sha256:90a6f1a7978a1b1b096dca6c57511ca48d3b8cf052f8e704baf358f34ea2f21b \ https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /app/global-bundle.pem USER node EXPOSE 3000 CMD ["node", "dist/main.js"]

The image is pushed to ECR, and the task definition references the database URL in Secrets Manager rather than putting it in a plain environment variable, which ECS injects when the task starts:

"secrets": [ { "name": "DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:nest/database-url" } ]

ECS Express Mode shortens the compute part: from an image and two IAM roles it creates the Fargate service, an Application Load Balancer with HTTPS and autoscaling. It is the AWS replacement for App Runner, which closed to new customers in 2026.

Good to know

Beyond the Dockerfile, the RDS instance, its subnet group and security group, the secret, the task execution role and its permission to read that secret, the log group and the target group are separate resources, usually described in CDK or Terraform, next to a Compose file locally that approximates the same setup. The Node.js on AWS guide goes through those pieces in more detail.

Can you run NestJS on AWS Lambda?

AWS Lambda

@codegenie/serverless-express adapts the Express app that Nest runs on to the event format Lambda passes in. Version 5 targets the Node.js 24 Lambda runtime and only supports promise-based handlers:

import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { ExpressAdapter } from '@nestjs/platform-express'; import serverlessExpress from '@codegenie/serverless-express'; import type { Context, Handler } from 'aws-lambda'; import express from 'express'; import { AppModule } from './app.module'; let server: Handler | undefined; async function bootstrap(): Promise<Handler> { const expressApp = express(); const app = await NestFactory.create(AppModule, new ExpressAdapter(expressApp)); await app.init(); return serverlessExpress({ app: expressApp }); } // Reuse the Nest app across invocations of a warm Lambda container. export const handler = async (event: unknown, context: Context) => { server ??= await bootstrap(); return server(event, context, () => {}); };
The whole Nest app becomes one function behind API Gateway or a function URL.

Key features

  • You pay per request and duration, which suits low or uneven traffic.
  • Scaling to zero and back is handled by Lambda.
  • The same Nest modules still run as a normal server locally with npm run start:dev.

Good to know

Nest builds its whole module graph on a cold start, so a larger app pays for that on the first request to each new container. A function can run for up to 15 minutes, but API Gateway has its own shorter integration timeout, and many concurrent functions opening Postgres connections usually calls for RDS Proxy, which is one more resource to define in SAM, CDK or Terraform.

When does Elastic Beanstalk fit a NestJS app?

AWS Elastic Beanstalk

Elastic Beanstalk has a managed Node.js platform that runs the app on EC2 instances behind a load balancer it creates. It uses a Procfile at the root if there is one and otherwise runs npm start, so a Nest app only needs a start script that runs the built dist/main.js.

Key features

  • The Node.js 24 platform on Amazon Linux 2023 is current, with a Docker platform as the alternative.
  • Rolling deployments, health checks and auto scaling are built in.
  • An RDS instance can be attached to the environment, though a separately created one is easier to keep when the environment changes.

Good to know

Each environment is one application, so a queue worker or a second Nest service means another environment, and SQS, S3 and IAM around it are still set up separately. Custom configuration lives in .ebextensions and platform hooks, which are hard to test before a deploy. The Elastic Beanstalk alternatives guide covers where teams usually move from there.

Which option should you choose?

  • Encore if the Nest app has a database, queues or several environments and you want them running locally and in your AWS account from the same code, so a coding agent can change those resources in the same review as the Nest modules.
  • ECS on Fargate or ECS Express Mode for a single containerized Nest API when the team is comfortable owning RDS, IAM and networking around it.
  • Lambda with serverless-express for small APIs with spiky traffic and short requests.
  • Elastic Beanstalk for one Nest app that fits its environment model.

Verdict. The manual routes all leave RDS, the TypeORM SSL setup, Secrets Manager, IAM and networking to be described somewhere, which is where CDK or Terraform comes in. Encore derives those resources from the code that uses them, which is why it comes first for a Nest app with Postgres. Teams bring their own agents, and Encore provides the environments, the system context and the controls, so an agent that adds a Nest module can write the migration, the entity and the topic in the same change. A well-organized codebase moves more easily either way, and the NestJS project structure guide covers how to lay out modules.

Frequently asked questions

What is the best way to deploy NestJS to AWS?

For a single container, ECS on Fargate is the usual choice: push an image to ECR and run it as a service behind a load balancer, or let ECS Express Mode create the service, load balancer and HTTPS for you. Postgres goes on RDS in private subnets, with the connection string in Secrets Manager.

How do I connect NestJS to Amazon RDS for PostgreSQL with TypeORM?

Register TypeOrmModule.forRootAsync with type postgres, the connection URL from an environment variable injected from Secrets Manager, synchronize set to false, and ssl set to the RDS CA bundle. RDS for PostgreSQL 15 and later rejects unencrypted connections by default. The RDS security group must allow port 5432 from the security group of the ECS tasks.

Can I run NestJS on AWS Lambda?

Yes. The @codegenie/serverless-express package wraps the Express app that Nest runs on as a Lambda handler behind API Gateway or a function URL. Cold starts grow with the size of the Nest module graph, and many concurrent functions talking to Postgres usually need RDS Proxy.

Should I use ECS Fargate or Elastic Beanstalk for NestJS?

Elastic Beanstalk runs npm start or a Procfile on EC2 instances behind a load balancer, which suits a single app. ECS on Fargate runs a container image with task roles and per-service scaling, and it is the better base once there is a worker or a second service.

Can I keep my Nest modules and deploy them to AWS with Encore?

Yes. Nest runs as a standalone application context for modules, providers and TypeORM repositories, Encore endpoints replace the controllers, and the database and Pub/Sub topics are declared in the application code. A deploy to your connected AWS account provisions RDS, SNS with SQS and the Fargate service.

Build TypeScript backends without the infrastructure boilerplate

Encore gives you type-safe APIs, local Postgres and Pub/Sub out of the box, built-in distributed tracing, and automated deploys to your own AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders