1. 前端Dockerfile配置

dockerfile

# 使用Nginx作为基础镜像
FROM registry.cn-hangzhou.aliyuncs.com/xx_blog/nginx:1.27.2

# 维护者信息
MAINTAINER maintainer="xx@qq.com"

# 复制前端构建文件到Nginx默认目录
COPY dist/ /usr/share/nginx/html

# 暴露80端口
EXPOSE 80

2. 项目文件结构准备

bash

# 确认项目目录和文件
[root@xx-blog xx-spring-boot-web]# pwd
/root/xx-spring-boot-web

[root@xx-blog xx-spring-boot-web]# ls
dist  Dockerfile

# 确保dist目录包含前端打包文件
[root@xx-blog xx-spring-boot-web]# ls dist/
index.html  static/  assets/

3. 构建Docker镜像

bash

# 构建镜像(注意最后的点表示当前目录)
docker build -t xx-spring-boot-web:v1 .

# 构建过程输出示例
Sending build context to Docker daemon  15.87MB
Step 1/4 : FROM registry.cn-hangzhou.aliyuncs.com/xx_blog/nginx:1.27.2
 ---> a1b2c3d4e5f6
Step 2/4 : MAINTAINER maintainer="xx@qq.com"
 ---> Running in 1234567890ab
 ---> 234567890abc
Step 3/4 : COPY dist/ /usr/share/nginx/html
 ---> 34567890abcd
Step 4/4 : EXPOSE 80
 ---> Running in 4567890abcde
 ---> 2155d2ca31fa
Successfully built 2155d2ca31fa
Successfully tagged xx-spring-boot-web:v1

4. 验证镜像构建结果

bash

# 查看所有镜像
[root@xx-blog xx-spring-boot-web]# docker images
REPOSITORY           TAG       IMAGE ID       CREATED          SIZE
xx-spring-boot-web   v1        2155d2ca31fa   4 seconds ago    192MB
xx-springboot        v1        82132e652235   44 minutes ago   546MB

5. 运行前端容器

bash

# 运行容器
docker run -d --name=xx-springboot-web -p 80:80 xx-spring-boot-web:v1

# 参数说明:
# -d : 后台运行
# --name : 容器名称
# -p 80:80 : 端口映射(主机端口:容器端口)

6. 容器运行状态检查

bash

# 查看运行中的容器
docker ps

# 查看容器日志
docker logs xx-springboot-web

# 检查容器状态
docker inspect xx-springboot-web

7. 访问验证

bash

# 测试访问
curl http://localhost

# 或者在浏览器中访问
http://服务器IP地址

8. 常用管理命令

bash

# 停止容器
docker stop xx-springboot-web

# 启动容器
docker start xx-springboot-web

# 重启容器
docker restart xx-springboot-web

# 删除容器
docker rm xx-springboot-web

# 删除镜像
docker rmi xx-spring-boot-web:v1

9. 优化建议

使用多阶段构建(可选)

dockerfile

# 构建阶段
FROM node:16 as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# 生产阶段
FROM registry.cn-hangzhou.aliyuncs.com/xx_blog/nginx:1.27.2
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

使用更小的基础镜像

dockerfile

FROM nginx:alpine
COPY dist/ /usr/share/nginx/html
EXPOSE 80

10. 故障排查

如果遇到访问问题,可以:

  1. 检查容器是否正常运行:docker ps

  2. 查看容器日志:docker logs xx-springboot-web

  3. 检查端口是否被占用:netstat -tulpn | grep 80

  4. 进入容器检查文件:docker exec -it xx-springboot-web bash

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