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