一、Docker Compose简介
当需要在多个容器之间协调和管理应用程序时,Docker Compose是一个非常有用的工具。它允许通过一个配置文件来定义、配置和启动多个 Docker 容器,使得整个应用程序的部署变得更加简单和一致。以下是 Docker Compose 的一些重要概念和用法:
1. Compose 文件
Compose 文件是 Docker Compose 的核心组件,通常命名为 docker-compose.yml。这个文件用于定义应用程序的服务、网络和卷等。它描述了容器之间的关系、容器的配置选项以及如何运行这些容器。Compose 文件使用 YAML 格式,因此它是易读易写的。
2. 服务
Compose 文件中的每个顶级键都代表一个服务。服务定义了应用程序的一个部分,通常对应一个容器。服务包含配置信息,例如使用的 Docker 镜像、容器的端口映射、环境变量、卷挂载等。
version: '3'
services:web:image: nginx:latestports:- "8080:80"volumes:- ./html:/usr/share/nginx/html
上面的例子定义了一个名为 web 的服务,使用 Nginx 镜像,将主机的 8080 端口映射到容器的 80 端口,并将主机的 ./html 目录挂载到容器的 /usr/share/nginx/html 目录。
3. 网络
Compose 允许你定义自己的网络,以便服务之间可以相互通信。默认情况下,Compose 会为你的应用程序创建一个默认网络,但你也可以自定义网络以更好地满足你的需求。
4. 卷
卷允许在容器之间共享和持久化数据。Compose 允许你将主机的目录或其他容器的卷挂载到你的服务中。
5. 启动和停止服务
使用 docker-compose up 命令可以启动应用程序,而 docker-compose down 命令则会停止并移除相关的容器、网络和卷。
docker-compose up -d # 在后台启动服务
docker-compose down # 停止并移除服务
6. 重启服务
使用 docker-compose restart 命令可以重新启动一个或多个服务。
docker-compose restart [service_name]
使用 Docker Compose,你可以更轻松地定义、配置和管理多个 Docker 容器,为复杂的应用程序提供了一种方便的部署方式。
二、通过Docker Compose部署微服务实战
上传项目
将后端所有服务模块的jar包上传到Linux服务器项目目录下,因为每个服务模块都需要配置个Dockerfile,所以分别建各自的目录,结构如下:
其中,nacos为注册中心和配置中心服务,gateway是网关服务,system为系统服务,business是主要的业务服务,html下放的是前端vue编译后的js、html等文件,nginx.conf是nginx的配置文件。每个目录下都有Dockerfile文件。
nacos配置文件
Dockerfile
FROM openjdk:8-jre-alpine
WORKDIR /appCOPY ./*.jar /app
COPY ./application.yml /app/application.yml
RUN apk update && apk add --no-cache libc6-compat
RUN apk update && apk add --no-cache gcompat
ENTRYPOINT ["java","-jar","/app/jeecg-cloud-nacos-2.3.5.RELEASE.jar"]
application.yml
server:servlet:contextPath: /nacostomcat:accesslog:enabled: truepattern: '%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i'basedir: ''
spring:datasource:platform: mysql
db:num: 1password:'0': xxxxxxxxxxxxurl:'0': jdbc:mysql://mysql57:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueuser:'0': root
management:metrics:export:elastic:enabled: falseinflux:enabled: false
nacos:core:auth:caching:enabled: truedefault:token:expire:seconds: 18000secret:key: SecretKey012345678901234567890123456789012345678901234567890123456789enabled: falsesystem:type: nacosistio:mcp:server:enabled: falsenaming:empty-service:auto-clean: trueclean:initial-delay-ms: 50000period-time-ms: 30000security:ignore:urls: /,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**standalone: true
gateway配置文件
Dockerfile
FROM openjdk:8-jre-alpine
WORKDIR /appCOPY ./*.jar /app
COPY ./application.yml /app/application.yml
ENTRYPOINT ["java","-jar","/app/jeecg-cloud-gateway-3.2.0.jar"]
application.yml
server:port: 9999
spring:application:name: jeecg-gateway#redis 配置redis:database: 0host: redis-6lettuce:pool:max-active: 8 #最大连接数据库连接数,设 0 为没有限制max-idle: 8 #最大等待连接中的数量,设 0 为没有限制max-wait: -1ms #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。min-idle: 0 #最小等待连接中的数量,设 0 为没有限制shutdown-timeout: 100ms# password: 123456a?port: 6379main:#循环依赖默认情况下已经被禁止了allow-circular-references: trueallow-bean-definition-overriding: truecloud:nacos:config:username: nacospassword: nacosnamespace: server-addr: nacos:8848group: DEFAULT_GROUPfile-extension: yamlprefix: jeecgdiscovery:namespace: server-addr: nacos:8848watch:enabled: false#Sentinel配置sentinel:transport:dashboard: jeecg-boot-sentinel:9000# 支持链路限流web-context-unify: falsefilter:enabled: false# 取消Sentinel控制台懒加载eager: falsedatasource:#流控规则flow: # 指定数据源名称# 指定nacos数据源nacos:server-addr: nacos:8848# 指定配置文件dataId: ${spring.application.name}-flow-rules# 指定分组groupId: SENTINEL_GROUP# 指定配置文件规则类型rule-type: flow# 指定配置文件数据格式data-type: json#降级规则degrade:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-degrade-rulesgroupId: SENTINEL_GROUPrule-type: degradedata-type: json#系统规则system:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-system-rulesgroupId: SENTINEL_GROUPrule-type: systemdata-type: json#授权规则authority:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-authority-rulesgroupId: SENTINEL_GROUPrule-type: authoritydata-type: json#热点参数param-flow:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-param-rulesgroupId: SENTINEL_GROUPrule-type: param-flowdata-type: json#网关流控规则gw-flow:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-flow-rulesgroupId: SENTINEL_GROUPrule-type: gw-flowdata-type: json#API流控规则gw-api-group:nacos:server-addr: nacos:8848dataId: ${spring.application.name}-api-rulesgroupId: SENTINEL_GROUPrule-type: gw-api-groupdata-type: jsongateway:discovery:locator:enabled: trueglobalcors:add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题cors-configurations:'[/**]':allowCredentials: true#springboot2.4后需用allowedOriginPatternsallowedOriginPatterns: "*"allowedMethods: "*"allowedHeaders: "*"
system配置文件
Dockerfile
FROM openjdk:8-jre-alpine
WORKDIR /appCOPY ./*.jar /app
COPY ./application.yml /app/application.yml
RUN apk add --update ttf-dejavu fontconfig
ENTRYPOINT ["java","-jar","/app/jeecg-cloud-system-start-3.2.0.jar"]
application.yml
server:#微服务端口port: 7001
spring:application:name: jeecg-systemcloud:nacos:config:username: nacospassword: nacosnamespace: server-addr: nacos:8848group: DEFAULT_GROUPfile-extension: yamlprefix: jeecgdiscovery:namespace: server-addr: nacos:8848watch:enabled: falsedatasource:dynamic:datasource:master:url: jdbc:mysql://mysql57:3306/trade-service-platform?rewriteBatchedStatements=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=trueusername: rootpassword: 2020miman2023driver-class-name: com.mysql.cj.jdbc.Driveradms7pro:url: jdbc:sqlserver://123.51.235.21:1433;DatabaseName=adms7prousername: JGLogpassword: JG5656driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver#redis 配置redis:database: 0host: redis-6lettuce:pool:max-active: 8 #最大连接数据库连接数,设 0 为没有限制max-idle: 8 #最大等待连接中的数量,设 0 为没有限制max-wait: -1ms #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。min-idle: 0 #最小等待连接中的数量,设 0 为没有限制shutdown-timeout: 100ms# password: 123456a?port: 6379jeecg:# 签名密钥串(前后端要一致,正式发布请自行修改)signatureSecret: dd05f1c54d63749eda95f9fa6d49v442a
business配置文件
Dockerfile
FROM openjdk:8-jre-alpine
WORKDIR /appCOPY ./*.jar /app
COPY ./application.yml /app/application.yml
ENTRYPOINT ["java","-jar","/app/jeecg-module-business-start.jar"]
application.yml
server:port: 7002
spring:main:allow-bean-definition-overriding: trueapplication:name: jeecg-businesscloud:nacos:config:username: nacospassword: nacosnamespace: server-addr: nacos:8848group: DEFAULT_GROUPfile-extension: yamlprefix: jeecgdiscovery:namespace: server-addr: nacos:8848watch:enabled: falsedatasource:dynamic:datasource:master:url: jdbc:mysql://mysql57:3306/trade-service-platform?rewriteBatchedStatements=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=trueusername: rootpassword: 2020mima2023driver-class-name: com.mysql.cj.jdbc.Driveradms7pro:url: jdbc:sqlserver://123.111.111.81:1433;DatabaseName=adms7prousername: rootpassword: JGLog11111driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver#redis 配置redis:database: 0host: redis-6lettuce:pool:max-active: 8 #最大连接数据库连接数,设 0 为没有限制max-idle: 8 #最大等待连接中的数量,设 0 为没有限制max-wait: -1ms #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。min-idle: 0 #最小等待连接中的数量,设 0 为没有限制shutdown-timeout: 100ms# password: 123456a?port: 6379jeecg:# 签名密钥串(前后端要一致,正式发布请自行修改)signatureSecret: dd05f1c54d63749eda95f9fa6d49v442a
mybatis-plus:configuration:map-underscore-to-camel-case: true
将前端打包后的dist内文件放到html中
根目录下放一个nginx配置文件:nginx.conf,ip改为对应的网关容器名gateway
#user nobody;
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;underscores_in_headers on; sendfile on;keepalive_timeout 65;server {listen 3001;server_name localhost;gzip on;gzip_min_length 1k;gzip_comp_level 9;gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;gzip_vary on;gzip_disable "MSIE [1-6]\.";location ^~ /jeecg-boot/ {proxy_pass http://gateway:9999/;#proxy_set_header Host 10.10.10.164; client_max_body_size 100m;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods *;add_header Access-Control-Allow-Headers *;if ($request_method = 'OPTIONS') {return 204;}add_header 'Access-Control-Allow-Credentials' true;add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';}location / {root /usr/share/nginx/html;index index.html index.htm;if (!-e $request_filename) {rewrite ^(.*)$ /index.html?s=$1 break;rewrite ^(.*)$ /index.html?s=$1 last;break;}}location ^~ /websocket/ {proxy_pass http://gateway:9999/websocket/;proxy_read_timeout 600;proxy_connect_timeout 4s;proxy_send_timeout 12s;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";}# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
}
根目录下新建Docker Compose的配置文件docker-compose.yml
version: "3"
services: nacos:container_name: nacosbuild:context: ./nacosdockerfile: Dockerfile image: nacos:latestenvironment:- TZ=Asia/Shanghaivolumes:- /etc/localtime:/etc/localtime:ro #配置与宿主机时钟一致- /etc/timezone/timezone:/etc/timezone:ro #配置与宿主机时钟一致ports:- 8848:8848networks:- jg_networkrestart: alwaysgateway:container_name: gatewaybuild:context: ./gatewaydockerfile: Dockerfile image: gateway:latestenvironment:- TZ=Asia/Shanghaivolumes:- /etc/localtime:/etc/localtime:ro #配置与宿主机时钟一致- /etc/timezone/timezone:/etc/timezone:ro #配置与宿主机时钟一致ports:- 9999:9999depends_on:- nacosnetworks:- jg_networkrestart: alwayssystem:container_name: systembuild:context: ./systemdockerfile: Dockerfile image: system:latestenvironment:- TZ=Asia/Shanghaivolumes:- /etc/localtime:/etc/localtime:ro #配置与宿主机时钟一致- /etc/timezone/timezone:/etc/timezone:ro #配置与宿主机时钟一致ports:- 7001:7001depends_on:- nacosnetworks:- jg_networkrestart: alwaysbusiness:container_name: businessbuild:context: ./businessdockerfile: Dockerfile image: business:latestenvironment:- TZ=Asia/Shanghaivolumes:- /etc/localtime:/etc/localtime:ro #配置与宿主机时钟一致- /etc/timezone/timezone:/etc/timezone:ro #配置与宿主机时钟一致ports:- 7002:7002depends_on:- nacosnetworks:- jg_networkrestart: always#nginx服务nginx:image: nginx:1.18.0container_name: nginxenvironment:- TZ=Asia/Shanghaiports:- "3001:3001"volumes:- ./html:/usr/share/nginx/html- ./nginx.conf:/etc/nginx/nginx.confrestart: alwaysnetworks:- jg_networknetworks:jg_network:external: true
三、启动容器编排
# 在后台启动服务
docker-compose up -d
# 停止并移除服务
docker-compose down
# 重新构建镜像 --force-rm 删除构建过程中的临时容器。
docker-compose build --force-rm
# 查看实时日志,如system
docker logs -t -f system