Environment Management


nself provides robust environment management for development, staging, and production deployments. This guide covers how to configure and manage different environments for your backend infrastructure.

Environment Overview

nself supports three primary environments, each with specific configurations and purposes:

Development

Local development with debug tools, hot reloading, and relaxed security for rapid iteration.

Staging

Production-like environment for testing and validation before deployment.

Production

Live production environment with security hardening, monitoring, and performance optimization.

Environment Configuration Files

Each environment uses its own configuration file:

my-project/
├── .env.local      # Development environment
├── .env.staging    # Staging environment
├── .env.prod-template # Production template (copy to .env before deployment)
├── .env.example    # Template with all options
└── .gitignore      # Excludes sensitive .env files

Copy .env.prod-template to .env before deployment.

Security Note

Never commit .env.* files (except .env.example) to version control. They contain sensitive information like passwords and API keys.

Development Environment

Default Configuration

# .env.local
PROJECT_NAME=my-backend
ENVIRONMENT=development
DEBUG=true
LOG_LEVEL=debug

# Development-friendly settings
DOMAIN=local.nself.org
SSL_MODE=none
AUTO_RELOAD=true
WATCH_FILES=true

# Development-only services
MAILHOG_ENABLED=true
NHOST_DASHBOARD_ENABLED=true
SWAGGER_ENABLED=true

# Relaxed security for development
JWT_EXPIRES_IN=30d
CORS_ORIGIN=*
SECURE_COOKIES=false

Development Features

  • Hot Reloading: Automatic service restart on code changes
  • Debug Tools: MailHog for email testing, Swagger for API docs
  • Relaxed CORS: Allow all origins for easier testing
  • Extended JWT: Longer token expiration for development
  • Detailed Logging: Debug-level logs for troubleshooting

Starting Development Environment

# Initialize development environment
nself init

# Start all development services
nself up

# Check service status
nself status

# View logs with debug information
nself logs --level debug

Staging Environment

Creating Staging Configuration

# Generate staging configuration
nself config generate --env staging

# Copy and customize
cp .env.example .env.staging

Staging Configuration Example

# .env.staging
PROJECT_NAME=my-backend
ENVIRONMENT=staging
DEBUG=false
LOG_LEVEL=info

# Staging domain
DOMAIN=staging.myapp.com
SSL_MODE=letsencrypt
LETSENCRYPT_EMAIL=admin@myapp.com

# Production-like security
JWT_EXPIRES_IN=7d
CORS_ORIGIN=https://staging-app.myapp.com
SECURE_COOKIES=true

# Disable development tools
MAILHOG_ENABLED=false
SWAGGER_ENABLED=false
NHOST_DASHBOARD_ENABLED=false

# Production-like resources
POSTGRES_MEMORY_LIMIT=1024
HASURA_MEMORY_LIMIT=512
REDIS_MEMORY_LIMIT=256

Deploying to Staging

# Build staging configuration
nself build --env staging

# Deploy to staging server
scp docker-compose.yml staging-server:~/
scp .env.staging staging-server:~/.env

# On staging server
ssh staging-server
nself up --env staging

Production Environment

Production Configuration

# Generate production configuration
nself prod

# This creates .env.prod-template with secure defaults
# Copy to .env before deployment

Copy .env.prod-template to .env before deployment.

Production Settings

# .env.prod-template
# Copy to .env before deployment
PROJECT_NAME=my-backend
ENVIRONMENT=production
DEBUG=false
LOG_LEVEL=warn

# Production domain and SSL
DOMAIN=api.myapp.com
SSL_MODE=letsencrypt
FORCE_SSL=true
LETSENCRYPT_EMAIL=admin@myapp.com

# Strong security
JWT_SECRET=very-long-random-string-here
JWT_EXPIRES_IN=7d
SESSION_TIMEOUT=4h
CORS_ORIGIN=https://myapp.com
SECURE_COOKIES=true
COOKIE_HTTP_ONLY=true

# Performance optimizations
WORKER_PROCESSES=4
CACHE_TTL=3600
GZIP_ENABLED=true

# Resource allocation
POSTGRES_MEMORY_LIMIT=2048
POSTGRES_CPU_LIMIT=2.0
HASURA_MEMORY_LIMIT=1024
HASURA_CPU_LIMIT=1.0

