分享

Docker

 昵称54185769 2018-07-20

Compose 是一个用户定义和运行多个容器的 Docker 应用程序。在 Compose 中你可以使用 YAML 文件来配置你的应用服务。然后,只需要一个简单的命令,就可以创建并启动你配置的所有服务。

使用 Compose 基本会有如下三步流程:

  1. 在 Dockfile 中定义你的应用环境,使其可以在任何地方复制。
  2. 在 docker-compose.yml 中定义组成应用程序的服务,以便它们可以在隔离的环境中一起运行。
  3. 最后,运行dcoker-compose up,Compose 将启动并运行整个应用程序。

开始使用 Docker Compose

这里面将会在 Docker Compose 中构建一个简单的 Python 程序。应用程序将使用 Flask 框架,并在 Redis 中维护一个计数器。

先决条件

确认你已经安装了 Docker Engine 与 Docker Compose。你不需要安装 Python 或者 Redis,这两个都会在 Docker 镜像中提供。

第一步:定义应用依赖

  1. 为项目创建目录

    $ mkdir composetest
    $ cd composetest
    • 1
    • 2
  2. 创建一个名为 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)
    
    if __name__ == "__main__":
       app.run(host="0.0.0.0", debug=True)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在这个例子中,redis 就是应用网络中 redis 容器的主机名。我们使用 Redis 的默认端口 6379。

  3. 在你的项目路径下创建另外一个叫做 requirements.txt 的文件,并将如下内容粘贴进去:

    flask
    redis
    • 1
    • 2

第二步:创建 Dockerfile

在这一步中,你需要编写一个 Dockerfile 来构建一个 Docker 镜像。这个镜像包含 Python 应用的所有依赖,也包含 Python 其本身。

在你的项目路径下创建一个 Dockerfile 文件,并将如下内容粘贴进去:

FROM python:3.4-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
  • 1
  • 2
  • 3
  • 4
  • 5

这会告诉容器:

  • 构建一个基于 Python 3.4 的镜像
  • 把当前目录添加到镜像中的 /code 路径下
  • 把工作路径设置成 /code
  • 安装 Python 依赖
  • 设置容器的默认命令为 python app.py

有关如何编写 Dockerfiles 的更多信息,请参考 Docker user guideDockerfile reference

第三步:在 Compose 文件中定义一个服务

在工作路径下创建一个叫做 docker-compose.yml 并粘贴如下内容:

version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
  redis:
    image: "redis:alpine"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这个 Compose 文件中定义了两个服务 web 与 redis。此 Web 服务:

  • 使用当前目录 Dockerfile 构建出来的镜像
  • 将容器上暴露的5000端口转发到主机的5000端口。我们使用 Flask Web 服务器的默认端口 5000。

而 Redis 服务使用从 Docker Hub 注册表中拉取的公有镜像。

第四步:在 Compose 中构建并运行你的应用

  1. 在你的项目路径下通过 docker-compose up 命令启动你的应用。

    $ 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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

Compose 拉取一个 Redis 镜像,以你自己的代码构建一个镜像,并启动你定义的服务。在这种情况下,代码在构建时静态拷贝到镜像中。

  1. 在浏览器中输入 http://0.0.0.0:5000 查看应用的运行情况。

    你将在你的浏览器中看到如下信息:

    Hello World! I have been seen 1 times.
    • 1
  2. 刷新一下浏览器,数值将会增加。

    Hello World! I have been seen 2 times.
    • 1
  3. 切换到另外一个容器,输入 docker image ls 列举所有本地镜像。

    镜像列表中将返回 reidis 与 web。

    $ docker image ls
    REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
    composetest_web         latest              e2c21aa48cc1        4 minutes ago       93.8MB
    python                  3.4-alpine          84e6077c7ab6        7 days ago          82.5MB
    redis                   alpine              9d8fa9aa0e5b        3 weeks ago         27.5MB
    • 1
    • 2
    • 3
    • 4
    • 5

    你也可以通过 docker inspect <tag or id> 来检查镜像。

  4. 停止镜像,即可以在你的项目路径下使用 docker-compose down ,也可以在原始的终端上使用 CTRL+C 停止当前启动着的应用。

第五步:编辑 Compose 文件添加一个绑定挂载

在你的项目路径下编辑 docker-compose.yml 为 web 服务添加一个绑定挂载:

version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: "redis:alpine"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

这个新的 volumes 键将当前路径(项目路径)与容器中的 /code 路径挂载到一起,允许你及时修改代码而不用重新构建镜像。

第六步:重新构建并在 Compose 中运行应用

在你的项目路径下,输入 docker-compose up 命令使用更新后的 Compose 文件构建应用并启动。

$ 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)
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

再次检查 Web 浏览器中的 Hello World 消息,然后刷新以查看计数增量。

第七步:更新应用程序

因为应用程序的代码通过 volume 挂载到容器中,你可以更改其代码并立即查看更改,而不必重新生成镜像。

  1. 修改 app.py 中的欢迎语并保存。例如,将 Hello World! 改成 Hello from Docker!:

    return 'Hello from Docker! I have been seen {} times.\n'.format(count)
    • 1
  2. 刷新你的浏览器。欢迎语已经更新,而计数器仍然在增长。

第八步:尝试一些其它命令

​如果你希望你的应用程序在后台运行,你可以将 -d 标记传递给 docker-compose up 并使用 docker-compose ps 来查看当前运行的应用。

$ docker-compose up -d
Starting composetest_redis_1...
Starting composetest_web_1...

$ docker-compose ps
Name                 Command            State       Ports
-------------------------------------------------------------------
composetest_redis_1   /usr/local/bin/run         Up
composetest_web_1     /bin/sh -c python app.py   Up      5000->5000/tcp
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

docker-compose run 命令允许你为你的应用程序运行一次性命令。例如,查看哪些环境变量可以用于 web 服务:

$ docker-compose run web env
  • 1

通过 docker-compose --help 查看所有可用的命令。

如果你使用 docker-compose up -d 启动了 Compose,你可能希望在它们运行完成后停止服务:

$ docker-compose stop
  • 1

你可以停掉所有一切,使用 down 命令完全移除容器。传递 —volumes 还可以删除 Redis 容器中所使用的数据卷。

$ docker-compose down --volumes
  • 1

这时,你已经看到了 Compose 工作的基础知识。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多