Docker的那些事儿Docker compose

Docker的那些事儿—一个例子教你docker compose

2018-03-09  本文已影响55人  sjyu_eadd

上一篇:Docker的那些事儿—如何安装docker-compose?


安装了Compose,下面就来通过一个例子认识Docker Compose是如何使用的?

目标:通过Docker Compose构建一个简单的Python Web应用程序,并且借助redis实现简单的计数功能。

Step 1:定义应用的依赖关系

1、创建项目目录:mycompose

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


3、在项目目录下创建requirements.txt文件,内容如下:


flask

redis


Step 2:创建Dockerfile文件

在项目目录下创建名字为Dockerfile文件,内容如下:


FROM python:3.4-alpine

ADD . /code

WORKDIR /code

RUN pip install -r requirements.txt

CMD ["python", "app.py"]


Step 3:定义Compose文件

在项目目录下创建名字为docker-compose.yml文件,内容如下:


version: '3'

services:

  web:

    build: .

    ports:

     -"5000:5000"

  redis:

    image:"redis:alpine"


上述Compose文件定义了两个服务:web服务和redis服务。其中redis服务使用的是Docker Hub上的镜像;web服务使用的是上述Dockerfile构建的镜像,并且做了端口的映射。

Step 4:使用Compose构建并运行应用

在项目目录下,执行docker-compose up启动应用


root@Ubuntu-001:~/mycompose#docker-compose up

Creating network"mycompose_default" with the default driver

Building web

Step 1/5 : FROM python:3.4-alpine

3.4-alpine: Pulling fromlibrary/python

81033e7c1d6a: Pull complete

9b61101706a6: Pull complete

415e2a07c89b: Pull complete

f22df7a3f000: Pull complete

8c16bf19c1f9: Pull complete

Digest:sha256:fe436cb066394d81cf49448a04dec7c765082445a500bc44f1ae5e8a455793bd

Status: Downloaded newerimage for python:3.4-alpine

 ---> 5c72717ec319

Step 2/5 : ADD . /code

 ---> 7b20a034f7a4

Step 3/5 : WORKDIR /code

Removing intermediatecontainer c837500a2226

 ---> d77fc02cacc1

Step 4/5 : RUN pip install -rrequirements.txt

 ---> Running in 59d8d8c0ecf6

Collecting flask (from -rrequirements.txt (line 1))

  Downloading Flask-0.12.2-py2.py3-none-any.whl(83kB)

Collecting redis (from -rrequirements.txt (line 2))

  Downloading redis-2.10.6-py2.py3-none-any.whl(64kB)

Collecting Werkzeug>=0.7(from flask->-r requirements.txt (line 1))

  DownloadingWerkzeug-0.14.1-py2.py3-none-any.whl (322kB)

Collecting click>=2.0(from flask->-r requirements.txt (line 1))

  Downloading click-6.7-py2.py3-none-any.whl(71kB)

Collecting Jinja2>=2.4(from flask->-r requirements.txt (line 1))

  Downloading Jinja2-2.10-py2.py3-none-any.whl(126kB)

Collectingitsdangerous>=0.21 (from flask->-r requirements.txt (line 1))

  Downloading itsdangerous-0.24.tar.gz (46kB)

CollectingMarkupSafe>=0.23 (from Jinja2>=2.4->flask->-r requirements.txt(line 1))

  Downloading MarkupSafe-1.0.tar.gz

Building wheels for collectedpackages: itsdangerous, MarkupSafe

  Running setup.py bdist_wheel for itsdangerous:started

  Running setup.py bdist_wheel foritsdangerous: finished with status 'done'

  Stored in directory:/root/.cache/pip/wheels/fc/a8/66/24d655233c757e178d45dea2de22a04c6d92766abfb741129a

  Running setup.py bdist_wheel for MarkupSafe:started

  Running setup.py bdist_wheel for MarkupSafe:finished with status 'done'

  Stored in directory:/root/.cache/pip/wheels/88/a7/30/e39a54a87bcbe25308fa3ca64e8ddc75d9b3e5afa21ee32d57

Successfully builtitsdangerous MarkupSafe

