目录
[创建 compose.yaml](#创建 compose.yaml)
前提条件
- 熟悉Docker、Spring Boot 、Vue基本知识
- 熟悉yaml文件基本知识,可参考:YAML 入门教程
- 掌握Docker部署Spring Boot + Vue项目方法,可参考:Docker部署Spring Boot + Vue项目
概述
本文在普通的Docker部署Spring Boot + Vue项目 的基础上进行。部署若依前后端分离版项目为例,重点在于如何使用Docker Compose的方式加快项目部署过程。
此前使用Docker部署一个Spring Boot + Vue项目,包含了4个容器:
-
MySQL
-
Redis
-
Java后端
-
Nginx前端
而稍微复杂的项目,还会有各种各样的其它中间件,需要部署的容器远不止4个。如果还像之前那样手动的逐一部署,就太麻烦了。
而Docker Compose就可以帮助我们实现 多个相互关联的Docker容器的快速部署。
Compose简介
Docker Compose 是一个用于定义和运行多容器应用程序的工具,是实现精简且高效的开发与部署体验的关键所在。
它简化了对整个应用程序栈的控制,能够通过一个易于理解的 YAML 配置文件轻松管理服务、网络和存储卷。然后,只需一条命令,就能依据配置文件创建并启动所有服务。
Docker Compose 可在所有环境中工作,包括生产、预发布、开发、测试环境以及持续集成(CI)工作流程。它还具备用于管理应用程序整个生命周期的命令,比如:
-
启动、停止和重建服务。
-
查看正在运行服务的状态。
-
流式输出正在运行服务的日志内容。
-
在某个服务上运行一次性命令。
通过使用 Docker Compose,使用一个名为 Compose 文件的 YAML 配置文件来配置应用程序的各项服务,然后使用 Compose 命令行界面(CLI)依据该配置文件创建并启动所有服务。
Compose 文件(即 compose.yaml 文件)在定义多容器应用程序方面遵循了 Compose 规范所提供的规则。
Compose文件
Compose 文件的默认路径是位于工作目录下的 compose.yaml
(首选)或 compose.yml
。为了与早期版本兼容,Compose 也支持 docker-compose.yaml
和 docker-compose.yml
。如果这两种文件都存在,Compose 会优先使用规范的 compose.yaml 文件。
你可以使用片段和扩展来保持 Compose 文件的高效性和易于维护性。
多个 Compose 文件可以合并在一起以定义应用程序模型。YAML 文件的组合是通过根据你设置的 Compose 文件顺序来追加或覆盖 YAML 元素来实现的。简单属性和映射会被最高顺序的 Compose 文件覆盖,列表则通过追加来合并。当要合并的互补文件存放在其他文件夹时,相对路径会基于第一个 Compose 文件的父文件夹来解析。由于一些 Compose 文件元素既可以表示为单个字符串也可以表示为复杂对象,所以合并操作适用于展开形式。
如果想复用其他 Compose 文件,或者将应用程序模型的部分内容提取到单独的 Compose 文件中,也可以使用 "include"。如果你的 Compose 应用程序依赖于由不同团队管理的另一个应用程序,或者需要与他人共享,这将非常有用。
Compose环境
安装docker时已经附带安装了docker-compose-plugin插件,所以无需另外安装docker compose
使用如下命令查询compose版本,看到版本号,说明docker compose正常可用
[root@localhost ~]# docker compose version
Docker Compose version v2.29.7
Compose命令
通过 "docker compose" 命令及其子命令与 Docker Compose 应用程序进行交互。可以管理在 compose.yaml 文件中定义的多容器应用程序的生命周期。这些命令能够轻松地启动、停止和配置应用程序。
帮助命令
docker compose帮助命令
[root@localhost ~]# docker compose --help
Usage: docker compose [OPTIONS] COMMAND
Define and run multi-container applications with Docker
Options:
--all-resources Include all resources, even those not used by services
--ansi string Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")
--compatibility Run compose in backward compatibility mode
--dry-run Execute command in dry run mode
--env-file stringArray Specify an alternate environment file
-f, --file stringArray Compose configuration files
--parallel int Control max parallelism, -1 for unlimited (default -1)
--profile stringArray Specify a profile to enable
--progress string Set type of progress output (auto, tty, plain, json, quiet) (default "auto")
--project-directory string Specify an alternate working directory
(default: the path of the, first specified, Compose file)
-p, --project-name string Project name
Commands:
attach Attach local standard input, output, and error streams to a service's running container
build Build or rebuild services
config Parse, resolve and render compose file in canonical format
cp Copy files/folders between a service container and the local filesystem
create Creates containers for a service
down Stop and remove containers, networks
events Receive real time events from containers
exec Execute a command in a running container
images List images used by the created containers
kill Force stop service containers
logs View output from containers
ls List running compose projects
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart service containers
rm Removes stopped service containers
run Run a one-off command on a service
scale Scale services
start Start services
stats Display a live stream of container(s) resource usage statistics
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker Compose version information
wait Block until containers of all (or specified) services stop.
watch Watch build context for service and rebuild/refresh containers when files are updated
Run 'docker compose COMMAND --help' for more information on a command.
查看某个命令的帮助,例如,docker compose up命令帮助如下
[root@localhost ~]# docker compose up --help
Usage: docker compose up [OPTIONS] [SERVICE...]
Create and start containers
Options:
--abort-on-container-exit Stops all containers if any container was stopped. Incompatible with -d
--abort-on-container-failure Stops all containers if any container exited with failure. Incompatible with -d
--always-recreate-deps Recreate dependent containers. Incompatible with --no-recreate.
--attach stringArray Restrict attaching to the specified services. Incompatible with --attach-dependencies.
--attach-dependencies Automatically attach to log output of dependent services
--build Build images before starting containers
-d, --detach Detached mode: Run containers in the background
--dry-run Execute command in dry run mode
--exit-code-from string Return the exit code of the selected service container. Implies --abort-on-container-exit
--force-recreate Recreate containers even if their configuration and image haven't changed
--menu Enable interactive shortcuts when running attached. Incompatible with --detach. Can
also be enable/disable by setting COMPOSE_MENU environment var.
--no-attach stringArray Do not attach (stream logs) to the specified services
--no-build Don't build an image, even if it's policy
--no-color Produce monochrome output
--no-deps Don't start linked services
--no-log-prefix Don't print prefix in logs
--no-recreate If containers already exist, don't recreate them. Incompatible with --force-recreate.
--no-start Don't start the services after creating them
--pull string Pull image before running ("always"|"missing"|"never") (default "policy")
--quiet-pull Pull without printing progress information
--remove-orphans Remove containers for services not defined in the Compose file
-V, --renew-anon-volumes Recreate anonymous volumes instead of retrieving data from the previous containers
--scale scale Scale SERVICE to NUM instances. Overrides the scale setting in the Compose file if
present.
-t, --timeout int Use this timeout in seconds for container shutdown when attached or when containers
are already running
--timestamps Show timestamps
--wait Wait for services to be running|healthy. Implies detached mode.
--wait-timeout int Maximum duration to wait for the project to be running|healthy
-w, --watch Watch source code and rebuild/refresh containers when files are updated.
关键命令
启动在 compose.yaml 文件中定义的所有容器服务:
docker compose up
停止并移除正在运行的容器服务:
docker compose down
监控正在运行的容器的输出并调试问题,通过以下命令查看日志:
docker compose logs
列出所有容器服务及其当前状态:
docker compose ps
Compose部署项目
此前docker命令一个一个容器手动部署步骤如下:
1.创建网络
[root@localhost ~]# docker network create rynet
2.启动mysql容器
docker run -d -p 3306:3306
-v /app/myconf:/etc/mysql/conf.d
-v /app/mydata:/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=password
--network rynet
--name mysqldb
mysql:8.0.39-debian
3.运行sql文件,得到初始数据
4.运行redis容器
docker run -d -p 6379:6379
--name myredis
-v /app/redis/conf:/usr/local/etc/redis
-v /app/redis/data:/data
--network rynet
redis
5.构建后端镜像
5.1Dockerfile内容
FROM openjdk:8
LABEL author=liang
COPY ruoyi-admin.jar /ruoyi-admin.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/ruoyi-admin.jar"]
5.2构建镜像
[root@localhost ruoyi]# docker build -t ruoyiadmin:v1 .
6.运行后端容器
docker run -d -p 8080:8080
--name backend
--network rynet
-v /app/admindata/uploadPath:/ruoyi/uploadPath
ruoyiadmin:v1
7.运行前端容器
docker run -d -p 80:80
-v /root/dist:/usr/share/nginx/html
-v ryngconf:/etc/nginx
--name rynginx
--network rynet
nginx
下面把这些步骤统一写在一个 compose.yaml
文件中,然后使用一条命令启动这些容器,避免手动一步一步运行各个容器的麻烦,简化部署流程。compose.yaml
内容(还可进一步优化,本文后面会提供优化后的yaml内容)如下:
services:
mysql:
image: mysql
container_name: mysqldb
ports:
- "3306:3306"
environment:
TZ: Asia/Shanghai
MYSQL_ROOT_PASSWORD: password
volumes:
- "/app/compose/mysql/myconf:/etc/mysql/conf.d"
- "/app/compose/mysql/mydata:/var/lib/mysql"
- "/app/compose/mysql/myinit:/docker-entrypoint-initdb.d" # 初始化sql文件所在目录绑定挂载
networks:
- rynet
redis:
image: redis
container_name: myredis
volumes:
- "/app/compose/redis/conf:/usr/local/etc/redis"
- "/app/compose/redis/data:/data"
networks:
- rynet
javabackend:
build:
context: ./ruoyi
dockerfile: Dockerfile
container_name: backend
image: ruoyiadmin:v2 # 指定镜像名
ports:
- "8080:8080" # 暴露端口
volumes:
- /app/admindata/uploadPath:/ruoyi/uploadPath # 上传目录绑定挂载
networks:
- rynet
depends_on:
- mysql
- redis
nginx:
image: nginx
container_name: nginx
ports:
- "80:80"
volumes:
- "/root/nginx.conf:/etc/nginx/nginx.conf" # 绑定挂载配置文件,提前准备
- "/root/dist:/usr/share/nginx/html"
depends_on:
- javabackend
networks:
- rynet
networks:
rynet:
看到compose.yaml文件定义了4个容器。读者可自行对比compose文件定义的容器和docker run命令运行容器的对应关系。
初始化环境
删除容器
[root@localhost ~]# docker rm -f $(docker ps -qa)
fcb5469c0776
88c2f4a4496f
74eeb57c4038
08776c3691f7
3655375bda89
ce27bf664148
2f92612fd555
f16e0185235f
5d0a2242ac54
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
删除未使用的网络
[root@localhost ~]# docker network prune
删除相关镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ruoyiadmin v1 6de9305df65c 2 hours ago 610MB
ruoyifront v1 35c81e6d0f0b 25 hours ago 194MB
test/mychangenginx v1 16689c99df42 3 days ago 188MB
ubuntu latest b1e9cef3f297 5 weeks ago 78.1MB
nginx latest 39286ab8a5e1 6 weeks ago 188MB
redis latest 7e49ed81b42b 2 months ago 117MB
mysql latest c757d623b190 2 months ago 586MB
mysql 8.0.39-debian 3c716403fbe7 2 months ago 611MB
hello-world latest d2c94e258dcb 17 months ago 13.3kB
[root@localhost ~]# docker rmi 6de 35c 166
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest b1e9cef3f297 5 weeks ago 78.1MB
nginx latest 39286ab8a5e1 6 weeks ago 188MB
redis latest 7e49ed81b42b 2 months ago 117MB
mysql latest c757d623b190 2 months ago 586MB
mysql 8.0.39-debian 3c716403fbe7 2 months ago 611MB
hello-world latest d2c94e258dcb 17 months ago 13.3kB
查看代码文件
在完成Docker部署Spring Boot + Vue项目后,就会有前后端的代码文件,通过如下命令查看代码文件,确保如下这些文件存在。
查看代码文件
[root@localhost ~]# ls
ruoyi dist ...
查看前端文件
[root@localhost ~]# ls dist
favicon.ico html index.html index.html.gz robots.txt static
查看到后端文件
[root@localhost ~]# ls ruoyi
Dockerfile ruoyi-admin.jar
sql数据准备
将mysql数据初始化文件ry_20240629.sql
,上传到指定目录,例如:/app/compose/mysql/myinit/
[root@localhost ~]# mkdir -p /app/compose/mysql/myinit
[root@localhost ~]# ls /app/compose/mysql/myinit/
ry_20240629.sql
nginx配置文件准备
[root@localhost ~]# vi nginx.conf
nginx.conf内容如下:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /prod-api/{
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backend:8080/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
1.location / {里面的root 配置前端代码文件所在的目录
2.location /prod-api/{里面配置了前端请求带有/prod-api/开头的路径,将请求转发到对应的后端地址,这里配置的后端服务地址为http://backend:8080/,例如:localhost:80/prod-api/getAllUser请求转发到http://backend:8080/getAllUser
创建 compose.yaml
[root@localhost ~]# vi compose.yaml
优化后的compose.yaml文件内容如下:
services:
mysqldb:
image: mysql:8.0.39-debian
container_name: mysqldb
ports:
- "3306:3306"
environment:
TZ: Asia/Shanghai
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: ryvue
LANG: C.UTF-8
command:
--character-set-server=utf8mb4
--collation-server=utf8mb4_general_ci
volumes:
- "/app/compose/mysql/myconf:/etc/mysql/conf.d"
- "/app/compose/mysql/mydata:/var/lib/mysql"
- "/app/compose/mysql/myinit:/docker-entrypoint-initdb.d" # 绑定挂载,初始化sql文件所在目录
networks:
- rynet
myredis:
image: redis
container_name: myredis
volumes:
- "/app/compose/redis/conf:/usr/local/etc/redis"
- "/app/compose/redis/data:/data"
networks:
- rynet
backend:
build:
context: ./ruoyi
dockerfile: Dockerfile
container_name: backend
image: ruoyiadmin:v2 # 指定镜像名
ports:
- "8080:8080"
volumes:
- /app/admindata/uploadPath:/ruoyi/uploadPath # 绑定挂载,上传目录
networks:
- rynet
restart: always
depends_on:
mysqldb:
condition: service_started
myredis:
condition: service_started
nginx:
image: nginx
container_name: nginx
ports:
- "80:80"
volumes:
- "/root/nginx.conf:/etc/nginx/nginx.conf" # 绑定挂载,nginx配置文件,提前准备
- "/root/dist:/usr/share/nginx/html" # 绑定挂载,前端代码目录
depends_on:
- backend
networks:
- rynet
networks:
rynet:
一键启动compose多个容器
[root@localhost ~]# docker compose up -d
[+] Running 1/1
! backend Warning Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting fo... 139.6s
[+] Building 0.1s (8/8) FINISHED docker:default
=> [backend internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 169B 0.0s
=> [backend internal] load metadata for docker.io/library/openjdk:8 0.0s
=> [backend internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [backend internal] load build context 0.0s
=> => transferring context: 39B 0.0s
=> [backend 1/2] FROM docker.io/library/openjdk:8 0.0s
=> CACHED [backend 2/2] COPY ruoyi-admin.jar /ruoyi-admin.jar 0.0s
=> [backend] exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:83e99924b0730b778deafc3783a049a240783ee9658f2c096f151d55b12bb6bc 0.0s
=> => naming to docker.io/library/ruoyiadmin:v2 0.0s
=> [backend] resolving provenance for metadata file 0.0s
[+] Running 5/5
Network root_rynet Created 0.1s
Container myredis Started 0.6s
Container mysqldb Started 0.6s
Container backend Started 0.9s
Container nginx Started 1.2s
[root@localhost ~]#
浏览器访问虚拟机ip:80(可省略默认的80端口)
虚拟机ip
输入验证码后,进入用户管理,看到如下界面
查看Compose运行的容器
[root@localhost ~]# docker compose ps
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
backend ruoyiadmin:v2 "java -jar /ruoyi-ad..." backend 10 seconds ago Up 8 seconds 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp
myredis redis "docker-entrypoint.s..." myredis 10 seconds ago Up 9 seconds 6379/tcp
mysqldb mysql:8.0.39-debian "docker-entrypoint.s..." mysqldb 10 seconds ago Up 9 seconds 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp
nginx nginx "/docker-entrypoint...." nginx 9 seconds ago Up 8 seconds 0.0.0.0:80->80/tcp, :::80->80/tcp
查看容器日志
使用如下命令查看容器日志
[root@localhost ~]# docker compose logs
...
省略日志输出
...
看到输出了Compose中多个容器的日志。
关闭并删除Compose开启的容器
关闭并删除Compose开启的容器
[root@localhost ~]# docker compose down
[+] Running 5/5
Container nginx Removed 0.3s
Container backend Removed 0.4s
Container mysqldb Removed 0.6s
Container myredis Removed 0.2s
Network root_rynet Removed 0.1s
[root@localhost ~]#
再次查看容器
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
完成!enjoy it!