docker-compose学习笔记

docker-compose简介

Docker Compose是一个用来定义和运行复杂应用的Docker工具。一个使用Docker容器的应用,通常由多个容器组成。使用Docker Compose不再需要使用shell脚本来启动容器。 
Compose 通过一个配置文件来管理多个Docker容器,在配置文件中,所有的容器通过services来定义,然后使用docker-compose脚本来启动,停止和重启应用,和应用中的服务以及所有依赖服务的容器,非常适合组合使用多个容器进行开发的场景。

我们平时操作 docker 还是很原始的一系列动作,你手动使用 docker 的动作可以拆分成

  1. 找到一个系统镜像 // docker search
  2. 安装好 vm 或者 virtual box // apt-get install docker
  3. 在 vm 中安装镜像 // docker run -d -it 你的镜像
  4. 略..

这是最小的动作, 如果你要映射硬盘,设置nat网络或者桥接网络,等等…你就要做更多的 docker 操作, 这显然是非常没有效率的。但是我们写在 docker-compose.file 里面就很好了。 你只需要写好后 只运行一句
docker-compose up -d

安装docker-compose

两种最新的docker安装方式

1.从daocloud上下载docker-compose二进制文件安装

  • 下载最新版的docker-compose文件 ,国内daocloud下载

curl -L https://get.daocloud.io/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` > ~/docker-compose
  • 添加可执行权限 
     

    root@localhost:~# sudo mv ~/docker-compose /usr/local/bin/docker-compose
    root@localhost:~# 
    root@localhost:~# 
    root@localhost:~# chmod +x /usr/local/bin/docker-compose
  • 测试安装结果 

root@localhost:~# docker-compose --version
docker-compose version 1.16.1, build 6d1ac21

2.pip安装

$ sudo pip install docker-compose

官方docker-compose Python Web应用实例实践:

getting started

扫描二维码关注公众号,回复: 2379655 查看本文章

1、设置,准备工作

(1)新建目录

$ mkdir composetest
$ cd composetest

(2)在目录中编写Python代码文件app.py,功能为使用Flask框架并在Redis中维护一个点击访问量计数器

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)

(3)在当前工程目录中新建requirements.txt,添加如下内容:

flask
redis

2、新建Dockerfile文件

在工程目录新建Dockerfile文件,添加如下内容:

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

docker将根据Dockerfile文件做如下操作:

- 构建新的Python3.4镜像环境

- 将当前目录挂载到镜像中的/code目录

- 设置工作目录为/code

- 安装Python所需依赖

- 设置容器启动执行默认命令:python app.py 

3、在yml文件中定义所需服务

在工程目录中新建docker-compose.yml文件,添加如下内容:

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

yml文件定义了两个服务,web和redis

web服务:

使用Dockerfile文件构建的镜像,将容器上暴露的端口5000转发到主机上的端口5000,使用Flask web服务器的默认端口5000。

redis服务:

使用从Docker Hub上拉取的Redis镜像。

4、通过Compose构建并运行Python web应用

(1)通过docker-compose up命令运行应用。

root@localhost:/usr/local/composetest# docker-compose up
Creating network "composetest_default" with the default driver
Building web
Step 1/5 : FROM python:3.4-alpine
3.4-alpine: Pulling from library/python
911c6d0c7995: Pull complete
01a7b783f4b1: Pull complete
2dc3208e79ca: Pull complete
699baba2f517: Pull complete
98acbb2a4062: Pull complete
Digest: sha256:98919cda20362518974e9a1f9259ef6a1cecff40f6379206c9e9c0575deb0866
Status: Downloaded newer image for python:3.4-alpine
 ---> 44fb4546354b
Step 2/5 : ADD . /code
 ---> 2d403b09d670
Step 3/5 : WORKDIR /code
Removing intermediate container e55760d6b246
 ---> d191b936fa9d
Step 4/5 : RUN pip install -r requirements.txt
 ---> Running in eba6ca29d93f
