Environment configuration and multi-environment management
Basic Concepts of Environment Configuration
Environment configuration is an essential aspect of Express application development. The requirements for development, testing, and production environments vary, such as database connections, API keys, and log levels. Proper configuration ensures seamless operation across different environments.
// Basic environment variable example
const port = process.env.PORT || 3000;
const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/dev_db';
Managing Environment Variables with dotenv
The dotenv package loads environment variables from a .env
file into process.env
. First, install it:
npm install dotenv
Create a .env
file:
PORT=3000
DB_URL=mongodb://localhost:27017/prod_db
API_KEY=your_api_key_here
Load the configuration in your application:
require('dotenv').config();
const express = require('express');
const app = express();
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
Multi-Environment Configuration Strategies
Configuration File Approach
Create a config
directory with environment-specific files:
/config
├── default.js
├── development.js
├── test.js
└── production.js
default.js
contains common configurations:
module.exports = {
logLevel: 'info',
timeout: 5000
};
development.js
extends the default configuration:
const config = require('./default');
module.exports = Object.assign({}, config, {
dbUrl: 'mongodb://localhost:27017/dev_db',
debug: true
});
Environment Variable Override Approach
Specify the environment using NODE_ENV
:
NODE_ENV=production node app.js
Dynamically load configurations in the code:
const env = process.env.NODE_ENV || 'development';
const config = require(`./config/${env}`);
app.set('dbUrl', config.dbUrl);
Advanced Configuration Techniques
Configuration Validation
Use joi
to validate environment variables:
const Joi = require('joi');
const schema = Joi.object({
PORT: Joi.number().required(),
DB_URL: Joi.string().uri().required()
});
const { error, value } = schema.validate(process.env);
if (error) {
throw new Error(`Configuration validation failed: ${error.message}`);
}
Handling Sensitive Information
For sensitive data, consider encryption or key management services:
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient();
async function getSecret(secretName) {
const [version] = await client.accessSecretVersion({
name: secretName
});
return version.payload.data.toString();
}
Environment-Specific Middleware
Load different middleware based on the environment:
if (process.env.NODE_ENV === 'development') {
app.use(require('morgan')('dev'));
app.use(require('errorhandler')());
}
if (process.env.NODE_ENV === 'production') {
app.use(require('compression')());
app.use(require('helmet')());
}
Special Handling for Test Environments
Test environments may require mocked services:
if (process.env.NODE_ENV === 'test') {
const { setupMockDatabase } = require('./test/mocks');
setupMockDatabase();
// Disable logs to avoid interfering with test output
app.set('logger', { info: () => {}, error: () => {} });
}
Deployment Configuration Practices
Docker Environment Variables
Pass environment variables in Docker:
FROM node:14
ENV NODE_ENV=production
COPY . .
RUN npm install
CMD ["node", "app.js"]
Override when starting the container:
docker run -e "DB_URL=mongodb://prod-db:27017/app" my-app
Kubernetes Configuration
Use ConfigMap and Secret:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
NODE_ENV: "production"
LOG_LEVEL: "info"
Hot Reload for Configuration
Enable configuration hot reload in development:
const fs = require('fs');
const path = require('path');
let config = require('./config/development');
fs.watch(path.join(__dirname, 'config/development.js'), () => {
delete require.cache[require.resolve('./config/development')];
config = require('./config/development');
console.log('Configuration reloaded');
});
Cross-Team Collaboration Configuration
Use configuration templates to help new team members get started quickly:
.env.example
Example content:
# Application configuration
PORT=3000
# Database configuration
DB_URL=mongodb://localhost:27017/dev_db
# Third-party API
API_KEY=your_api_key_here
Version Control for Configuration
Separate sensitive information from configuration. Recommended .gitignore
:
# Ignore local environment files
.env
*.local.env
# Ignore sensitive configurations
config/local*.js
Commit example files:
.env.example
config/example.js
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:项目结构与目录组织规范
下一篇:路由分层与模块化设计