Javascript is required
Docker Compose

说明

以前Docker,流程是单个容器通过编写Dockerfile, build,run来手动操作。

使用DockerCompose来轻松高效管理容器,定义运行多个容器。

Compose是用于定义和运行多容器Docker应用程序的工具。通过Compose,您可以使用YAML文件来配置应用程序的服务。然后,使用一个命令,就可以从配置中创建并启动所有服务。

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

使用流程

  1. Dockerfile来保证项目可运行
  2. 定义组成应用程序服务service。 文件docker-compose.yml
  3. 启动项目docker-compose up

示例yml

version: '2.0'
services:
  web: # Web服务
    build: .
    ports:
    - "5000:5000"
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis: # Redis服务
    image: redis
volumes:
  logvolume01: {}

安装

Docker Compose依靠Docker Engine. 所以确保已安装Docker.

默认Mac系统已经安装了。或者也可以使用pip包安装

pip install docker-compose

Linux加速安装

# 1.下载
sudo curl -L "https://get.daocloud.io/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# 2.授权
sudo chmod +x /usr/local/bin/docker-compose
  ~ docker-compose version
docker-compose version 1.26.2, build eefe0d31
docker-py version: 4.2.2
CPython version: 3.7.7
OpenSSL version: OpenSSL 1.1.1g  21 Apr 2020
  ~ docker-compose
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  -f, --file FILE             Specify an alternate compose file
                              (default: docker-compose.yml)
  -p, --project-name NAME     Specify an alternate project name
                              (default: directory name)
  -c, --context NAME          Specify a context name
  --verbose                   Show more output
  --log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  --no-ansi                   Do not print ANSI control characters
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --skip-hostname-check       Don't check the daemon's hostname against the
                              name specified in the client certificate
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)
  --compatibility             If set, Compose will attempt to convert keys
                              in v3 files to their non-Swarm equivalent
  --env-file PATH             Specify an alternate environment file

Commands:
  build              Build or rebuild services
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove containers, networks, images, and volumes
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  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 services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            展示docker-compose的版本信息

快速体验

步骤

  1. 应用
  Desktop mkdir composetest
  Desktop cd 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)

requirements.txt

flask
redis
  1. Dockerfile 应用打包镜像
FROM 3.7.4-alpine3.10
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_appHOST 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"]
  1. Docker-compose.yaml 定义整个服务
  2. 启动Docker-compose

定义一个docker-compose.yaml

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

在项目根目录打开终端,构建并且运行项目

docker-compose build
docker-compose up

停止运行

docker-compose down

然后我们再看看Docker网络

下面代码是运行时的

  composetest docker-compose build
redis uses an image, skipping
Building web
Step 1/10 : FROM python:3.7-alpine
3.7-alpine: Pulling from library/python
df20fa9351a1: Pull complete
36b3adc4ff6f: Pull complete
4db9de03f499: Pull complete
cd38a04a61f4: Pull complete
6bbb0c43b470: Pull complete
Digest: sha256:d1375bf0b889822c603622dc137b24fb7064e6c1863de8cc4262b61901ce4390
Status: Downloaded newer image for python:3.7-alpine
 ---> 078114edb6be
Step 2/10 : WORKDIR /code
 ---> Running in fd9621a21c66
Removing intermediate container fd9621a21c66
 ---> 3fb596445a6d
Step 3/10 : ENV FLASK_APP app.py
 ---> Running in 59774f148143
Removing intermediate container 59774f148143
 ---> c8ddb45af25e
Step 4/10 : ENV FLASK_RUN_HOST 0.0.0.0
 ---> Running in 6f33dd2d0008
Removing intermediate container 6f33dd2d0008
 ---> ccd759a4a9bf
Step 5/10 : RUN apk add --no-cache gcc musl-dev linux-headers
 ---> Running in 7b3c7abb835d
fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/community/x86_64/APKINDEX.tar.gz
(1/13) Installing libgcc (9.3.0-r2)
(2/13) Installing libstdc++ (9.3.0-r2)
(3/13) Installing binutils (2.34-r1)
(4/13) Installing gmp (6.2.0-r0)
(5/13) Installing isl (0.18-r0)
(6/13) Installing libgomp (9.3.0-r2)
(7/13) Installing libatomic (9.3.0-r2)
(8/13) Installing libgphobos (9.3.0-r2)
(9/13) Installing mpfr4 (4.0.2-r4)
(10/13) Installing mpc1 (1.1.0-r1)
(11/13) Installing gcc (9.3.0-r2)
(12/13) Installing linux-headers (5.4.5-r1)
(13/13) Installing musl-dev (1.1.24-r9)
Executing busybox-1.31.1-r16.trigger
OK: 153 MiB in 48 packages
Removing intermediate container 7b3c7abb835d
 ---> 20773301e6af
