云原生(四)、Docker-Compose

Docker-Compose

Docker Compose 是一个用于定义和运行多容器 Docker 应用程序的工具。它使用一个简单的 YAML 文件来配置应用程序的服务、网络和卷,从而使得在不同环境中轻松部署应用程序变得更加简单和可靠。

Docker Compose 主要由以下几个核心组件组成:

  1. YAML 文件:用于定义 Docker 应用程序的配置文件,包括服务、网络、卷等信息。这个文件通常命名为 docker-compose.yml

  2. 服务(Services):每个服务对应一个容器,用于运行应用程序中的一个特定组件,比如一个数据库、Web 服务器、消息队列等。

  3. 网络(Networks):用于定义容器之间的网络连接方式,包括桥接网络、主机网络等。

  4. 卷(Volumes):用于定义容器内外部的数据持久化和共享。

通过 Docker Compose,用户可以通过简单的命令启动、停止、重启整个应用程序,而不需要手动创建和管理每个容器。这使得开发、测试和生产环境之间的部署更加一致和可重复。

docker-compose 官方文档: https://docs.docker.com/compose/

# 容器批量管理工具
# Compose定义和运行多个docekr容器,通过Compose,使用一个yarm文件管理应用服务。通过一个简单的命令,就可以将所有服务全部启动

Docker Compose is a tool for defining and running multi-container applications. It is the key to unlocking a streamlined and efficient development and deployment experience.

Compose simplifies the control of your entire application stack, making it easy to manage services, networks, and volumes in a single, comprehensible YAML configuration file. Then, with a single command, you create and start all the services from your configuration file.

Compose中有两个重要的概念:

  • 服务:一个应用的容器,实际上可以包括若干运行相同镜像的容器实例,
    • 订单服务image
    • 物流服务image
    • 用户服务iamge
    • 支付服务image
    • 4个容器后面构成一个服务 service
  • 项目:由一组关联的应用容器组成的一个完整的业务单元,在docker-compose中定义

Compose项目是由python编写的,实际上就是调用了Docker服务提供的API来对容器进行管理,因此,只要所在的操作系统的平台支持DockerAPI,就可以在其上利用Compose来进行容器编排管理

1、docker-compose安装

下载文件,并安装授权

# 方法1
sudo apt-get update
sudo apt-get install docker-compose-plugin

#方法2
sudo yum update
sudo yum install docker-compose-plugin

#安装成功
[root@hcss-ecs-8f46 ~]# docker-compose -v
Docker Compose version v2.24.7

尝试使用compose

官方案例:https://docs.docker.com/compose/gettingstarted/

Step1

1、Create a directory for the project:

创建文件目录,并进入

mkdir composetest
cd composetest

2、Create a file called app.py in your project directory and paste the following code in:

在composetest目录像创建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)

3、Create another file called requirements.txt in your project directory and paste the following code in:

创建一个文本文件requirements.txt,录入内容

flask
redis
Step2

The Dockerfile is used to build a Docker image. The image contains all the dependencies the Python application requires, including Python itself.

In your project directory, create a file named Dockerfile and paste the following code in:

在项目目录创建Dockerfile文件,录入内容

# syntax=docker/dockerfile:1
FROM python:3.10-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"]
Step3

Create a file called compose.yaml in your project directory and paste the following:

创建compose.yaml文件,录入内容

services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"
Step4

使用命令docker compose up 运行yaml文件,它会自动运行文件中所有的镜像并构建容器

docker compose up

测试:访问服务器ip:80,可以看到一个时间计数器。

docker compose 命令需要在项目目录下才能使用

2、Compose命令

[root@hcss-ecs-8f46 composetest]# docker compose --help

Usage:  docker compose [OPTIONS] COMMAND

Define and run multi-container applications with Docker

Options:
      --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, 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 the first service container stops
  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 -d 启动应用程序开始

docker compose logs和ps命令可以用来验证应用程序的状态,还能帮助调试。

修改代码后,先执行 docker compose build 构建新的镜像,然后执行 docker compose up-d 取代运行中的容器

注意,Compose会保留原来容器中所有旧的数据卷,这意味着即使容器更新后,数据库和缓存也依旧在容器内(这很可能造成混淆,因此要特别小心)

如果你修改了Compose的YAML文件,但不需要构建新的镜像,可以通过up-d参数使Compose以新的配置替换容器

如果想要强制停止Compose并重新创建所有容器,docker compose stop xxxx和 docker compose rm xxxx

简单使用:
1、执行命令运行容器:docker compose up -d
2、查看镜像:docker images
3、停止和删除容器: docker compose stop xx和 docker compose rm xxxx

3、compose.yaml文件

模板文件是Compose的核心,涉及的指令关键字比较多但是大部分的指令与docker run相关的参数的含义是类似的

默认的模板名是docker-compose.yml

#语法-3层
version:""
services:#定义很多服务
  服务1:
  #当前的服务配置
  服务2:
  #当前服务配置
#服务要用的网络、卷、等其他全局规则
volumes :
networks :
configs :
...

官网链接:https://docs.docker.com/compose/compose-file/#compose-file-structure-and-examples

yaml文件参数
  1. version: 指定 Compose 文件格式的版本。版本号决定了可以使用的功能和语法。

  2. services: 定义要运行的各个服务的配置。每个服务可以包含以下参数:

    • image: 指定要使用的镜像名称。
    • build: 指定 Dockerfile 所在的目录路径,用于构建镜像。
    • ports: 指定端口映射,将容器内部端口映射到主机的端口。
    • volumes: 指定挂载的数据卷。
    • environment: 设置环境变量。
    • command: 指定要运行的命令。
    • 等等,还有很多其他的参数可以用于配置服务的行为。
  3. networks: 定义要使用的网络配置。可以配置自定义网络以便服务之间的通信。

  4. volumes: 定义要使用的卷配置。可以配置匿名卷或具名卷,用于数据持久化或共享。

  5. configs: 定义要使用的配置对象。可以将配置文件注入到服务中,以便动态配置。

  6. secrets: 定义要使用的敏感数据。可以将敏感数据注入到服务中,以便安全地使用。

  7. deploy: 用于指定部署配置的参数。这些参数包括部署的模式、副本数、更新策略等。

  8. restart: 指定容器退出时的重启策略,如 “no”、“always”、“on-failure” 等。

  9. depends_on: 指定服务之间的依赖关系,确保一个服务在另一个服务之前启动。(重要)

  10. labels: 为服务添加标签,用于组织和管理。

  11. extends: 允许服务的配置从其他服务或外部文件中继承配置。

  12. external_links: 将容器链接到在 Docker 外部定义的容器。

  13. container_name: 指定容器的名称。

  14. expose: 暴露容器的端口,但不映射到主机。

  15. extra_hosts: 添加额外的主机名解析到容器中。

  16. healthcheck: 配置服务的健康检查选项。

  17. logging: 配置服务的日志记录选项。

  18. stdin_open/tty: 控制是否打开标准输入以及是否分配一个伪终端。

  19. privileged: 指定容器是否拥有特权访问。

  20. tmpfs: 将临时文件系统挂载到容器中。

  21. ulimits: 配置容器的资源限制。

4、实战 WorldPress

github项目地址:https://github.com/docker/awesome-compose/tree/master/official-documentation-samples/wordpress

  • 根据文档创建docker-compose.yml文件
  • 执行命令docker compose up -d启动项目

通过服务器ip:80访问项目。
在这里插入图片描述

  • 28
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值