Chapter 9: Deployment & Production
Deploying and running your NestJS app in production requires careful planning. This chapter covers Dockerization, CI/CD, environment management, health checks, logging, monitoring, scaling, and troubleshooting. We’ll walk through practical steps and explain how to make your app production-ready.
9.1 Preparing for Production
Before deploying, ensure your application is production-ready.Production Checklist
Environment Configuration:- Set
NODE_ENV=production - Use environment variables for all secrets
- Remove hardcoded credentials
- Validate all environment variables
- Enable CORS with specific origins
- Set secure HTTP headers (helmet)
- Use HTTPS
- Validate all inputs
- Rate limiting enabled
- Build optimized bundle (
npm run build) - Remove dev dependencies
- Enable compression
- Optimize database queries
- Use connection pooling
- Health checks configured
- Logging set up
- Error tracking (Sentry, etc.)
- Metrics collection
- All tests passing
- Tested in staging environment
- Load testing completed
- Security audit done
9.2 Dockerizing Your App
Containerization makes deployment consistent and portable. Docker packages your app and dependencies into a single image.Basic Dockerfile
Optimized Dockerfile
.dockerignore
Docker Compose
- Use multi-stage builds for smaller images
- Keep images minimal (alpine base, no dev dependencies)
- Use
.dockerignoreto exclude unnecessary files - Run as non-root user
- Add health checks
- Use specific version tags
9.3 Environment Variables
Store secrets and configuration in environment variables. Never commit secrets to version control.Using @nestjs/config
Environment Files
Using Config Service
joi) to ensure required environment variables are set and validate their values.
9.4 Health Checks
Health checks help load balancers and orchestrators know if your app is healthy.Installing Terminus
Health Check Controller
Custom Health Indicators
9.5 Logging & Monitoring
Proper logging and monitoring are essential for production applications.NestJS Logger
Structured Logging
Winston Integration
Error Tracking with Sentry
- Log errors and warnings
- Use structured logs (JSON) for cloud platforms
- Monitor logs and metrics in real time
- Set up alerts for critical errors
- Don’t log sensitive information
- Use log levels appropriately
9.6 CI/CD Pipelines
Automate build, test, and deployment with CI/CD pipelines.GitHub Actions Workflow
GitLab CI
9.7 Kubernetes Deployment
Deploy NestJS applications to Kubernetes for scalability and reliability.Deployment Manifest
Service Manifest
9.8 Scaling & High Availability
Scale your application to handle increased load.Horizontal Scaling
- Run multiple instances behind a load balancer
- Use Kubernetes HPA (Horizontal Pod Autoscaler)
- Scale based on CPU, memory, or custom metrics
Vertical Scaling
- Increase instance size (more CPU/memory)
- Use for applications that can’t scale horizontally
- Limited by single instance capacity
Database Scaling
- Use read replicas for read-heavy workloads
- Shard databases for very large datasets
- Use connection pooling
- Cache frequently accessed data
Caching
9.9 Performance Optimization
Optimize your application for production performance.Enable Compression
Connection Pooling
Query Optimization
- Use indexes on frequently queried columns
- Optimize N+1 queries
- Use select to limit fields
- Implement pagination
9.10 Troubleshooting & Maintenance
Monitor and maintain your production application.Monitoring
- Monitor CPU, memory, and response times
- Track error rates
- Monitor database performance
- Set up alerts for anomalies
Logging
- Centralize logs (ELK, CloudWatch, etc.)
- Search and filter logs
- Set up log retention policies
- Monitor log volumes
Backup & Recovery
- Regular database backups
- Test restore procedures
- Document recovery steps
- Store backups securely
Updates
- Regularly update dependencies
- Test updates in staging
- Use semantic versioning
- Document breaking changes
9.11 Summary
You’ve learned how to deploy and maintain NestJS applications in production: Key Concepts:- Docker: Containerize applications
- CI/CD: Automate deployment
- Health Checks: Monitor application health
- Logging: Track application behavior
- Monitoring: Observe production systems
- Scaling: Handle increased load
- Kubernetes: Orchestrate containers
- Use environment variables for configuration
- Containerize with Docker
- Implement health checks
- Set up proper logging
- Monitor production systems
- Scale horizontally
- Regular backups and updates