Docker进阶

Docker进阶

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:

  1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
    • Dockerfile`保证我们的项目在任何地方都可以运行
  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
    • Services 什么是服务
    • docker-compose.yml 怎么写
  3. Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using the docker-compose binary.
    • 启动项目

作用:批量容器编排

Compose 是Docker官方的开源项目,需要安装

Dockerfile 让程序在任何地方运行,web服务,mysql,redis…多个容器

Compose

version: "3.9"  # optional since v1.27.0
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
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

体验

官方文档: Get started with Docker Compose | Docker Documentation

创建文件夹

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 
# 或 ctrl+c

docker-compose
以前都是单个docker run启动容器。
docker-compose。通过 docker-compose编写yaml配置文件、可以通过compose一键启动所有服务,停止。!

小结

1、Docker镜像。run =>容器

2、DockerFile构建镜像(服务打包)
3、docker-compose启动项目(编排、多个微服务/环境)4、Docker网络!

yaml 规则

docker-compose.yaml 核心

官方地址: Compose specification | Docker Documentation

# 总共三层

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.

There are two types of nodes: managers and workers.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EyRMnsVU-1658059434816)(Docker进阶.assets/1658048345555.png)]

If you haven’t already, read through the swarm mode overview and key concepts.

搭建集群

查看命令

[root@root liapp]# docker swarm --help

Usage:  docker swarm COMMAND

Manage Swarm

Commands:
  ca          Display and rotate the root CA
  init        Initialize a swarm                    # 初始化一个swarm集群
  join        Join a swarm as a node and/or manager # 加入一个swarm集群
  join-token  Manage join tokens                    # 创建一个token
  leave       Leave the swarm                       # 离开一个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]# docker swarm init --help

Usage:  docker swarm init [OPTIONS]

Initialize a swarm

Options:
# --advertise-addr 地址 
      --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协议

假设一个节点挂了!其他节点是否可以用

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]# docker service --help

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]# docker service create --help

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容器维护创建!)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
感谢您的提问!以下是一些关于 Docker 学习的建议: 1. 学习容器编排工具:Docker Compose 和 Kubernetes 是两个常用的容器编排工具。通过学习它们,您可以更好地管理和编排多个容器,构建复杂的应用架构。 2. 持续集成与持续部署(CI/CD):学习如何使用 Docker 构建持续集成和持续部署流程。这将有助于自动化应用程序的构建、测试和部署,提高开发和交付效率。 3. 多段构建(Multi-stage Builds):掌握多段构建技术可以帮助您优化 Docker 镜像的大小和性能。通过在构建过程中创建多个段,并且只保留最终运行所需的组件,可以减小镜像的体积。 4. Docker 插件和扩展:探索 Docker 的插件和扩展生态系统,了解如何使用它们来扩展 Docker 的功能。一些常见的扩展包括网络插件、存储插件和身份验证插件,它们可以提供额外的功能和灵活性。 5. 容器安全和隔离:学习如何配置和管理容器的安全性和隔离性。了解容器的安全最佳实践,并使用适当的配置和工具来加强容器的安全性,以防止潜在的攻击和数据泄漏。 6. Docker Swarm:Docker Swarm 是 Docker 官方提供的一个原生的容器编排和集群管理工具。通过学习 Docker Swarm,您可以了解如何使用它来管理分布式应用程序,并实现负载均衡和高可用性。 7. 监控和日志:学习如何监控和记录 Docker 容器的性能和日志。了解如何使用相关工具和技术来监测容器的资源利用率、运行状况和错误日志,以便及时发现和解决问题。 这些是 Docker 学习的一些建议,希望对您有所帮助!如有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值