当前位置: 首页 > news >正文

Node.js Express 项目现代化打包部署全指南

Node.js Express 项目现代化打包部署全指南

在这里插入图片描述

一、项目准备阶段

1.1 依赖管理优化

# 生产依赖安装(示例)
npm install express mongoose dotenv compression helmet# 开发依赖安装
npm install nodemon eslint @types/node --save-dev

1.2 环境变量配置

// .env.production
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 进程管理

# 安装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, // 15分钟max: 100 // 每个IP限制100个请求
})

七、注意事项

  • 环境变量安全:切勿将.env文件提交到版本库
  • 日志管理:建议使用Winston进行结构化日志记录
  • 性能监控:集成APM工具(如New Relic或Prometheus)
  • 错误跟踪:配置Sentry进行异常捕获
  • CI/CD扩展:可结合SonarQube进行代码质量检测

八、延伸工具推荐

  • 性能分析工具:clinic.js
  • 压力测试:artillery
  • 配置管理:Consul
  • 容器编排:Kubernetes
  • 服务监控:Grafana + Prometheus

相关文章:

  • LAN(局域网)和WAN(广域网)
  • osgEarth中视角由跟随模式切换到漫游模式后没有鼠标拖拽功能问题分析及解决方法
  • 【VSCode】在远程服务器Linux 系统 实现 Anaconda 安装与下载
  • jenkins使用Send build artifacts over SSH发布jar包目录配置
  • AUTOSAR 运行时环境 (RTE)
  • CMake 跨平台构建系统详解
  • C++(26): 标准库 <iterator>
  • 基于python的机器学习(八)—— 评估算法(一)
  • 策略的组合与叠加多策略联合交易
  • 前端面经-nginx/docker
  • RTMP协议解析【三】
  • Linux服务器SOS Report完全指南:收集方法、作用解析与最佳实践
  • WPF···
  • 哥德巴赫猜想
  • 本特利内华达125768-01 RIM i/o模块规范
  • 8.2 线性变换的矩阵
  • QT的自定义控件
  • UI自动化测试框架:PO模式+数据驱动
  • 回表是数据库概念,还是mysql的概念?
  • 业务逻辑篇水平越权垂直越权未授权访问检测插件SRC 项目
  • 世界第一爆冷出局,双打均剩独苗,新周期国乒考验从双打开始
  • 云南陆良县发生一起装载机致人伤亡事件,造成6死4伤
  • 媒体谈平台帮商家“拉黑”客户:平台治理需兼顾商家与消费者权益
  • 凤阳文旅局长回应鼓楼瓦片脱落:楼宇是否属于文物?施工经费用在何处?
  • 大巴车高速上撞山致2死2伤,广东肇庆警方通报
  • 一日双赛“莎头组合”赢得强势,但国乒已开始品尝输球滋味