Installing collectedpackages: Werkzeug, click, MarkupSafe, Jinja2, itsdangerous, flask, redis

Successfully installedJinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7 flask-0.12.2itsdangerous-0.24 redis-2.10.6

Removing intermediatecontainer 59d8d8c0ecf6

 ---> 51143f11c451

Step 5/5 : CMD["python", "app.py"]

 ---> Running in 422960a19b01

Removing intermediatecontainer 422960a19b01

 ---> de5cc3ead62d

Successfully builtde5cc3ead62d

Successfully taggedmycompose_web:latest

WARNING: Image for serviceweb was built because it did not already exist. To rebuild this image you mustuse `docker-compose build` or `docker-compose up --build`.

Pulling redis(redis:alpine)...

alpine: Pulling fromlibrary/redis

ff3a5c916c92: Pull complete

aae70a2e6027: Pull complete

87c655da471c: Pull complete

a0bd51ac7350: Pull complete

755565c3ea2b: Pull complete

8bf100ea488d: Pull complete

Digest:sha256:4f54ade2260d5c80283d044ab9657f390cb8effd9a7a847765693a3670f6874a

Status: Downloaded newerimage for redis:alpine

Creating mycompose_web_1   ... done

Creating mycompose_redis_1... done

Attaching tomycompose_redis_1, mycompose_web_1

redis_1  | 1:C 08 Mar 14:41:49.790 # oO0OoO0OoO0OoRedis is starting oO0OoO0OoO0Oo

redis_1  | 1:C 08 Mar 14:41:49.790 # Redisversion=4.0.8, bits=64, commit=00000000, modified=0, pid=1, just started

redis_1  | 1:C 08 Mar 14:41:49.790 # Warning: noconfig file specified, using the default config. In order to specify a configfile use redis-server /path/to/redis.conf

redis_1  | 1:M 08 Mar 14:41:49.798 * Runningmode=standalone, port=6379.

redis_1  | 1:M 08 Mar 14:41:49.798 # WARNING: The TCPbacklog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconnis set to the lower value of 128.

redis_1  | 1:M 08 Mar 14:41:49.798 # Serverinitialized

redis_1  | 1:M 08 Mar 14:41:49.798 # WARNINGovercommit_memory is set to 0! Background save may fail under low memorycondition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.confand then reboot or run the command 'sysctl vm.overcommit_memory=1' for this totake effect.

redis_1  | 1:M 08 Mar 14:41:49.798 # WARNING you haveTransparent Huge Pages (THP) support enabled in your kernel. This will create latencyand memory usage issues with Redis. To fix this issue run the command 'echonever > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it toyour /etc/rc.local in order to retain the setting after a reboot. Redis must berestarted after THP is disabled.

redis_1  | 1:M 08 Mar 14:41:49.799 * DB loaded fromdisk: 0.000 seconds

redis_1  | 1:M 08 Mar 14:41:49.799 * Ready to acceptconnections

web_1    |  *Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

web_1    |  *Restarting with stat

web_1    |  *Debugger is active!

web_1    |  *Debugger PIN: 246-553-608


从docker-compose up的过程可以总结如下:

1、构建mycompose_default网络,该网络供下面容器启动使用

2、基于Dockerfile构建mycompose_web:latest镜像

3、从Docker Hub pull redis:alpine镜像

4、分别启动mycompose_web_1和mycompose_redis_1容器

5、Attach到mycompose_web_1和mycompose_redis_1容器

注意:这里无论创建的网络、镜像还是容器,其前缀名都是基于项目名的

打开新的终端窗口,查询运行的容器

打开浏览器键入http://192.168.1.106:5000,其中192.168.1.106是Ubuntu-001主机的IP

刷新页面后

可以看到收到两条get请求,浏览器每刷新一次,发送一条get请求

其中192.168.1.101是我的本地电脑的IP

打开新的终端,查询镜像

在原来的终端窗口按CTRL+C或者在新的终端窗口使用docker-compose down停止应用


下一篇:Docker的那些事儿—一个例子教你docker compose是如何使用的(二)?


上一篇下一篇

猜你喜欢

热点阅读