一、部署前的核心准备
1.1 服务器环境选择
- 云服务器推荐:腾讯云轻量应用服务器(2核4G配置)或阿里云ECS(学生优惠机型),建议选择CentOS 8/Ubuntu 20.04 LTS系统
- 本地开发环境检查:确认Node.js版本≥14.15.0,npm/yarn版本≥6.14.0,Vue CLI版本≥4.5.0
- 网络工具准备:安装Xshell/FinalShell(Windows)或iTerm2(Mac)作为SSH客户端,FileZilla用于文件传输
1.2 服务器基础配置
# 更新系统软件包(以Ubuntu为例)sudo apt update && sudo apt upgrade -y# 安装基础开发工具sudo apt install -y git curl wget unzip build-essential# 配置防火墙(仅开放必要端口)sudo ufw allow 22/tcp # SSH端口sudo ufw allow 80/tcp # HTTP服务sudo ufw allow 443/tcp # HTTPS服务sudo ufw enable
二、构建优化与生产环境准备
2.1 Vue项目构建配置
- 环境变量配置:在项目根目录创建
.env.production文件VUE_APP_API_BASE_URL=https://api.yourdomain.comVUE_APP_ENV=production
- 路由模式选择:建议使用history模式时配置Nginx重写规则
// vue.config.js 配置示例module.exports = {publicPath: process.env.NODE_ENV === 'production' ? '/dist/' : '/',productionSourceMap: false, // 生产环境关闭source mapconfigureWebpack: {performance: {hints: false,maxEntrypointSize: 512000,maxAssetSize: 512000}}}
2.2 构建生产包
# 安装依赖并构建npm install --productionnpm run build# 构建结果检查ls -lh dist/ # 应包含js/css/index.html等文件du -sh dist/ # 推荐打包后体积≤5MB
三、服务器部署实施
3.1 Nginx配置详解
# /etc/nginx/conf.d/vue_app.conf 示例配置server {listen 80;server_name yourdomain.com;root /var/www/vue_app/dist;index index.html;location / {try_files $uri $uri/ /index.html;# 静态资源缓存配置location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {expires 1y;add_header Cache-Control "public, no-transform";}}# API代理配置(可选)location /api/ {proxy_pass http://backend_server;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
3.2 部署流程标准化
# 1. 创建部署目录sudo mkdir -p /var/www/vue_appsudo chown -R $USER:$USER /var/www/vue_app# 2. 上传构建文件# 使用FileZilla或scp命令:scp -r dist/* username@server_ip:/var/www/vue_app/# 3. 重启Nginx服务sudo systemctl restart nginxsudo nginx -t # 测试配置语法
四、进阶优化与安全加固
4.1 HTTPS配置(Let’s Encrypt)
# 安装Certbotsudo apt install -y certbot python3-certbot-nginx# 获取证书sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com# 自动续期测试sudo certbot renew --dry-run
4.2 安全增强措施
- 目录权限设置:
sudo chown -R www-data:www-data /var/www/vue_appsudo find /var/www/vue_app -type d -exec chmod 750 {} \;sudo find /var/www/vue_app -type f -exec chmod 640 {} \;
-
禁用危险模块:在Nginx配置中添加
server {...# 禁用目录列表autoindex off;# 防止点击劫持add_header X-Frame-Options "SAMEORIGIN";# 禁用XSS保护add_header X-XSS-Protection "1; mode=block";}
五、常见问题解决方案
5.1 路由404问题
- 现象:刷新页面出现404错误
- 原因:未正确配置Nginx的try_files规则
- 解决:确保location / 块包含
try_files $uri $uri/ /index.html;
5.2 静态资源加载失败
- 检查项:
- 确认publicPath配置与部署路径匹配
- 检查Nginx配置中的root指令路径
- 使用浏览器开发者工具查看网络请求状态
5.3 跨域问题处理
- 前端配置:在vue.config.js中设置
devServer: {proxy: {'/api': {target: 'http://backend_domain',changeOrigin: true,pathRewrite: { '^/api': '' }}}}
- 后端配置:确保CORS头设置正确
location /api/ {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';}
六、自动化部署方案
6.1 Git Hook自动部署
# 服务器端配置mkdir -p /var/repo/vue_app.gitcd /var/repo/vue_app.gitgit init --bare# 创建post-receive钩子cat > hooks/post-receive <<EOF#!/bin/bashTARGET="/var/www/vue_app"GIT_DIR="/var/repo/vue_app.git"BRANCH="master"while read oldrev newrev refdobranch=\$(git rev-parse --symbolic --abbrev-ref \$ref)if [ "master" = "\$branch" ]; thenecho "Ref \$ref received. Deploying ${branch} branch to production..."git --work-tree=\$TARGET --git-dir=\$GIT_DIR checkout -f \$branchcd \$TARGETnpm install --productionnpm run buildsudo systemctl restart nginxelseecho "Ref \$ref received. Doing nothing: only the master branch may be deployed on this server."fidoneEOFchmod +x hooks/post-receive
6.2 CI/CD集成方案
- GitHub Actions示例:
```yaml
name: Vue CI/CD
on:
push:
branches: [ master ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2- name: Install Node.jsuses: actions/setup-node@v2with:node-version: '14'- run: npm ci- run: npm run build- name: Deploy to Serveruses: appleboy/ssh-action@masterwith:host: ${{ secrets.SERVER_IP }}username: ${{ secrets.SERVER_USER }}key: ${{ secrets.SSH_PRIVATE_KEY }}script: |rm -rf /var/www/vue_app/*cp -r /tmp/dist/* /var/www/vue_app/sudo systemctl restart nginx
# 七、监控与维护## 7.1 性能监控- **Nginx状态模块**:```nginx# 在nginx.conf中添加load_module modules/ngx_http_stub_status_module.so;server {...location /nginx_status {stub_status on;allow 127.0.0.1;deny all;}}
- 访问日志分析:
```bash
实时查看访问日志
tail -f /var/log/nginx/access.log
统计访问量
awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | sort -nr
## 7.2 定期维护任务```bash# 每周清理日志echo "0 3 * * 1 root /usr/bin/find /var/log/nginx/ -name '*.log' -mtime +7 -exec rm {} \;" | sudo tee /etc/cron.weekly/nginx_logrotate# 每月更新系统echo "0 0 1 * * root apt update && apt upgrade -y" | sudo tee /etc/cron.monthly/system_update
通过以上系统化的部署方案,服务器小白可以完成从环境搭建到自动化运维的全流程操作。建议首次部署后进行全面的功能测试,包括路由跳转、API调用、静态资源加载等关键环节。随着项目规模扩大,可逐步引入Docker容器化部署和Kubernetes集群管理方案,实现更高效的资源利用和故障恢复能力。