docker.recipes

NestJS + PostgreSQL

intermediate

Progressive Node.js framework with TypeORM and PostgreSQL.

Overview

NestJS is a progressive Node.js framework built with TypeScript that leverages decorators and dependency injection to create scalable server-side applications. Inspired by Angular's architecture, NestJS was created by Kamil Myśliwiec in 2017 to bring enterprise-grade structure to Node.js development. The framework combines elements of object-oriented programming, functional programming, and reactive programming, making it particularly attractive for developers familiar with Angular or Spring Boot who want similar architectural patterns in their backend services. This stack pairs NestJS with PostgreSQL through TypeORM, creating a type-safe development environment where database schemas are defined as TypeScript entities and queries are validated at compile time. PostgreSQL's advanced features like JSONB columns, full-text search, and complex query capabilities complement NestJS's modular architecture perfectly. The combination provides ACID compliance for critical business logic while maintaining the flexibility to handle both relational and document-style data within the same application. This configuration is ideal for teams building enterprise applications, SaaS platforms, or complex APIs that require strict type safety, comprehensive testing capabilities, and robust data integrity. The stack excels in scenarios where business logic is complex, data relationships are intricate, and long-term maintainability is crucial. Development teams familiar with Angular will find the learning curve minimal, while the TypeScript foundation ensures excellent IDE support and refactoring capabilities across the entire application stack.

Key Features

  • Decorator-based routing and dependency injection system with Guards, Interceptors, and Pipes for request lifecycle management
  • TypeORM integration with Entity definitions, Repository patterns, and automatic migration generation from TypeScript classes
  • Built-in Swagger documentation generation through decorators that automatically create OpenAPI specifications
  • PostgreSQL JSONB column support for hybrid relational-document data models with full TypeScript type inference
  • Class-validator integration for automatic DTO validation with custom validation decorators and error formatting
  • Modular architecture with lazy-loaded modules, circular dependency resolution, and dynamic module configuration
  • Built-in testing utilities with dependency mocking, e2e testing support, and database transaction rollback for tests
  • Exception filters and custom error handling with PostgreSQL-specific error code interpretation

Common Use Cases

  • 1Enterprise SaaS platforms requiring multi-tenant architecture with complex user permissions and data isolation
  • 2E-commerce backends with inventory management, order processing, and payment integration requiring ACID transactions
  • 3Content management systems with complex taxonomies, full-text search, and media asset relationships
  • 4Financial applications requiring audit trails, transaction integrity, and compliance with regulatory reporting
  • 5Real-time collaboration platforms with WebSocket support, event sourcing, and conflict resolution
  • 6API-first applications serving mobile apps and SPAs with comprehensive authentication and rate limiting
  • 7Data analytics dashboards requiring complex PostgreSQL queries with window functions and aggregations

Prerequisites

  • Docker and Docker Compose installed with minimum 2GB RAM available for PostgreSQL operations
  • Node.js 18+ knowledge and TypeScript familiarity for understanding decorators and advanced types
  • Basic SQL knowledge for writing TypeORM queries and understanding PostgreSQL-specific features
  • Understanding of dependency injection patterns and object-oriented programming concepts
  • Port 3000 available for NestJS application and port 5432 free for PostgreSQL connections
  • Environment variables configured: DB_USER, DB_PASSWORD, and DB_NAME in .env file

For development & testing. Review security settings, change default credentials, and test thoroughly before production use. See Terms

docker-compose.yml

docker-compose.yml
1services:
2 nestjs:
3 build: .
4 container_name: nestjs
5 environment:
6 DB_HOST: postgres
7 DB_PORT: 5432
8 DB_USER: ${DB_USER}
9 DB_PASSWORD: ${DB_PASSWORD}
10 DB_NAME: ${DB_NAME}
11 ports:
12 - "3000:3000"
13 depends_on:
14 - postgres
15 networks:
16 - nest-network
17
18 postgres:
19 image: postgres:16-alpine
20 environment:
21 POSTGRES_DB: ${DB_NAME}
22 POSTGRES_USER: ${DB_USER}
23 POSTGRES_PASSWORD: ${DB_PASSWORD}
24 volumes:
25 - postgres_data:/var/lib/postgresql/data
26 networks:
27 - nest-network
28
29volumes:
30 postgres_data:
31
32networks:
33 nest-network:
34 driver: bridge

