项目部署及nginx上线

前言 - 重点总结

  • 接口请求路径
    • 使用nginx配置反向代理时统一使用相对路径(仅需nginx需改路径即可)
    • 仅在访问外部服务时使用全路径(支付接口,地图API)
  • 跨越解决方案
    • 相对路径:nginx反向代理
    • 全路径:CORS(浏览器比对请求的origin和服务器返回的相应头的Access-Control-Allow-Origin是否一致)
  • 配置环境中的publicPath和路由base必须保持一致(仅需要子路径时配置)
    • publicPath:静态资源的加载路径
    • 路由base:URL路径的路由匹配逻辑

一、node部署(本地)

1.1 技术点

  • express.static托管静态资源
  • connect-history-api-fallback:解决页面刷新找不到问题
    • 首次访问/路径,服务器返回 index.html
    • 刷新页面服务器在文件系统中找不到对应路径的文件
  • http-proxy-middleware:解决接口无法调用问题
    • 无代理服务器,无法访问后端
  • 代理相关
    • 开发环境
    export default defineConfig({
        server: {
            proxy: {
            '/api': {
                target: 'http://api.example.com',
                changeOrigin: true,
                rewrite: path => path.replace(/^\/api/, ''),
            }
            }
        }
    })
    // 解读
    // 1. 浏览器请求: /api/users -> http://localhost:5173/api/users
    // 2. 开发服务器代理转发: http://api.example.com/users
    // 3. API 服务器返回响应
    

1.2 完整代码

const express = require('express');
const history = require('connect-history-api-fallback');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// 解决页面刷新找不到
app.use(history({}));
// express.static托管静态资源
app.use(express.static(__dirname + '/public'));

// 代理服务器
app.use(
  '/api-prod',
  createProxyMiddleware({
    target: 'http://124.222.47.xx:9000',
    changeOrigin: true,
    pathRewrite: {
        '^/api-prod' : ''
    }
  }),
);

app.listen('8899', () => {
    console.log('服务器已启动')
})

二、nginx服务器部署(本地)

2.1 nginx介绍

  • 介绍:一款高性能的http服务器和反向代理服务器
  • 作用:
    • 1.反向代理
    • 2.负载均衡
    • 3.静态内容服务
    • 4.http/2支持
    • 5.SSL/TLS支持
    • 6.高速缓存

2.2 使用步骤

  • 下载nginx。官网地址
  • 点击nginx.exe启动服务器
  • 验证启动:localhost:80/localhost
  • 修改nginx.conf中的配置
  • 根路径部署
location / {
    root   E:\dist;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html; # 解决刷新404
}

location /api-prod/ {
    # 设置代理目标,注意/api-prod/和http://124.222.47.x x:9000/ 最后/不能少
    proxy_pass http://124.222.47.xx:9000/;
}

三、服务器部署:mac+node+mysql+vue3+nginx

相关概念解读

  • 命令
    sudo 以管理员权限执行
    chown 修改文件/目录所有者
    -R 递归操作(包含子目录和文件)
    $USER:$USER 设置所有者和所属组为当前登录用户($USER会自动获取当前登录用户名:ubuntu:ubunt)
    SCP = Secure Copy Protocol (安全复制协议),用于在本地计算机和远程服务器之间安全地传输文件
  • 缓存状态码
    • 200 OK(from disk cache)/ 200 OK (from memory cache):取缓存
    • 304 Not Modified
    • 200 OK
  • 服务器器上部署地址
    /var/www Vue3部署的地址
    /etc/nginx/sites-available nginx地址
    /home/ubuntu/project-api node后端地址
    /var/lib/mysql sql地址
  • 配置环境中的publicPath和路由base必须保持一致
    • 开发环境:publicPath和base基本无需配置
    • 生产环境:
      • 根目录下无需配置
      • 子目录下需要同时配置
         // vue.config.js / vite.config.js
         // vue2
         module.exports = {
             publicPath: '/sub-path/'  // 必须带结尾斜线
         }
         // vue3
         export default defineConfig({
             base: '/sub-path/' 
         })
        
         // router.js
         // vue2
         export default new VueRouter({
             mode: 'history',
             base: '/sub-path/',
         })
         // vue3(import.meta.env.BASE_URL取vite.config.js中的base)
         const router = createRouter({
             history: createWebHistory(import.meta.env.BASE_URL),
         })
        

3.1 服务器购买

