前后端通过docker部署笔记

  1. 项目背景:这是一个SpringBoot+vue3的项目,通过maven打包后,需要在Linux服务器上部署,本篇博客主要记录docker-compose.yaml文件的含义:
    在这里插入图片描述

docker-compose.yml 文件中定义了一个 algorithm_platform_frontend 容器,该容器基于 nginx:latest 镜像,并通过数据卷 (volumes) 绑定了 前端静态文件Nginx 配置文件。下面详细解析各个参数的作用,以及 :z 选项的含义。


1. docker-compose.yml 解析

algorithm_platform_frontend:
  image: nginx:latest
  container_name: algorithm_platform_frontend
  hostname: algorithm_platform_frontend
  restart: unless-stopped
  volumes:
    - ./frontend/html:/usr/share/nginx/html:z
    - ./frontend/nginx.conf:/etc/nginx/nginx.conf:z
  ports:
    - "8000:80"
  networks:
    - algorithm_platform_network

参数解析

参数作用
image: nginx:latest使用官方 nginx 最新版镜像
container_name: algorithm_platform_frontend指定容器名称,方便管理
hostname: algorithm_platform_frontend设置容器的主机名
restart: unless-stopped容器异常退出时自动重启,但如果手动停止,则不会重启
volumes挂载数据卷(绑定前端文件和 Nginx 配置文件)
ports映射端口(宿主机 8000 -> 容器 80,外部访问 http://localhost:8000
networks指定容器加入 algorithm_platform_network 网络

2. volumes 详解

volumes:
  - ./frontend/html:/usr/share/nginx/html:z
  - ./frontend/nginx.conf:/etc/nginx/nginx.conf:z

挂载的路径

  1. ./frontend/html:/usr/share/nginx/html:z

    • 作用:将宿主机 ./frontend/html 目录(即前端 HTML 代码)挂载到 Nginx 的 /usr/share/nginx/html,使 Nginx 直接读取宿主机的静态资源。
    • 效果:修改 ./frontend/html 里的文件后,Nginx 自动加载更新,无需重新构建镜像。
  2. ./frontend/nginx.conf:/etc/nginx/nginx.conf:z

    • 作用:将 nginx.conf 配置文件挂载到容器的 /etc/nginx/nginx.conf,自定义 Nginx 配置。

3. :z 选项的作用

volumes 挂载路径的末尾,:z 选项是 SELinux 相关的设置,适用于启用了 SELinux(如 CentOS、RHEL)的环境。

:z 的作用

  • 改变 SELinux 上的标签,让容器能访问宿主机文件。
  • SELinux 默认会阻止 Docker 访问 docker 目录的文件:z 选项会自动添加 共享访问权限

是否需要 :z

  • 如果使用 CentOS / RHEL,而且 SELinux 开启,那么需要 :z 选项。
  • 如果是 Ubuntu / Debian / macOS / Windows,则不需要 :z,可以去掉。

📌 示例:去掉 :z

volumes:
  - ./frontend/html:/usr/share/nginx/html
  - ./frontend/nginx.conf:/etc/nginx/nginx.conf

如果你的环境 没有 SELinux,可以去掉 :z,避免不必要的权限修改。


4. 启动容器

📌 启动 docker-compose

docker-compose up -d
  • -d:后台运行容器
  • 访问 http://localhost:8000,应该能看到你的前端页面

📌 查看运行状态

docker ps

📌 查看日志

docker logs -f algorithm_platform_frontend

📌 更新配置后重启
如果修改了 nginx.confhtml 文件:

docker restart algorithm_platform_frontend

5. 总结

  • 这个 docker-compose.yml 文件创建了一个 nginx 容器,负责运行前端静态页面。
  • 挂载数据卷
    • html 目录:提供前端代码
    • nginx.conf:自定义 Nginx 配置
  • :z 选项:用于 SELinux 权限管理,非 SELinux 环境可以去掉。
  • 端口映射 8000:80,让外部可以通过 http://localhost:8000 访问前端。

🚀 建议

  • 确保 ./frontend/html 目录存在,否则 Nginx 可能无法启动。
  • 如果 nginx.conf 有错误,可以进入容器调试:
    docker exec -it algorithm_platform_frontend /bin/sh
    cat /etc/nginx/nginx.conf
    nginx -t  # 测试 Nginx 配置是否正确
    

如果你有更具体的问题,欢迎找博主讨论!😊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder小谢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值