Compose

概念

对于docker 我们平时部署的流程就是编写dockerfile,然后build镜像,最后run。

但是如果容器数量过多的话,逐个进行这样的流程就比较费时费力

docker compose 就是 用来高效管理容器的,可以定义运行多个容器,在yaml配置文件中进行管理。

所有环境都可以使用 compose

作用:批量容器编排
compose是docker 官方的开源项目,需要安装
dockerfile 让程序能在任何地方运行。

compose docker 出错 docker compose详解_compose docker 出错

重要的概念

  • 服务service。容器、应用(web、redis、mysql)。最终打包起来运行起来就是project
  • 项目project。一组关联的容器

三步骤

  1. 定义dockerfile
  2. 定义服务、将服务写进 文件中
  3. 启动项目

安装

1、下载

官网下载

compose docker 出错 docker compose详解_compose docker 出错_02

2、文件权限修改

给 docker-compose 赋予 777 权限

3、检查

docker-compose version 查看是否安装成功

体验

官方地址:https://docs.docker.com/compose/gettingstarted

1、创建文件夹

mkdir composetest
cd composetest

2、创建一个文件

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)

3、创建一个依赖包

vim requirements.txt

引入redis和flask

flask
redis

4、创建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"]

5、定义服务

创建docker-compose.yml

vim docker-compose.yml
version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

6、运行

$ docker-compose up

Creating network "composetest_default" with the default driver
Creating composetest_web_1 ...
Creating composetest_redis_1 ...
Creating composetest_web_1
Creating composetest_redis_1 ... done
Attaching to composetest_web_1, composetest_redis_1
web_1    |  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
redis_1  | 1:C 17 Aug 22:11:10.480 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 17 Aug 22:11:10.480 # Redis version=4.0.1, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 17 Aug 22:11:10.480 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
web_1    |  * Restarting with stat
redis_1  | 1:M 17 Aug 22:11:10.483 * Running mode=standalone, port=6379.
redis_1  | 1:M 17 Aug 22:11:10.483 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
web_1    |  * Debugger is active!
redis_1  | 1:M 17 Aug 22:11:10.483 # Server initialized
redis_1  | 1:M 17 Aug 22:11:10.483 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
web_1    |  * Debugger PIN: 330-787-903
redis_1  | 1:M 17 Aug 22:11:10.483 * Ready to accept connections

运行过程

1、创建compose网络
2、打包执行compose.yaml
3、启动服务,根据compose文件中得名字自动生成了服务 的名字

默认的服务名格式 文件名_服务名_副本数量
原因:集群模式,同一个服务会部署很多副本

网络规则: 创建compose后会新建一个composetets-default网络。项目中得所有服务都能够通过域名访问,
如上文 app.py中写的 cache = redis.Redis(host=‘redis’, port=6379)
。这里访问redis 就是通过域名

7、停止compose

需要在compose当前文件下执行命令

$ docker-compose stop
或者
$ docker-compose down --volumes
或者
ctrl+c

compose.yaml规则

官网地址:https://docs.docker.com/compose/compose-file/compose-file-v3/

1、版本层 version

compose docker 出错 docker compose详解_docker_03


docker compose的版本信息,跟docker引擎对应,向下兼容

2、服务层 service

service:
	服务1:web
		#服务配置
		images
		build
		network
		volumes
		.....
	服务2:redis
	....

3、其他配置层

网络配置、存储卷配置、全局规则
volumes:
network:
configs:

4、示例

depends_on 启动顺序

version: "3.9"
services:
  web:
    build: .
    depends_on:		#web依赖于db和redis  启动顺序  db -> redis -> web
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

deploy 部署

version: "3.9"
services:
  redis:
    image: redis:alpine
    deploy:		#集群相关信息
      replicas: 6	# 副本数量
      placement:
        max_replicas_per_node: 1
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

实战-搭建博客WP

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

1、创建项目目录

mkdir compose
cd compose

2、编写docker-compose.yaml

version: '3.3'		#版本

services:
   db:	#服务1
     image: mysql:5.7	#使用镜像的信息
     volumes:
       - db_data:/var/lib/mysql	#挂载信息
     restart: always	#重启策略
     environment:	#环境变量信息
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:	#服务2
     depends_on:	#依赖关系,依赖上面的db
       - db
     image: wordpress:latest	#wp镜像信息
     ports:	#对外暴露的端口信息
       - "8000:80"
     restart: always	#重启策略
     environment:	#环境变量
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:	#挂载信息
    db_data: {}

3、启动项目

在compose.yaml 所在目录执行命令

$ docker-compose up

Creating network "my_wordpress_default" with the default driver
Pulling db (mysql:5.7)...
5.7: Pulling from library/mysql
efd26ecc9548: Pull complete
a3ed95caeb02: Pull complete
...
Digest: sha256:34a0aca88e85f2efa5edff1cea77cf5d3147ad93545dbec99cfe705b03c520de
Status: Downloaded newer image for mysql:5.7
Pulling wordpress (wordpress:latest)...
latest: Pulling from library/wordpress
efd26ecc9548: Already exists
a3ed95caeb02: Pull complete
589a9d9a7c64: Pull complete
...
Digest: sha256:ed28506ae44d5def89075fd5c01456610cd6c64006addfe5210b8c675881aff6
Status: Downloaded newer image for wordpress:latest
Creating my_wordpress_db_1
Creating my_wordpress_wordpress_1

查看是否部署成功

docker ps  #查看容器是否启动

浏览器访问

compose docker 出错 docker compose详解_redis_04