Node.js Express 项目现代化打包部署全指南
一、项目准备阶段
1.1 依赖管理优化
npm install express mongoose dotenv compression helmet
npm install nodemon eslint @types/node --save-dev
1.2 环境变量配置
MONGODB_URI = mongodb+ srv: / / < user> : < password> @cluster0. example. mongodb. net/ production
JWT_SECRET = prod_secure_key_here
PORT = 8080
NODE_ENV = production
二、核心打包流程
2.1 构建脚本配置
{ "scripts" : { "build" : "npm run lint && npm audit" , "start:prod" : "NODE_ENV=production node ./bin/www" , "lint" : "eslint 'src/**/*.js' --fix" }
}
2.2 静态资源优化
if ( process. env. NODE_ENV === 'production' ) { app. use ( express. static ( 'public' , { maxAge : '1y' , setHeaders : ( res, path ) => { if ( express. static. mime. lookup ( path) === 'text/html' ) { res. setHeader ( 'Cache-Control' , 'public, max-age=0' ) } } } ) )
}
三、生产环境部署
3.1 PM2 进程管理
npm install pm2 -g
pm2 start ./bin/www -i max --name "express-api"
3.2 数据库连接优化
mongoose. connect ( process. env. MONGODB_URI , { useNewUrlParser : true , useUnifiedTopology : true , serverSelectionTimeoutMS : 5000 , socketTimeoutMS : 45000
} ) mongoose. connection. on ( 'error' , err => { console. error ( 'MongoDB连接异常:' , err) process. exit ( 1 )
} )
四、进阶部署方案
4.1 Docker 容器化部署
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 8080
CMD [ "npm" , "run" , "start:prod" ]
4.2 Nginx 反向代理配置
upstream nodejs_backend {server localhost:8080;keepalive 32;
}server {listen 80;location / {proxy_pass http://nodejs_backend;proxy_http_version 1.1;proxy_set_header Connection "";}
}
五、自动化部署策略
5.1 GitHub Actions 配置
name : CI/CD Pipeline
on : push : branches : [ main ] jobs : deploy : runs-on : ubuntu- lateststeps : - uses : actions/checkout@v3- uses : actions/setup- node@v3- run : npm ci- run : npm run build- name : Deploy to Serveruses : appleboy/ssh- action@v0.1.10with : host : ${ { secrets.PROD_HOST } } username : ${ { secrets.SSH_USER } } key : ${ { secrets.SSH_KEY } } script : | cd /var/www/express-appgit pull origin mainnpm install --productionpm2 reload all
六、安全与监控
const helmet = require ( 'helmet' )
const rateLimit = require ( 'express-rate-limit' )
app. use ( helmet ( { contentSecurityPolicy : { directives : { defaultSrc : [ "'self'" ] , scriptSrc : [ "'self'" , "'unsafe-inline'" ] } }
} ) )
const limiter = rateLimit ( { windowMs : 15 * 60 * 1000 , max : 100
} )
七、注意事项
环境变量安全:切勿将.env文件提交到版本库 日志管理:建议使用Winston进行结构化日志记录 性能监控:集成APM工具(如New Relic或Prometheus) 错误跟踪:配置Sentry进行异常捕获 CI/CD扩展:可结合SonarQube进行代码质量检测
八、延伸工具推荐
性能分析工具:clinic.js 压力测试:artillery 配置管理:Consul 容器编排:Kubernetes 服务监控:Grafana + Prometheus