Loading lesson path
Concept visual
Deployment strategies focus on how to deploy and manage your Node.js applications in production. Key aspects of modern Node.js deployment include: Containerization: Package your app and dependencies into a container that runs consistently across environments. Orchestration: Automate container management with tools like Kubernetes or Docker Swarm.
Formula
CI/CD: Automate testing and deployment pipelines.
Cloud - native: Use cloud services and serverless functions.IaC: Define infrastructure as code for reproducible deployments. Observability: Monitor your application's performance and health.
Containers package your application and its dependencies into a standardized unit, ensuring consistent behavior across different environments. Docker is the most popular containerization platform for Node.js applications. Benefits of Docker for Node.js Environment consistency across development, testing, and production Isolation from the host system and other applications
Dockerizing a Node.js Application
Example: Basic Dockerfile for Node.js
Formula
WORKDIR /appCOPY package*.json ./
COPY . .
CMD ["node", "app.js"]
Specifies a base image (Alpine Linux with Node.js 20)
Formula
# Build the image docker build - t my - nodejs - app .
# Run the container docker run - p 8080:8080 my - nodejs - appFormula
Multi - stage builds create smaller, more secure images by separating the build environment from the runtime environment:# Build stage
Formula
WORKDIR /appCOPY package*.json ./
Formula
RUN npm ci -- only = production# Production stage
Formula
WORKDIR /app
COPY -- from = build /app/node_modules ./node_modulesCOPY . . # Set NODE_ENV
Formula
ENV NODE_ENV = production
# Non - root user for securityCMD ["node", "app.js"]
Smaller images (no build tools or dev dependencies) Better security (fewer potential vulnerabilities)
For applications with multiple services (e.g., Node.js app + database), use Docker Compose to define and run multi-container applications:
Example: docker-compose.yml version: '3.8' services: # Node.js application app: build: . ports: - "8080:8080" environment:
Formula
- NODE_ENV = production
- DB_HOST = db
- DB_USER = user
- DB_PASSWORD = password
- DB_NAME = myapp depends_on:
- db restart: unless - stopped# Database db: image: postgres:14 volumes:
- postgres_data:/var/lib/postgresql/data environment:Formula
- POSTGRES_USER = user
- POSTGRES_PASSWORD = password
- POSTGRES_DB = myapp restart: unless - stopped volumes:postgres_data:
Formula
# Start all services docker - compose up
# Start in detached mode docker - compose up - d
# Stop all services docker - compose down