安装和配置Nginx容器

  1. 文件目录

/home/nginx/conf.d 用于存放配置文件
/home/nginx/cert 用于存放https证书
/home/nginx/html 用于存放网页文件
/home/nginx/logs 用于存放日志

  1. 运行nginx容器
docker run -d \
--name nginx --restart always \
-p 80:80 -p 443:443 \
-e "TZ=Asia/Shanghai" \
-v /home/nginx/nginx.conf:/etc/nginx/nginx.conf \
-v /home/nginx/conf.d:/etc/nginx/conf.d \
-v /home/nginx/logs:/var/log/nginx \
-v /home/nginx/cert:/etc/nginx/cert \
-v /home/nginx/html:/usr/share/nginx/html \
nginx:alpine
  1. 配置nginx 这里使用Nginx反向代理访问后端服务,由于容器内部通信,因此需要使用容器的IP,也就是172.17.0.1。
  2. 在/home/nginx/conf.d创建一个{name}.conf的配置文件,文件内容如下
    server
     {
         listen 80;
         server_name 域名/外网IP;
         index index.html;
         root  /usr/share/nginx/html/{name}/dist;  #dist上传的路径
    
         # 避免访问出现 404 错误
         location / {
           try_files $uri $uri/ @router;
           index  index.html;
         }
    
         location @router {
           rewrite ^.*$ /index.html last;
         }
    
         # 接口
         location /api {
           proxy_pass http://172.17.0.1:8000;
           proxy_set_header X-Forwarded-Proto $scheme;
           proxy_set_header X-Forwarded-Port $server_port;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "upgrade";
         }
    
         # 授权接口
         location /auth {
           proxy_pass http://172.17.0.1:8000;
           proxy_set_header X-Forwarded-Proto $scheme;
           proxy_set_header X-Forwarded-Port $server_port;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "upgrade";
         }
    
         # WebSocket 服务
         location /webSocket {
           proxy_pass http://172.17.0.1:8000;
           proxy_set_header X-Forwarded-Proto $scheme;
           proxy_set_header X-Forwarded-Port $server_port;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "upgrade";
         }
    
         # 限制spring boot admin
         location ~ ^(/[^/]*)?/actuator(/.*)?$ {
             return 403;
         }
    
         # 头像
         location /avatar {
           proxy_pass http://172.17.0.1:8000;
         }
    
         # 文件
         location /file {
           proxy_pass http://172.17.0.1:8000;
         }
     }
     # 容器中 /usr/share/nginx/html/{name}/dist 对应宿主机的 /home/nginx/html/{name}/dist 目录,因此文件上传到宿主机的目录即可
    
  3. 将 .env.production 中的接口地址改为 ‘/’
  4. 修改 api.js 中的 baseUrl = process.env.VUE_APP_BASE_API === ‘/’ ? ’’ : process.env.VUE_APP_BASE_API