1. 准备前端文件
确保你的前端项目已经构建完成(如使用 npm run build
、yarn build
或 vite build
),生成 dist
或 build
目录。
例如:
npm run build # Vue/React 项目通常会生成 dist/ 或 build/
2. 创建 Dockerfile
在项目根目录下创建 Dockerfile
(无后缀),内容如下:
# 使用官方 Nginx 镜像作为基础 FROM nginx:alpine # 删除默认的 Nginx 配置 RUN rm -rf /etc/nginx/conf.d/* # 将构建好的前端文件复制到 Nginx 的默认静态文件目录 COPY dist/ /usr/share/nginx/html # 可选项:使用自定义 Nginx 配置(如需要) # COPY nginx.conf /etc/nginx/conf.d/default.conf # 暴露 80 端口(Nginx 默认端口) EXPOSE 80 # 启动 Nginx CMD ["nginx", "-g", "daemon off;"]
说明:
nginx:alpine
是一个轻量级的 Nginx 镜像。如果你的前端文件不在
dist/
目录,请修改COPY
路径(如COPY build/ /usr/share/nginx/html
)。如果需要自定义 Nginx 配置(如处理 SPA 路由),取消注释相关行并创建
nginx.conf
文件。
3. (可选)自定义 Nginx 配置
如果你的前端是单页应用(SPA,如 Vue/React),可能需要配置 Nginx 以支持路由跳转。创建 nginx.conf
文件:
server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html; try_files $uri $uri/ /index.html; # 支持前端路由 } # 可选项:配置 gzip 压缩 gzip on; gzip_types text/css application/javascript;}
然后在 Dockerfile
中取消注释 COPY nginx.conf /etc/nginx/conf.d/default.conf
。
4. 构建 Docker 镜像
在项目根目录(Dockerfile
所在目录)运行:
docker build -t my-frontend-app .
-t my-frontend-app
:给镜像命名为my-frontend-app
。.
:表示使用当前目录的Dockerfile
。
5. 运行容器
启动一个基于该镜像的容器:
docker run -d -p 8080:80 --name frontend-container my-frontend-app
-d
:后台运行。-p 8080:80
:将宿主机的 8080 端口映射到容器的 80 端口。--name frontend-container
:容器名称。
访问 http://localhost:8080
即可看到前端页面。
6. (可选)推送到 Docker Hub
如果需分享镜像:
docker tag my-frontend-app yourusername/my-frontend-app:latestdocker push yourusername/my-frontend-app:latest
常见问题
路由 404:确保 Nginx 配置了
try_files
(如上文nginx.conf
)。静态资源路径错误:前端项目需使用相对路径(如 Vue 设置
publicPath: './'
)。缓存问题:在
nginx.conf
中配置缓存策略或添加构建哈希(如[name].[hash].js
)。
通过以上步骤,你可以轻松将前端项目打包为 Nginx 镜像并部署到任何支持 Docker 的环境(如服务器、Kubernetes 等)。