一、核心思想
- 不把前端文件打包进镜像,而是使用官方 Nginx 镜像
- 通过
-v(或--volume)参数,将主机上的dist/目录挂载到容器内的 Nginx 默认 Web 根目录(如/usr/share/nginx/html) - Nginx 配置可通过挂载自定义配置文件实现反向代理等逻辑
💡 优点:修改前端文件无需重建镜像,刷新即生效
⚠️ 缺点:依赖主机路径,可移植性差,权限问题较常见
二、部署步骤(完整流程)
第 1 步:构建前端项目,生成 dist/目录
npm run build
# 输出通常为 dist/ 或 build/
假设你的前端产物在:
/root/wanchuang_Platform/dist/
第 2 步:准备 Nginx 配置文件( default.conf)
创建 /root/wanchuang_Platform/default.conf:
server {
listen 8085;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# 代理后端 API
location /admin/ {
proxy_pass http://127.0.0.1:8080; # 若用 --network host
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;
}
# 支持前端路由(如 Vue Router history 模式)
location / {
try_files $uri /index.html;
}
}
第 3 步:启动容器并挂载文件和配置
podman run -d \
--name wanchuang_platform \
--network host \ # 共享主机网络,便于访问后端
-v /root/wanchuang_Platform/dist:/usr/share/nginx/html:ro,Z \ # 挂载前端文件
-v /root/wanchuang_Platform/default.conf:/etc/nginx/conf.d/default.conf:ro,Z \ # 挂载配置
nginx:alpine
🔑 参数说明:
-v 源路径:容器路径:ro,Z
-
ro:只读(安全)Z:自动设置 SELinux 标签(解决权限拒绝问题,阿里云 CentOS 必加)
--network host:让容器能通过127.0.0.1访问主机上的后端服务
第 4 步:访问应用
根据配置中的 listen 8085;,访问:
http://47.116.170.161:8085/user/login