Step 6/10 : COPY requirements.txt requirements.txt
 ---> 43c4fdd4899f
Step 7/10 : RUN pip install -r requirements.txt
 ---> Running in b3aad024091c
Collecting flask
  Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
Collecting redis
  Downloading redis-3.5.3-py2.py3-none-any.whl (72 kB)
Collecting itsdangerous>=0.24
  Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB)
Collecting Jinja2>=2.10.1
  Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB)
Collecting Werkzeug>=0.15
  Downloading Werkzeug-1.0.1-py2.py3-none-any.whl (298 kB)
Collecting click>=5.1
  Downloading click-7.1.2-py2.py3-none-any.whl (82 kB)
Collecting MarkupSafe>=0.23
  Downloading MarkupSafe-1.1.1.tar.gz (19 kB)
Building wheels for collected packages: MarkupSafe
  Building wheel for MarkupSafe (setup.py): started
  Building wheel for MarkupSafe (setup.py): finished with status 'done'
  Created wheel for MarkupSafe: filename=MarkupSafe-1.1.1-cp37-cp37m-linux_x86_64.whl size=16913 sha256=905a2d3551601b1bdabf54e7d39408a7ed322407d1462d0affd27e415fe80449
  Stored in directory: /root/.cache/pip/wheels/b9/d9/ae/63bf9056b0a22b13ade9f6b9e08187c1bb71c47ef21a8c9924
Successfully built MarkupSafe
Installing collected packages: itsdangerous, MarkupSafe, Jinja2, Werkzeug, click, flask, redis
Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2 flask-1.1.2 itsdangerous-1.1.0 redis-3.5.3
Removing intermediate container b3aad024091c
 ---> 8a1840ed2c6f
Step 8/10 : EXPOSE 5000
 ---> Running in aea130f1e6ee
Removing intermediate container aea130f1e6ee
 ---> fe200f749e07
Step 9/10 : COPY . .
 ---> e9e54c6fb4ad
Step 10/10 : CMD ["flask", "run"]
 ---> Running in 2845bd8fdb17
Removing intermediate container 2845bd8fdb17
 ---> 84fc6ba7b059
Successfully built 84fc6ba7b059
Successfully tagged composetest_web:latest
  composetest docker-compose up
Creating network "composetest_default" with the default driver
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
df20fa9351a1: Already exists
9b8c029ceab5: Pull complete
e983a1eb737a: Pull complete
3ff995df75b6: Pull complete
53083afa127f: Pull complete
2509483afa4c: Pull complete
Digest: sha256:5326e0af4341affe12c544b546f17e4fcb5db2d9204a83e5c28d8b8a98d69778
Status: Downloaded newer image for redis:alpine
Creating composetest_web_1   ... done
Creating composetest_redis_1 ... done
Attaching to composetest_redis_1, composetest_web_1
redis_1  | 1:C 04 Sep 2020 10:36:23.245 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 04 Sep 2020 10:36:23.245 # Redis version=6.0.7, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 04 Sep 2020 10:36:23.245 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 04 Sep 2020 10:36:23.246 * Running mode=standalone, port=6379.
redis_1  | 1:M 04 Sep 2020 10:36:23.247 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 04 Sep 2020 10:36:23.247 # Server initialized
redis_1  | 1:M 04 Sep 2020 10:36:23.247 # 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.
redis_1  | 1:M 04 Sep 2020 10:36:23.247 * Ready to accept connections
web_1    |  * Serving Flask app "app.py"
web_1    |  * Environment: production
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: off
web_1    |  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
web_1    | 172.18.0.1 - - [04/Sep/2020 10:41:25] "GET / HTTP/1.1" 200 -
web_1    | 172.18.0.1 - - [04/Sep/2020 10:41:25] "GET /favicon.ico HTTP/1.1

yaml规则

官方文档

https://docs.docker.com/compose/compose-file/

# 版本 与Docker版本对应 比如1.x 2.x 3.x
version: ''
# 服务
services:
    # 服务1:web
    # 服务2:redis
    redis: 
        image: redis:alpine
        ports: 
            - "6379"
    networks:
        - frontend

# 其他配置 比如 网络/卷 全局规则
volumes:
networks:
configs:

说明

官方文档

https://docs.docker.com/compose/

DaoCloud

https://www.daocloud.io/mirror

🇨🇳2018-2024 晋ICP备18004820号-4