# Monitoring and health checks
HEALTH_CHECK_ENABLED=true
METRICS_ENABLED=true
BACKUP_ENABLED=true
BACKUP_SCHEDULE=0 2 * * *

Production Security Hardening

  • Strong Passwords: Generate secure passwords for all services
  • SSL/TLS: Enable HTTPS with proper certificates
  • Firewall Rules: Restrict access to necessary ports only
  • Regular Updates: Keep all services and dependencies updated
  • Monitoring: Enable comprehensive monitoring and alerting

Environment Switching

Command Line Environment Selection

# Use specific environment
nself up --env development
nself up --env staging
nself up --env production

# Build for specific environment
nself build --env staging

# Check status of specific environment
nself status --env production

Environment Variables

# Set environment via environment variable
export NSELF_ENV=staging
nself up

# Or set in your shell profile
echo 'export NSELF_ENV=staging' >> ~/.bashrc

Environment-Specific Services

Development-Only Services

# Services only in development
MAILHOG_ENABLED=true          # Email testing
NHOST_DASHBOARD_ENABLED=true  # Visual dashboard
SWAGGER_ENABLED=true          # API documentation
ADMINER_ENABLED=true          # Database browser

Production-Only Services

# Services only in production
MONITORING_ENABLED=true       # Prometheus/Grafana
LOG_AGGREGATION=true         # Centralized logging
BACKUP_SERVICE=true          # Automated backups
SECURITY_SCANNER=true        # Vulnerability scanning

Multi-Environment Deployment

CI/CD Pipeline Example

# .github/workflows/deploy.yml
name: Deploy to Environments
on:
  push:
    branches: [main, staging, develop]

jobs:
  deploy-dev:
    if: github.ref == 'refs/heads/develop'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to Development
        run: |
          nself build --env development
          nself deploy --env development

  deploy-staging:
    if: github.ref == 'refs/heads/staging'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to Staging
        run: |
          nself build --env staging
          nself deploy --env staging

  deploy-prod:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to Production
        run: |
          nself build --env production
          nself deploy --env production

Environment Migration

Promoting Between Environments

# Export configuration from staging
nself config export --env staging > staging-config.json

# Import to production (review and modify first)
nself config import --env production < staging-config.json

# Database migration between environments
nself db dump --env staging
nself db restore --env production --file staging_dump.sql

Data Synchronization

# Copy database from production to staging
nself db copy --from production --to staging

# Sync storage files
nself storage sync --from production --to staging

# Reset staging with production data
nself db reset --env staging
nself db restore --env staging --from production

Environment Monitoring

Health Checks

# Check all environments
nself status --all

# Detailed environment health
nself health --env production --verbose

# Monitor specific services
nself monitor --env production --services postgres,hasura

Environment Comparison

# Compare configurations
nself config diff --env1 staging --env2 production

# Compare service versions
nself version --compare staging production

# Check configuration drift
nself config validate --all

Best Practices

Configuration Management

  • Environment Parity: Keep environments as similar as possible
  • Secrets Management: Use secure secret storage for production
  • Configuration Validation: Test configurations before deployment
  • Documentation: Document environment-specific settings

Security Guidelines

  • Principle of Least Privilege: Only enable necessary services
  • Network Isolation: Separate environments with firewalls
  • Access Control: Limit who can deploy to production
  • Audit Logs: Track all configuration changes

Testing Strategy

  • Test in Staging First: Always test changes in staging
  • Automated Testing: Run tests in each environment
  • Rollback Plan: Have a plan to revert changes
  • Monitoring: Monitor deployments closely

Troubleshooting Environments

Common Issues

# Environment not starting
nself logs --env production --tail 100

# Configuration validation
nself config validate --env production

# Service connectivity issues
nself status --env production --verbose

# Resource constraints
nself resources --env production

Environment Reset

# Reset development environment
nself reset --env development

# Clean rebuild
nself down --env staging
nself build --env staging
nself up --env staging

# Force recreation of containers
nself up --env production --recreate

Next Steps

Now that you understand environment management:

Proper environment management is crucial for reliable software delivery. Use separate environments to test changes safely before they reach production.