# Production Node.js Stack

> Production Node.js with Nginx, PM2, PostgreSQL, Redis, and BullMQ for job queues

- Category: Full Web Stacks
- Difficulty: advanced
- Components: nginx, nodejs, pm2, postgres, redis
- Tags: nodejs, express, production, pm2, nginx, postgres, redis, bullmq
- Source: https://docker.recipes/full-stacks/production-nodejs-stack

## Overview

Node.js is a JavaScript runtime built on Chrome's V8 engine that enables server-side JavaScript execution, revolutionizing web development by allowing developers to use a single language across their entire stack. PM2 is a production-grade process manager for Node.js applications that provides clustering, monitoring, and automatic restarts, making it the de facto standard for running Node.js in production environments. This production stack combines Node.js with PM2 for robust application management, NGINX as a high-performance reverse proxy, PostgreSQL for reliable ACID-compliant data storage, and Redis powering both caching and BullMQ job queuing. The architecture creates a scalable, fault-tolerant system where NGINX handles SSL termination and load balancing, PM2 manages Node.js processes in cluster mode, PostgreSQL ensures data integrity, and Redis enables fast session storage and background job processing. This combination is ideal for high-traffic web applications, API services, and enterprise systems that require both performance and reliability. Startups scaling beyond basic deployments, enterprises modernizing legacy systems, and development teams building real-time applications will find this stack provides the production-grade infrastructure needed to handle demanding workloads while maintaining operational simplicity.

## Features

- PM2 cluster mode with automatic load balancing across CPU cores
- NGINX reverse proxy with SSL/TLS termination and HTTP/2 support
- PostgreSQL ACID compliance with advanced transaction support and JSON/JSONB capabilities
- Redis sub-millisecond caching with rich data structures and pub/sub messaging
- BullMQ job queue processing with Redis-backed persistence and retry mechanisms
- Event-driven Node.js architecture with non-blocking I/O operations
- PM2 automatic restart and crash recovery with zero-downtime deployments
- PostgreSQL full-text search and complex query optimization for analytics

## Use cases

- E-commerce platforms requiring inventory management, order processing, and payment workflows
- SaaS applications with user authentication, subscription billing, and background email processing
- Real-time collaboration tools needing WebSocket connections and live data synchronization
- Content management systems with image processing, search indexing, and publication workflows
- API backends for mobile applications handling user sessions and push notifications
- Financial applications requiring transaction integrity and audit trails with background reporting
- Social media platforms with user-generated content, real-time feeds, and notification systems

## Prerequisites

- Minimum 2GB RAM (PostgreSQL requires 256MB+, Redis 512MB+, Node.js cluster 1GB+)
- Docker and Docker Compose installed with support for multi-service orchestration
- Basic understanding of Node.js ecosystem, npm/yarn, and JavaScript async patterns
- Familiarity with SQL queries and PostgreSQL database administration
- Knowledge of NGINX configuration syntax for reverse proxy and SSL setup
- Understanding of process management concepts and PM2 ecosystem configuration

## docker-compose.yml

```yaml
services:
  nginx:
    image: nginx:alpine
    container_name: node-nginx
    restart: unless-stopped
    ports:
      - "${NGINX_PORT:-80}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./public:/app/public:ro
    depends_on:
      - app

  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: node-app
    restart: unless-stopped
    command: pm2-runtime ecosystem.config.js
    volumes:
      - ./:/app
      - /app/node_modules
    environment:
      - NODE_ENV=production
      - PORT=3000
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379
      - SESSION_SECRET=${SESSION_SECRET}
    depends_on:
      - db
      - redis

  worker:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: node-worker
    restart: unless-stopped
    command: node dist/worker.js
    volumes:
      - ./:/app
      - /app/node_modules
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis

  db:
    image: postgres:16-alpine
    container_name: node-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    container_name: node-redis
    restart: unless-stopped
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:
```

## .env

```bash
# Node.js Production Stack
NGINX_PORT=80

# App
SESSION_SECRET=your-session-secret

# Database
DB_USER=node
DB_PASSWORD=node_password
DB_NAME=node_app
```

## Usage notes

- Create Dockerfile with Node.js and PM2
- Create ecosystem.config.js for PM2 cluster mode
- Run migrations with your ORM (Prisma, TypeORM, etc.)
- Worker processes BullMQ jobs from Redis
- PM2 handles process management and clustering
- Scale workers: docker compose up -d --scale worker=3

## Troubleshooting

- PM2 processes not starting: Check ecosystem.config.js syntax and ensure Node.js dependencies are installed with npm ci
- NGINX 502 Bad Gateway: Verify Node.js app is running on port 3000 and container networking allows nginx to reach app service
- PostgreSQL connection refused: Ensure DATABASE_URL format is correct and database container is healthy before app starts
- Redis connection timeout: Check REDIS_URL configuration and verify Redis container is accessible on port 6379
- BullMQ jobs stuck in waiting: Confirm worker container is running and can connect to Redis, check worker.js for error handling
- High memory usage: Monitor PM2 processes with pm2 monit and adjust cluster instances in ecosystem.config.js based on available RAM

