云原生(四)、Docker-Compose

news2024/10/5 16:32:24

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访问项目。
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1526902.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

DockerHub搜索并拉取一个Redis镜像

1)去DockerHub搜索Redis镜像 2)查看Redis镜像的名称和版本 3)利用docker pull命令拉取镜像 4)利用docker save命令将 redis:latest打包为一个redis.tar包 5)利用docker rmi 删除本地的redis:latest 6)利用…

小鹏MONA将至:10 - 15万级,用性价比打新势力,用智驾打比亚迪

‍ 作者 |老缅 编辑 |德新 小鹏的全新品牌即将发布,10-15万级也能有高等级智能驾驶。 3月16日在中国电动汽车百人会论坛2024上,小鹏汽车董事长、CEO何小鹏提出:“下一个十年将是智能化的十年。未来18个月内高阶智驾的拐点将到来”。 所谓…

Git——GitHub远端协作详解

目录 Git&GitHub1、将内容Push到GitHub上1.1、在GitHub上创建新项目1.2、upstream1.3、如果不想要相同的分支名称 2、Pull下载更新2.1、Fetch指令2.2、Fetch原理2.3、Pull指令2.4、PullRebase 3、为什么有时候推不上去3.1、问题复现3.2、解决方案一:先拉再推3.3…

深度学习神经网络相关记录《二》

如何判断模型是一个好模型? 模型预测效果,也就是模型预测的准确率运算速度;能够处理大量数据、短时间内急速学习、可以实时进行预测,是机器学习的重要优势;可解释性;深度学习已经不太关系这一点了&#xf…

面试算法-51-翻转二叉树

题目 给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。 示例 1: 输入:root [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1] 解 class Solution {public TreeNode invertTree(TreeNode root) {dfs(root);re…

苍穹外卖-day09:用户端历史订单模块(理解业务逻辑),商家端订单管理模块(理解业务逻辑),校验收货地址是否超出配送范围(相关API)

用户端历史订单模块 1. 查询历史订单(分页查询) 1.1 需求分析和设计 产品原型: 业务规则 分页查询历史订单可以根据订单状态查询展示订单数据时,需要展示的数据包括:下单时间、订单状态、订单金额、订单明细&#…

“SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用教程

原文链接:“SRP模型”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用教程https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&mid2247597452&idx5&snf723d9e5858a269d00e15dbe2c7d3dc0&chksmfa823c6…

202303 CSP认证 | LDAP

LDAP 好好好&#xff0c;难度直线上升&#xff0c;是一道又有了字符串处理味道的第三题 第一把写官网40分&#xff0c;acwing TLE且只通过了一道数据…本文是自己这题奋斗过程 的一个记录 先贴个40分的代码&#xff1a; #include<bits/stdc.h> using namespace std; t…

2024全新红娘交友系统定制版源码 | 相亲交友小程序源码 全开源可二开

内容目录 一、详细介绍二、效果展示1.部分代码2.效果图展示 三、学习资料下载 一、详细介绍 全新红娘交友系统定制版源码 | 相亲交友小程序源码 全开源可二开 定制版红娘交友平台小程序源码&#xff0c;很牛逼的东西&#xff0c;虽然是小程序&#xff0c;但是有700多M大&…

LeetCode每日一题【59.螺旋矩阵Ⅱ】

思路&#xff1a;模拟&#xff0c;给出上下左右4个方向的边界&#xff0c;逐步收缩 class Solution { public:vector<vector<int>> generateMatrix(int n) {int left 0;int right n-1;int top 0;int bottom n-1;int k 1;vector<vector<int>> ans…

七、链表问题(中)

2、两数相加&#xff08;中等&#xff09; 题目描述 给你两个 非空 的链表&#xff0c;表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的&#xff0c;并且每个节点只能存储 一位 数字。 请你将两个数相加&#xff0c;并以相同形式返回一个表示和的链表。 你可以…

window 查看特定端口占用并停掉

要查看Windows上特定端口的占用情况并停止相关进程&#xff0c;你可以使用以下步骤&#xff1a; 查看端口占用&#xff1a; 首先&#xff0c;你可以使用netstat命令来查看特定端口的占用情况。假设你想要查看端口号为8080的情况&#xff0c;你可以运行以下命令&#xff1a; net…

力扣● 583. 两个字符串的删除操作 ● 72. 编辑距离 ● 编辑距离总结篇

● 583. 两个字符串的删除操作 注意审题&#xff1a; 给定两个单词 word1 和 word2 &#xff0c;返回使得 word1 和 word2 相同所需的最小步数。 每步 可以删除任意一个字符串中的一个字符。 删除最少的字符使两者相同&#xff0c;说明留下来的就是最大公共子序列。不要求…

谷歌google adsense广告申请提示:网站已下线或无法访问

自己在运营网站时&#xff0c;想在网站上挂google adsense广告&#xff0c;但是申请很多次&#xff0c;收到的邮件都是您需要先纠正一些问&#xff0c;登陆google adsense后台显示&#xff0c;网站已下线或无法访问。 重新申请多次问题依旧&#xff0c;我在想为什么国外无法访…

一个可商用私有化部署的基于JAVA的chat-gpt网站

目录 介绍一、核心功能1、智能对话2、AI绘画3、知识库4、一键思维导图5、应用广场6、GPTS 二、后台管理功能1、网站自定义2、多账号登录支持3、商品及会员系统4、模型配置5、兑换码生成6、三方商户用户打通 结语 介绍 java语言的私有化部署的商用网站还是比较少的 这里给大家介…

C语言中大小写字母如何转化

&#x1f31f; 前言 欢迎来到我的技术小宇宙&#xff01;&#x1f30c; 这里不仅是我记录技术点滴的后花园&#xff0c;也是我分享学习心得和项目经验的乐园。&#x1f4da; 无论你是技术小白还是资深大牛&#xff0c;这里总有一些内容能触动你的好奇心。&#x1f50d; &#x…

GaussDB数据库的索引管理

目录 一、引言 二、GaussDB数据库中的索引基本概念 1. 什么是GaussDB索引&#xff1f; 2. GaussDB索引的作用 三、GaussDB支持的索引类型 1. B-Tree索引 2. GIN索引 3. GiST索引 4. SP-GiST索引 四、创建和管理GaussDB索引 1. 创建索引 2. 删除索引 3. 索引的优化…

主键约束

Oracle从入门到总裁:​​​​​​https://blog.csdn.net/weixin_67859959/article/details/135209645 主键约束可以看成是非空约束再加上唯一约束 也就是说设置为主键列&#xff0c;不能为空&#xff0c;不能重复 像一般用户编号是不可能重复的&#xff0c;也不可能为空的 …

如何解决网络中IP地址发生冲突故障?

0、前言 本专栏为个人备考软考嵌入式系统设计师的复习笔记&#xff0c;未经本人许可&#xff0c;请勿转载&#xff0c;如发现本笔记内容的错误还望各位不吝赐教&#xff08;笔记内容可能有误怕产生错误引导&#xff09;。 1、个人IP地址冲突解决方案 首先winR&#xff0c;调出…