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.

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.
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.
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.
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:
Run in your terminal to get started locally.
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);
},
});
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:
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.
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.
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.
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.
@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, () => {});
};
npm run start:dev.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.
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.
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.
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.
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.
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.
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.
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.
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.