前后端通过docker部署笔记
- 项目背景:这是一个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:latestcontainer_name: algorithm_platform_frontendhostname: algorithm_platform_frontendrestart: unless-stoppedvolumes:- ./frontend/html:/usr/share/nginx/html:z- ./frontend/nginx.conf:/etc/nginx/nginx.conf:zports:- "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
挂载的路径
-
./frontend/html:/usr/share/nginx/html:z
- 作用:将宿主机
./frontend/html
目录(即前端 HTML 代码)挂载到 Nginx 的/usr/share/nginx/html
,使 Nginx 直接读取宿主机的静态资源。 - 效果:修改
./frontend/html
里的文件后,Nginx 自动加载更新,无需重新构建镜像。
- 作用:将宿主机
-
./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.conf
或 html
文件:
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 配置是否正确
如果你有更具体的问题,欢迎找博主讨论!😊