系统:腾讯云 -> 基于操作系统镜像 -> Ubuntu

3.2 服务器连接(VS Code连接)

3.2 服务器端安装相关环境

# 1. 更新系统
sudo apt update && sudo apt upgrade -y
# 2. 安装Node.js
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# 3. 安装MySQL和Nginx
sudo apt install -y mysql-server nginx
# 4. 安装进程管理工具
sudo npm install -g pm2

3.3 mysql 连接

  • 1.设置root密码(安全访问控制)
sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456789';"
  • 2.创建应用数据库
sudo mysql -u root -p'123456789' -e "CREATE DATABASE auth_system;"
  • 3.导入表结构
# 电脑终端执行 - 复制本地文件到服务器(tmp文件重启后自动清空)
scp ~/Documents/test/user.sql ubuntu@124.222.47.xx:/tmp/
# 服务器端执行 - 执行导入
sudo mysql -u root -p'123456789' auth_system < /tmp/user.sql
# 服务器端执行 - 验证导入
sudo mysql -u root -p'123456789' -e "USE auth_system; SHOW TABLES;"

3.4 node部署及启动

  • node部署
# 服务器端执行 - 创建项目文件夹
sudo mkdir -p /home/ubuntu/project-api
sudo chown -R $USER:$USER /home/ubuntu/project-api # 解决权限问题
# 电脑终端执行 - 文件复制(也可通过拖拽的方式实现)
scp -r ~/Documents/test/project-api/* ubuntu@124.222.47.xx:/home/ubuntu/project-api  
  • 相关命令(需要在node文件夹层面运行)
    • pm2 start server.js –name “my-pc” –watch # –watch 监听文件改动自动重启
    • pm2 start npm –name “my-pc” – run start
    • pm2 stop my-pc # 停止指定应用
    • pm2 stop all # 停止所有应用
    • pm2 list # 所有运行中的进程
    • pm2 delete all # 删除所有应用
    • pm2 flush # 清除日志文件
    • pm2 logs app –lines 100 # 查看最近100行日志
    • pm2 monit # 实时监控

3.5 vue3项目部署

sudo rm -r var/www/mypc # 删除文件
# 服务器端执行 - 创建项目文件夹
sudo mkdir -p /var/www/mypc-main # 根项目
sudo mkdir -p /var/www/mypc-sub # 子项目
sudo chown -R $USER:$USER /var/www # 赋予当前用户权限

# 电脑终端执行 - 文件复制(加*不带文件夹复制)
scp -r ~/Documents/test/mypc-main/* ubuntu@124.222.47.xx:/var/www/mypc-main/
scp -r ~/Documents/test/mypc-sub/* ubuntu@124.222.47.xx:/var/www/mypc-sub/

3.6 配置nginx

  • 1.创建站点配置
#  nginx.conf为主配置文件,sites-available模式为:模块化(每个应用独立配置)
ls /etc/nginx/sites-enabled/ # 查看现有配置文件
sudo nano /etc/nginx/sites-available/mypc.conf # 创建或打开配置文件
Ctrl+O, Enter, Ctrl+X # 保存并退出
  • 2.相关配置
server {
    listen 80;
    server_name 124.222.47.xx;  # 你的域名或服务器IP
    root /var/www/mypc-main;
    index index.html;  
  
    # 根目录项目
    location / {
        try_files $uri $uri/ /index.html;
        # HTML文件不缓存
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
    
    # 子路径应用 - 使用alias确保路径隔离
    location ^~ /sub-path {
        # 关键:alias路径末尾不要加斜杠
        alias /var/www/mypc-sub;
        try_files $uri $uri/ /sub-path/index.html;
        # HTML文件不缓存
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # 代理后端 API 请求
    location /api {
        rewrite ^/api/(.*)$ /$1 break;  # 去掉 /api 前缀
        proxy_pass http://localhost:9000;  # Node.js 服务地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}
  • 相关命令
sudo ln -s /etc/nginx/sites-available/mypc.conf /etc/nginx/sites-enabled/ # 激活配置
sudo nginx -t # 测试配置语法 - 必须看到 "syntax is ok"
sudo systemctl reload nginx # 重载配置

3.7 故障排查

  • 查看实时日志
pm2 logs project-api --lines 100
  • 查看错误日志
sudo tail -f /var/log/nginx/error.log 
  • 实时监控
pm2 monit
×

喜欢就点赞,疼爱就打赏