.env Template

.env
1DB_NAME=nestjs
2DB_USER=nestjs
3DB_PASSWORD=changeme

Usage Notes

  1. 1Docs: https://docs.nestjs.com/
  2. 2Access at http://localhost:3000
  3. 3Modular architecture with providers and modules
  4. 4TypeORM or Prisma for database access
  5. 5Swagger docs: @nestjs/swagger with /api endpoint
  6. 6Built-in validation with class-validator

Individual Services(2 services)

Copy individual services to mix and match with your existing compose files.

nestjs
nestjs:
  build: .
  container_name: nestjs
  environment:
    DB_HOST: postgres
    DB_PORT: 5432
    DB_USER: ${DB_USER}
    DB_PASSWORD: ${DB_PASSWORD}
    DB_NAME: ${DB_NAME}
  ports:
    - "3000:3000"
  depends_on:
    - postgres
  networks:
    - nest-network
postgres
postgres:
  image: postgres:16-alpine
  environment:
    POSTGRES_DB: ${DB_NAME}
    POSTGRES_USER: ${DB_USER}
    POSTGRES_PASSWORD: ${DB_PASSWORD}
  volumes:
    - postgres_data:/var/lib/postgresql/data
  networks:
    - nest-network

Quick Start

terminal
1# 1. Create the compose file
2cat > docker-compose.yml << 'EOF'
3services:
4 nestjs:
5 build: .
6 container_name: nestjs
7 environment:
8 DB_HOST: postgres
9 DB_PORT: 5432
10 DB_USER: ${DB_USER}
11 DB_PASSWORD: ${DB_PASSWORD}
12 DB_NAME: ${DB_NAME}
13 ports:
14 - "3000:3000"
15 depends_on:
16 - postgres
17 networks:
18 - nest-network
19
20 postgres:
21 image: postgres:16-alpine
22 environment:
23 POSTGRES_DB: ${DB_NAME}
24 POSTGRES_USER: ${DB_USER}
25 POSTGRES_PASSWORD: ${DB_PASSWORD}
26 volumes:
27 - postgres_data:/var/lib/postgresql/data
28 networks:
29 - nest-network
30
31volumes:
32 postgres_data:
33
34networks:
35 nest-network:
36 driver: bridge
37EOF
38
39# 2. Create the .env file
40cat > .env << 'EOF'
41DB_NAME=nestjs
42DB_USER=nestjs
43DB_PASSWORD=changeme
44EOF
45
46# 3. Start the services
47docker compose up -d
48
49# 4. View logs
50docker compose logs -f

One-Liner

Run this command to download and set up the recipe in one step:

terminal
1curl -fsSL https://docker.recipes/api/recipes/nestjs-postgres/run | bash

Troubleshooting

  • TypeORM synchronize: true causing data loss: Set synchronize: false in production and use proper migrations with npm run migration:generate
  • Cannot connect to PostgreSQL from NestJS: Ensure DB_HOST uses service name 'postgres' not 'localhost' in Docker network
  • Class-validator not working on DTOs: Add @UsePipes(ValidationPipe) decorator to controllers and install class-transformer
  • PostgreSQL connection pool exhausted: Configure TypeORM with proper connection limits using extra.max and extra.min pool settings
  • Circular dependency detected in modules: Use forwardRef() wrapper or restructure modules to eliminate circular imports
  • TypeORM entity changes not reflected: Run npm run build to compile TypeScript changes and restart containers with fresh database connection

Community Notes

Loading...
Loading notes...

Download Recipe Kit

Get all files in a ready-to-deploy package

Includes docker-compose.yml, .env template, README, and license

Ad Space