Docker-Compose入门

匿名 (未验证) 提交于 2019-12-02 22:56:40

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

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

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

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

先决条件

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

  1. 为项目创建目录

     $ mkdir composetest $ cd composetest
  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)

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

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

     flask redis

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

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

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

这会告诉容器:

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

Docker user guideDockerfile reference

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

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

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

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

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

  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

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

  1. http://0.0.0.0:5000

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

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

     Hello World! I have been seen 2 times.
  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

    docker inspect <tag or id>

  4. docker-compose down

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

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

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

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) ...

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

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

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

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

-ddocker-compose updocker-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

docker-compose run

 $ docker-compose run web env

docker-compose --help

docker-compose up -d

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

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

文章来源: Docker-Compose入门
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!