Docker Compose

一、设置

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)

3.在当前路径下创建 requirements.txt 表示 py 需要依赖的依赖项:

flask
redis

二、创建 DockerFile 文件

1.创建 dockerfile

FROM python:3.7-alpine                               
WORKDIR /code                                        
ENV FLASK_APP app.py                                                                
ENV FLASK_RUN_HOST 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
COPY . .
CMD ["flask", "run"]
  • 引入 python 3.7 的依赖
  • 设置 /code 为工作目录
  • 设置 FLASK 命令使用的环境变量
  • 安装gcc,这样像MarkupSafe和SQLAlchemy这样的Python包就可以编译加速。
  • 复制requirements.txt并安装Python依赖项。
  • 复制当前目录到工作目录中
  • 启动命令

三、创建 Compose 文件

1. 创建 docker-compose.yml

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
  • version :设置版本
  • services :理解为 contains
  • web :理解为设置了一个 name = web 的 contain
  • build . :通过当前路径下的 dockerfile 进行构建
  • port :进行端口映射
  • redis :理解为设置了一个 name = web 的 contain
  • imger :指从镜像库拉取

四、构建和运行程序

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
  • docker-compose up :

    • -d :后台运行
    • -f : 指定 compose 文件
upCreate and start containers
versionShow the Docker-Compose version information
runRun a one-off command
rmRemove stopped containers
imagesList images
startStart services
stopStop services
logsView output from containers
createCreate services
buildBuild or rebuild services

2.访问 5050 端口,查看效果

image.png

3.docker image ls

$ 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

五、修改文件增加挂载

修改 compose 文件,给 web 服务增加挂载:

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"
  • volumes :将主机中的当前目录挂载到容器内的 /code 目录下

允许您动态修改代码,而不必重新构建映像

六、重新运行

$ 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.修改配置文件

return 'Hello from Docker! I have been seen {} times.\n'.format(count)

2.刷新页面查看效果

image.png

八、其余操作

1.如果你想在后台运行你的服务,你可以将-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

2.要查看哪些环境变量对web服务可用

$ docker-compose run web env

3.停止服务

$ docker-compose stop

4.删除

$ docker-compose down --volumes
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值