Collecting flask (from -r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/7f/e7/08578774ed4536d3242b14dacb4696386634607af824ea997202cd0edb4b/Flask-1.0.2-py2.py3-none-any.whl (91kB)
Collecting redis (from -r requirements.txt (line 2))
  Downloading https://files.pythonhosted.org/packages/3b/f6/7a76333cf0b9251ecf49efff635015171843d9b977e4ffcf59f9c4428052/redis-2.10.6-py2.py3-none-any.whl (64kB)
Collecting click>=5.1 (from flask->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/34/c1/8806f99713ddb993c5366c362b2f908f18269f8d792aff1abfd700775a77/click-6.7-py2.py3-none-any.whl (71kB)
Collecting Werkzeug>=0.14 (from flask->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/20/c4/12e3e56473e52375aa29c4764e70d1b8f3efa6682bef8d0aae04fe335243/Werkzeug-0.14.1-py2.py3-none-any.whl (322kB)
Collecting Jinja2>=2.10 (from flask->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/7f/ff/ae64bacdfc95f27a016a7bed8e8686763ba4d277a78ca76f32659220a731/Jinja2-2.10-py2.py3-none-any.whl (126kB)
Collecting itsdangerous>=0.24 (from flask->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/dc/b4/a60bcdba945c00f6d608d8975131ab3f25b22f2bcfe1dab221165194b2d4/itsdangerous-0.24.tar.gz (46kB)
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10->flask->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/4d/de/32d741db316d8fdb7680822dd37001ef7a448255de9699ab4bfcbdf4172b/MarkupSafe-1.0.tar.gz
Building wheels for collected packages: itsdangerous, MarkupSafe
  Running setup.py bdist_wheel for itsdangerous: started
  Running setup.py bdist_wheel for itsdangerous: finished with status 'done'
  Stored in directory: /root/.cache/pip/wheels/2c/4a/61/5599631c1554768c6290b08c02c72d7317910374ca602ff1e5
  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/33/56/20/ebe49a5c612fffe1c5a632146b16596f9e64676768661e4e46
Successfully built itsdangerous MarkupSafe
Installing collected packages: click, Werkzeug, MarkupSafe, Jinja2, itsdangerous, flask, redis
Successfully installed Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7 flask-1.0.2 itsdangerous-0.24 redis-2.10.6
Removing intermediate container eba6ca29d93f
 ---> 9c182096aa31
Step 5/5 : CMD ["python", "app.py"]
 ---> Running in 01c4b9c48666
Removing intermediate container 01c4b9c48666
 ---> d3bfbda33266
Successfully built d3bfbda33266
Successfully tagged composetest_web:latest
WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
8e3ba11ec2a2: Pull complete
1f20bd2a5c23: Pull complete
782ff7702b5c: Pull complete
cd719ead7ee3: Pull complete
01018940af9a: Pull complete
3f1bfdda9588: Pull complete
Digest: sha256:e57274dac037e5b0c7680717fcaaa0efeffb23430e54e839c50819c9d842a38c
Status: Downloaded newer image for redis:alpine
Creating composetest_web_1 ... 
Creating composetest_redis_1 ... 
Creating composetest_redis_1
Creating composetest_web_1 ... done
Attaching to composetest_redis_1, composetest_web_1
redis_1  | 1:C 17 Jul 07:15:40.305 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 17 Jul 07:15:40.305 # Redis version=4.0.10, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 17 Jul 07:15:40.305 # 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 17 Jul 07:15:40.371 * Running mode=standalone, port=6379.
redis_1  | 1:M 17 Jul 07:15:40.371 # 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 17 Jul 07:15:40.371 # Server initialized
redis_1  | 1:M 17 Jul 07:15:40.371 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 17 Jul 07:15:40.379 # 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 17 Jul 07:15:40.379 * Ready to accept connections
web_1    |  * Serving Flask app "app" (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: Do not use the development server in a production environment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: on
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: 312-557-248

(2)在浏览器中输入http://0.0.0.0:5000访问Python应用

注意这里IP地址应该改成宿主机的IP地址,访问之后web页面显示如下,每刷新一次,次数自动增加一次。

Hello World! I have been seen 2 times.

(3)在另一个命令终端,docker images查看本地镜像

root@localhost:/usr/local/composetest# docker images
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
composetest_web       latest              d3bfbda33266        About an hour ago   78.3MB
my/javaweb            v1                  61ad89d0b68e        5 hours ago         609MB
wuts/ubuntu_javaweb   latest              5f333d720370        6 hours ago         609MB
python                3.4-alpine          44fb4546354b        7 hours ago         67MB
redis                 alpine              80581db8c700        6 days ago          28.6MB
tomcat                latest              2d084b11164d        13 days ago         463MB
ubuntu                14.04               578c3e61a98c        5 weeks ago         223MB

可以看到本测试例子中docker-compose所新建的composetest_web、redis和Python镜像。

(4)通过第二终端,输入命令docker-compose down关闭应用服务。

root@localhost:/usr/local/composetest# docker-compose down
Stopping composetest_web_1   ... done
Stopping composetest_redis_1 ... done
Removing composetest_web_1   ... done
Removing composetest_redis_1 ... done
Removing network composetest_default

5、修改compse文件,添加绑定挂载

修改 docker-compose.yml文件

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

volumes 将项目目录(当前目录)挂载到容器内的/code上,允许动态修改代码,而不需要重新构建映像。

6、重新构建并运行应用

root@localhost:/usr/local/composetest# docker-compose up
Creating network "composetest_default" with the default driver
Creating composetest_redis_1 ... 
Creating composetest_redis_1
Creating composetest_web_1 ... 
Creating composetest_web_1 ... done
Attaching to composetest_redis_1, composetest_web_1
redis_1  | 1:C 17 Jul 08:20:38.786 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 17 Jul 08:20:38.786 # Redis version=4.0.10, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 17 Jul 08:20:38.786 # 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 17 Jul 08:20:38.818 * Running mode=standalone, port=6379.
redis_1  | 1:M 17 Jul 08:20:38.818 # 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 17 Jul 08:20:38.818 # Server initialized
redis_1  | 1:M 17 Jul 08:20:38.818 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 17 Jul 08:20:38.818 # 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 17 Jul 08:20:38.818 * Ready to accept connections
web_1    |  * Serving Flask app "app" (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: Do not use the development server in a production environment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: on
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: 323-733-644
web_1    | 192.168.199.11 - - [17/Jul/2018 08:20:47] "GET / HTTP/1.1" 200 -

7、更新应用

由于添加了volumes,可以更新代码而不用重新构建镜像

修改app.py,return内容改成 Hi,welcome!.....

compose日志:

web_1    |  * Detected change in '/code/app.py', reloading
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 323-733-644

刷新浏览器,显示修改后的提示内容

Hi,Welcome! You have been seen 2 times.

8、其他命令

docker-compose up -d

在后台运行compose

如果通过后台运行应用,停止运行命令如下:

docker-compose stop

如果想删除compose中所有容器,运行命令如下

docker-compose down --volumes

猜你喜欢

转载自blog.csdn.net/qq_40012404/article/details/81078288
今日推荐