1. 项目概述
作为一名长期奋战在一线的全栈开发者,我深知前端项目部署环节的重要性。Vue.js作为当前最流行的前端框架之一,其部署方式直接影响着用户体验和系统稳定性。而Nginx作为高性能的Web服务器,能够完美胜任Vue项目的部署需求。
在实际工作中,我发现很多开发者虽然能够完成基础部署,但往往忽略了性能调优、安全配置等关键细节。本文将基于我多年部署经验,从项目打包到生产环境配置,详细剖析每个环节的技术要点和最佳实践。
2. 项目打包与优化
2.1 环境准备与依赖安装
在开始打包之前,确保你的开发环境满足以下要求:
- Node.js LTS版本(推荐16.x或18.x)
- npm 8.x及以上版本
- Vue CLI(如使用)4.5.x及以上版本
提示:建议使用nvm管理Node.js版本,可以轻松切换不同项目所需的Node版本
安装依赖时,有几个关键点需要注意:
- 优先使用
npm ci替代npm install,它能严格根据package-lock.json安装依赖,确保环境一致性 - 对于国内用户,建议配置淘宝镜像加速:
bash复制npm config set registry https://registry.npmmirror.com
- 检查依赖安全性:
bash复制npm audit
2.2 编译配置优化
在vue.config.js中,我们可以进行多项优化配置:
javascript复制module.exports = {
productionSourceMap: false, // 关闭sourcemap减小体积
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
},
chainWebpack: config => {
config.plugin('preload').tap(() => [{
rel: 'preload',
as: 'script'
}])
}
}
这段配置实现了:
- 关闭sourcemap生成,减少打包体积约30%
- 优化代码分割策略,将node_modules单独打包
- 启用preload预加载关键资源
2.3 高级构建技巧
- 多环境配置:
javascript复制// .env.production
VUE_APP_API_BASE=https://api.yourdomain.com
VUE_APP_CDN_URL=https://cdn.yourdomain.com
- 使用--modern模式生成现代浏览器包:
bash复制npm run build -- --modern
- 启用gzip压缩(需配合Nginx配置):
javascript复制// vue.config.js
const CompressionPlugin = require('compression-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new CompressionPlugin({
algorithm: 'gzip',
test: /\.(js|css)$/,
threshold: 10240,
minRatio: 0.8
})
]
}
}
3. Nginx安装与配置
3.1 系统级优化配置
在安装Nginx前,建议先进行系统级优化:
bash复制# 调整文件描述符限制
echo "fs.file-max = 65535" | sudo tee -a /etc/sysctl.conf
echo "nginx soft nofile 65535" | sudo tee -a /etc/security/limits.conf
echo "nginx hard nofile 65535" | sudo tee -a /etc/security/limits.conf
# 优化内核参数
echo "net.core.somaxconn = 65535" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog = 65535" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
3.2 编译安装最新稳定版
虽然包管理器安装方便,但编译安装可以获得更好性能和最新特性:
bash复制# 安装依赖
sudo apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# 下载并解压
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
# 编译配置
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-threads \
--with-file-aio
# 编译安装
make -j$(nproc)
sudo make install
3.3 系统服务配置
创建systemd服务文件:
bash复制sudo tee /etc/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 启动服务
sudo systemctl enable nginx
sudo systemctl start nginx
4. 高级Nginx配置
4.1 性能优化配置
在nginx.conf的http块中添加以下配置:
nginx复制http {
# 基础性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
# 开启gzip
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 静态资源缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 日志优化
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main buffer=32k flush=1m;
error_log /var/log/nginx/error.log warn;
}
4.2 Vue项目专属配置
完整的Vue项目server配置示例:
nginx复制server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
# 强制HTTPS(配置SSL后启用)
# if ($scheme != "https") {
# return 301 https://$host$request_uri;
# }
root /var/www/vue-project/dist;
index index.html;
# 开启brotli压缩(需Nginx支持)
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 前端路由支持
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache";
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# API代理配置示例
location /api/ {
proxy_pass http://backend-server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 安全头设置
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.yourdomain.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https://*.yourdomain.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.yourdomain.com; frame-ancestors 'self';";
# 错误页面
error_page 404 /404.html;
location = /404.html {
internal;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
4.3 负载均衡配置
对于高流量场景,可以配置负载均衡:
nginx复制upstream backend {
least_conn;
server 10.0.0.1:3000 weight=5;
server 10.0.0.2:3000;
server 10.0.0.3:3000 backup;
keepalive 32;
}
server {
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
5. 安全加固与监控
5.1 全面的SSL配置
使用Certbot获取证书后,建议进行以下加固:
nginx复制ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 1.1.1.1 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
5.2 安全防护配置
- 防止敏感文件泄露:
nginx复制location ~ /\.(?!well-known) {
deny all;
access_log off;
log_not_found off;
}
location ~* (\.env|\.git|\.svn|\.ht) {
deny all;
}
- 限制HTTP方法:
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
- 防DDoS基础配置:
nginx复制limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20 nodelay;
}
}
5.3 监控与日志分析
- 配置Nginx状态页:
nginx复制location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
- 日志分析建议:
- 使用GoAccess进行实时日志分析
- 配置ELK堆栈进行长期日志存储和分析
- 设置日志轮转:
bash复制sudo tee /etc/logrotate.d/nginx <<EOF
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
EOF
6. 高级部署策略
6.1 蓝绿部署方案
为实现零停机部署,可以采用蓝绿部署策略:
- 准备两个相同的部署环境(蓝环境和绿环境)
- 初始时所有流量指向蓝环境
- 更新时先部署到绿环境并充分测试
- 切换DNS或负载均衡配置将流量导向绿环境
- 蓝环境作为下一次更新的目标
Nginx配置示例:
nginx复制upstream blue {
server 10.0.0.1:80;
}
upstream green {
server 10.0.0.2:80;
}
split_clients "${remote_addr}${http_user_agent}" $variant {
50% blue;
50% green;
}
server {
location / {
proxy_pass http://$variant;
}
}
6.2 容器化部署
使用Docker部署Nginx和Vue项目:
- Dockerfile示例:
dockerfile复制FROM nginx:1.25-alpine
COPY dist/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY security-headers.conf /etc/nginx/conf.d/security-headers.conf
RUN apk add --no-cache brotli && \
rm -rf /var/cache/apk/*
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]
- docker-compose.yml示例:
yaml复制version: '3.8'
services:
web:
build: .
ports:
- "80:80"
- "443:443"
volumes:
- ./certs:/etc/ssl/certs
restart: unless-stopped
networks:
- frontend
networks:
frontend:
driver: bridge
6.3 CDN集成配置
当使用CDN时,需要调整Nginx配置:
nginx复制# 识别真实客户端IP
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
# ...添加所有CDN IP段
real_ip_header X-Forwarded-For;
# 缓存控制
map $sent_http_content_type $expires {
default off;
text/html 1h;
text/css max;
application/javascript max;
~image/ max;
}
server {
expires $expires;
# 仅允许CDN IP访问源站
allow 192.168.0.0/16;
allow 172.16.0.0/12;
allow 10.0.0.0/8;
allow 103.21.244.0/22;
# ...添加其他信任IP
deny all;
}
7. 性能调优实战
7.1 内核参数调优
bash复制# 编辑/etc/sysctl.conf
echo "net.core.netdev_max_backlog = 65536" | sudo tee -a /etc/sysctl.conf
echo "net.core.somaxconn = 65535" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog = 65535" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_syncookies = 1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_tw_reuse = 1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.ip_local_port_range = 1024 65535" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
7.2 Nginx worker配置
根据CPU核心数优化worker配置:
nginx复制worker_processes auto; # 自动匹配CPU核心数
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
7.3 静态资源优化策略
- 使用WebP格式图片:
nginx复制location ~* \.(jpg|jpeg|png)$ {
add_header Vary Accept;
set $webp "";
if ($http_accept ~* "webp") {
set $webp ".webp";
}
try_files $uri$webp $uri =404;
}
- 智能内容协商:
nginx复制map $http_accept $suffix {
default "";
"~*webp" ".webp";
"~*avif" ".avif";
}
server {
location ~* ^(/img/.+)\.(png|jpg)$ {
try_files $1$suffix $uri =404;
}
}
8. 故障排查与维护
8.1 常见问题排查指南
- 502 Bad Gateway:
- 检查后端服务是否运行
- 查看Nginx错误日志:
tail -f /var/log/nginx/error.log - 检查防火墙设置
- 403 Forbidden:
- 检查文件权限:
ls -la /path/to/dist - 确认SELinux状态:
getenforce - 检查Nginx配置中的root路径
- 前端路由刷新404:
- 确保有正确的try_files配置
- 检查Vue router的base配置
- 验证Nginx location匹配规则
8.2 性能问题诊断工具
- 实时监控:
bash复制# 查看Nginx连接状态
watch -n 1 "curl -s http://localhost/nginx_status"
# 监控系统资源
htop
- 慢请求分析:
nginx复制# 在http块中添加
log_format slow '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
# 在server块中添加
access_log /var/log/nginx/slow.log slow if=$slow;
set $slow 0;
if ($request_time > 1) { set $slow 1; }
8.3 定期维护任务
- 证书续期检查:
bash复制sudo certbot renew --dry-run
- 配置备份:
bash复制# 每日备份Nginx配置
sudo tar -czf /backup/nginx-config-$(date +%Y%m%d).tar.gz /etc/nginx
- 日志清理:
bash复制# 保留最近7天日志
find /var/log/nginx -name "*.log" -mtime +7 -delete
在实际部署过程中,我发现很多问题都源于配置细节的疏忽。比如有一次线上事故就是因为忘记更新Nginx的root路径指向新版本,导致用户访问到的还是旧版页面。从那以后,我养成了部署后必做三项检查的习惯:配置文件语法检查、实际访问测试和日志监控。