Docker Compose
Docker
DockerFile build run 手动操作单个容器
微服务 微服务之间的依赖关系
Docker Compose 来轻松高效的管理容器,定义运行多个容器
官方介绍
定义,运行多个容器
YAML file配置文件
single command 命令有哪些
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.
所有的环境都可以使用Compose
Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.
三步骤
Using Compose is basically a three-step process:
作用:批量容器编排
Compose 是Docker官方的开源项目,需要安装
Dockerfile 让程序在任何地方运行,web服务,mysql,redis…多个容器
Compose
version: "3.9" services: web: build: . ports: - "8000:5000" volumes: - .:/code - logvolume01:/var/log links: - redis redis: image: redis volumes: logvolume01: {}
Compose:重要概念
- 服务services,容器,应用,(web,redis,mysql…)
- 项目project,一组关联的容器
1.下载
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yNyBa3bT-1658059434812)(Docker进阶.assets/1657939654808.png)]
2.授权
sudo chmod +x /usr/local/bin/docker-compose sudo chmod +x docker-compose
docker-compose version [root@root bin] docker-compose version 1.25.5, build 8a1c60f6 docker-py version: 4.1.0 CPython version: 3.7.5 OpenSSL version: OpenSSL 1.1.0l 10 Sep 2019
创建文件夹
mkdir composetest cd composetest
创建 app.py 文件
vim app.py import time import redis from flask import Flask app = Flask(__name__) cache = redis.Redis(host='redis', port=6379) def get_hit_count(): retries = 5 while True: try: return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5) @app.route('/') def hello(): count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count)
创建 requirements.txt 文件
vim requirements.txt flask redis
创建 Dockerfile 文件
vim Dockerfile FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add --no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD ["flask", "run"]
定义 docker-compose.yml 文件
vim docker-compose.yml version: "3.9" services: web: build: . ports: - "8000:5000" redis: image: "redis:alpine"
docker compose up docker-compose up
总结:分为4步
1、应用 app.py
2、Dockerfile 应用打包为镜像
3、Docker-compose.yaml 文件(定义整个服务,需要的环境,web,redis)完整的上线服务
4、启动compose项目(docker-compose up)
流程:
1、创建网络
2、执行Docker-compose.yaml
3、启动服务
Docker-compose.yaml
Compose composetest_web_1 …done
Compose composetest_redis_1 …done
1、文件名composetest
2、服务
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Sd7VbbHV-1658059434814)(Docker进阶.assets/1657955621172.png)]
version: "3.9" services: web: build: . ports: - "8000:5000" redis: image: "redis:alpine"
自动的默认规则?
docker images
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aoqs0ulE-1658059434814)(Docker进阶.assets/1657956417713.png)]
默认的服务名 文件名_服务名 _num
多个服务器。集群。A B_num副本数量
服务redis服务略=>4个副本。
集群状态。服务都不可能只有一个运行实例。弹性.10 HA高并发。
(k8s中)kubectl service负载均衡。
3、网络规则
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZV9oaAFw-1658059434815)(Docker进阶.assets/1657964566260.png)]
10个服务=>项目 (项目中的内容都在同一个网络下,域名访问)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RjPSHevH-1658059434815)(Docker进阶.assets/1657964686084.png)]
停止:
docker compose down
docker-compose
以前都是单个docker run启动容器。
docker-compose。通过 docker-compose编写yaml配置文件、可以通过compose一键启动所有服务,停止。!
1、Docker镜像。run =>容器
2、DockerFile构建镜像(服务打包)
3、docker-compose启动项目(编排、多个微服务/环境)4、Docker网络!
docker-compose.yaml 核心
version: '' services: 服务1: web images: port: network: depends_on: ... 服务2: redis ... volumes: network:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3ZF7fdWu-1658059434816)(Docker进阶.assets/1657965844691.png)]
services: db: image: mariadb:10.6.4-focal command: '--default-authentication-plugin=mysql_native_password' volumes: - db_data:/var/lib/mysql restart: always environment: - MYSQL_ROOT_PASSWORD=somewordpress - MYSQL_DATABASE=wordpress - MYSQL_USER=wordpress - MYSQL_PASSWORD=wordpress expose: - 3306 - 33060 wordpress: image: wordpress:latest ports: - 80:80 restart: always environment: - WORDPRESS_DB_HOST=db - WORDPRESS_DB_USER=wordpress - WORDPRESS_DB_PASSWORD=wordpress - WORDPRESS_DB_NAME=wordpress volumes: db_data:
1、编写项目微服务
2、dockerfile构建镜像
3.docker-compose.yaml 编排项目
4、丢到服务器docker-compose up
小结:
未来项目只要有docker-compose文件。按照这个规则,启动编排容器。!
公司: docker-compose。直接启动。
网上开源项目: docker-compose一键搞定。
假设项目要重新部署打包
docker-compose --build docker compose --build
总结:
工程、服务、容器项目
compose:三层·工程 Porject·服务服务
容器运行实例! docker k8s容器
Docker Swarm
官网地址
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ehCgRAUL-1658059434816)(Docker进阶.assets/1658048039422.png)]
Estimated reading time: 2 minutes
Docker Engine 1.12 introduces swarm mode that enables you to create a cluster of one or more Docker Engines called a swarm. A swarm consists of one or more nodes: physical or virtual machines running Docker Engine 1.12 or later in swarm mode.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EyRMnsVU-1658059434816)(Docker进阶.assets/1658048345555.png)]
查看命令
[root@root liapp] Usage: docker swarm COMMAND Manage Swarm Commands: ca Display and rotate the root CA init Initialize a swarm join Join a swarm as a node and/or manager join-token Manage join tokens leave Leave the swarm unlock Unlock swarm unlock-key Manage the unlock key update Update the swarm Run 'docker swarm COMMAND --help' for more information on a command.
查看init后面可以跟的命令
[root@root liapp] Usage: docker swarm init [OPTIONS] Initialize a swarm Options: --advertise-addr string Advertised address (format: <ip|interface>[:port]) --autolock Enable manager autolocking (requiring an unlock key to start a stopped manager) --availability string Availability of the node ("active"|"pause"|"drain") (default "active") --cert-expiry duration Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s) --data-path-addr string Address or interface to use for data path traffic (format: <ip|interface>) --data-path-port uint32 Port number to use for data path traffic (1024 - 49151). If no value is set or is set to 0, the default port (4789) is used. --default-addr-pool ipNetSlice default address pool in CIDR format (default []) --default-addr-pool-mask-length uint32 default address pool subnet mask length (default 24) --dispatcher-heartbeat duration Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s) --external-ca external-ca Specifications of one or more certificate signing endpoints --force-new-cluster Force create a new cluster from current state --listen-addr node-addr Listen address (format: <ip|interface>[:port]) (default 0.0.0.0:2377) --max-snapshots uint Number of additional Raft snapshots to retain --snapshot-interval uint Number of log entries between Raft snapshots (default 10000) --task-history-limit int Task history retention limit (default 5)
地址分为公网和私网
初始化节点
doccker swarm init --advertise-addr 192.168.49.131
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Eb3d7TPP-1658059434817)(Docker进阶.assets/1658049892760.png)]
docker swarm join 加入一个节点
docker swarm join-token manager docker swarm join-token worker
1.生成主节点 init
2.加入(管理者,worker)
假设一个节点挂了!其他节点是否可以用
Raft协议:保证大多数存活才可以用,只要>1,集群至少大于3台
实验:
1.将docker1停止,(宕机)双主,另外一个主节点也不能使用了
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hHU4l1uF-1658059434817)(Docker进阶.assets/1658050967539.png)]
2.可以将其他节点移开
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nH20BuKC-1658059434818)(Docker进阶.assets/1658051016360.png)]
3.work就是工作的、管理节点操作!
十分简单:集群,可用!3个主节点。>1台管理节点存活!
Raft协议:保证大多数节点存活,才可以使用,高可用!
弹性。扩缩容,集群!
以后告别docker run!
docker-compose up!启动一个项目。单机!
集群: swarm docker serivce
容器=→>服务!
容器=>服务!>副本!
redis 服务=>10个副本!(同时开启10个redis容器)
docker service 命令
[root@root liapp] Usage: docker service COMMAND Manage services Commands: create Create a new service inspect Display detailed information on one or more services logs Fetch the logs of a service or task ls List services ps List the tasks of one or more services rm Remove one or more services rollback Revert changes to a service's configuration scale Scale one or multiple replicated services update Update a service Run 'docker service COMMAND --help' for more information on a command.
创建后跟的参数
[root@root liapp] Usage: docker service create [OPTIONS] IMAGE [COMMAND] [ARG...] Create a new service Options: --cap-add list Add Linux capabilities --cap-drop list Drop Linux capabilities --config config Specify configurations to expose to the service --constraint list Placement constraints --container-label list Container labels --credential-spec credential-spec Credential spec for managed service account (Windows only) -d, --detach Exit immediately instead of waiting for the service to converge --dns list Set custom DNS servers --dns-option list Set DNS options --dns-search list Set custom DNS search domains --endpoint-mode string Endpoint mode (vip or dnsrr) (default "vip") --entrypoint command Overwrite the default ENTRYPOINT of the image -e, --env list Set environment variables --env-file list Read in a file of environment variables --generic-resource list User defined resources --group list Set one or more supplementary user groups for the container --health-cmd string Command to run to check health --health-interval duration Time between running the check (ms|s|m|h) --health-retries int Consecutive failures needed to report unhealthy --health-start-period duration Start period for the container to initialize before counting retries towards unstable (ms|s|m|h) --health-timeout duration Maximum time to allow one check to run (ms|s|m|h) --host list Set one or more custom host-to-IP mappings (host:ip) --hostname string Container hostname --init Use an init inside each service container to forward signals and reap processes --isolation string Service container isolation mode -l, --label list Service labels --limit-cpu decimal Limit CPUs --limit-memory bytes Limit Memory --limit-pids int Limit maximum number of processes (default 0 = unlimited) --log-driver string Logging driver for service --log-opt list Logging driver options --max-concurrent uint Number of job tasks to run concurrently (default equal to --replicas) --mode string Service mode (replicated, global, replicated-job, or global-job) (default "replicated") --mount mount Attach a filesystem mount to the service --name string Service name --network network Network attachments --no-healthcheck Disable any container-specified HEALTHCHECK --no-resolve-image Do not query the registry to resolve image digest and supported platforms --placement-pref pref Add a placement preference -p, --publish port Publish a port as a node port -q, --quiet Suppress progress output --read-only Mount the container's root filesystem as read only --replicas uint Number of tasks --replicas-max-per-node uint Maximum number of tasks per node (default 0 = unlimited) --reserve-cpu decimal Reserve CPUs --reserve-memory bytes Reserve Memory --restart-condition string Restart when condition is met ("none"|"on-failure"|"any") (default "any") --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) (default 5s) --restart-max-attempts uint Maximum number of restarts before giving up --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) --rollback-delay duration Delay between task rollbacks (ns|us|ms|s|m|h) (default 0s) --rollback-failure-action string Action on rollback failure ("pause"|"continue") (default "pause") --rollback-max-failure-ratio float Failure rate to tolerate during a rollback (default 0) --rollback-monitor duration Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h) (default 5s) --rollback-order string Rollback order ("start-first"|"stop-first") (default "stop-first") --rollback-parallelism uint Maximum number of tasks rolled back simultaneously (0 to roll back all at once) (default 1) --secret secret Specify secrets to expose to the service --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) (default 10s) --stop-signal string Signal to stop the container --sysctl list Sysctl options -t, --tty Allocate a pseudo-TTY --ulimit ulimit Ulimit options (default []) --update-delay duration Delay between updates (ns|us|ms|s|m|h) (default 0s) --update-failure-action string Action on update failure ("pause"|"continue"|"rollback") (default "pause") --update-max-failure-ratio float Failure rate to tolerate during an update (default 0) --update-monitor duration Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 5s) --update-order string Update order ("start-first"|"stop-first") (default "stop-first") --update-parallelism uint Maximum number of tasks updated simultaneously (0 to update all at once) (default 1) -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) --with-registry-auth Send registry authentication details to swarm agents -w, --workdir string Working directory inside the container
docker run docker service
扩缩容
docker service update --replicas 3 my-nginx
服务。集群中任意的节点都可以访问。服务可以有多个副本动态扩缩容实现高可用!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nemmixSI-1658059434819)(Docker进阶.assets/1658056812315.png)]
也可以用scale进行扩缩容
docker service scale my-nginx=3
可以通过rm移除服务
docker service rm my-nginx
swarm
集群的管理和编号。docker可以初始化一个swarm集群,其他节点可以加入。(管理、工作者)
Node
就是一个docker节点。多个节点就组成了一个网络集群。(管理、工作者)
service
任务,可以在管理节点或者工作节点来运行。核心。!用户访问!
Task
客器内的命令,细节任务!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6JQFSVUW-1658059434819)(Docker进阶.assets/1658058602191.png)]
逻辑是不变的
命令->管理-> api ->调度->工作节点(创建Task容器维护创建!)
原文链接:https://blog.csdn.net/m0_64892750/article/details/125836198?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168994674616800227425886%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=168994674616800227425886&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~times_rank-6-125836198-null-null.268%5Ev1%5Ekoosearch&utm_term=docker%E3%80%81wordpress%E3%80%81wordpress%E5%BB%BA%E7%AB%99%E3%80%81wordpress%E4%B8%BB%E9%A2%98%E3%80%81%E5%AE%B9%E5%99%A8%E9%95%9C%E5%83%8F%E3%80%81