Docker-Compose的使用
简介
Docker Compose 是一个用于定义和运行多容器的 Docker 应用程序的工具。它允许开发人员通过简单的 YAML 文件来定义应用程序的服务、网络和卷等资源,并使用单个命令来启动、停止和管理整个应用程序的容器。
安装
下载地址:https://github.com/docker/compose/releases/

下载完修改文件名为docker-compose,赋予可执行权限,放到 /usr/local/bin 目录下

能显示版本信息则安装成功
常用命令

下面以一个实例来演示如何使用 docker-compose:
- 创建一个项目目录
mkdir test
cd test
创建一个 app.py 文件
touch 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)
创建 requirements.txt 文件:
touch requirements.txt
flask
redis
创建 Dockerfile:
FROM python:latest
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories && apk add -U tzdata && ln -snf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime && echo "${TIMEZONE}" > /etc/timezone
RUN apk add -U tzdata && ln -snf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime && echo "${TIMEZONE}" > /etc/timezone
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镜像开始构建镜像(需提前下载)
-
将工作目录设置为/code
-
设置flask命令使用的环境变量
-
修改源为了快速下载 -安装gcc,以便诸如MarkupSafe和SQLAlchemy之类的Python包可以编译加速
-
复制requirements.txt并安装Python依赖项
-
将.项目中的当前目录复制到.映像中的工作目录
-
将容器的默认命令设置为flask run
创建 docker-compose.yml 文件:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:latest"
在项目目录中,运行启动应用程序
docker-compose up


完成以后可以通过浏览器确认结果
打开浏览器输入: http://ip:5000/

通过在启动该应用的原始终端中按CTRL + C或执行docker-compose down停止该应用
查看日志:docker-compose logs

这样我们通过docker-compose.yml文件来定义一组相关联的应用容器为一个项目(project),可以轻松启动和停止整个项目程序,如docker-compose up和docker-compose down

浙公网安备 33010602011771号