Compose是Docker的服务编排工具,主要用来构建基于Docker的复杂应用,是一个用于定义和运行多容器 Docker 的应用程序工具。
官方安装文档地址:https://docs.docker.com/compose/install/
1.安装docker-compose
# curl -L https://github.com/docker/compose/releases/download/1.25.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose #获取文件并下载到/usr/local/的目录下
# chmod +x /usr/local/bin/docker-compose #赋予docker-compose文件的执行权限
# ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose #创建一个软连接
# docker-compose --version #查看版本
docker-compose version 1.25.0, build 0a186604
2.用docker-compose构建和运行应用
# mkdir composetest
# cd composetest #必须切换到构建目录下
# vi 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)
# vi requirements.txt
flask
redis
# vi 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
RUN pip config set global.index-url http://mirrors.aliyun.com/pypi/simple
RUN pip config set install.trusted-host mirrors.aliyun.com
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]
# vi docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
# docker-compose up #运行来启动应用程序
# cd composetest/ #必须切换到构建目录下
# docker-compose ps #查看构建的容器
Name Command State Ports
-------------------------------------------------------------------------------------
composetest_redis_1 docker-entrypoint.sh redis ... Up 6379/tcp
composetest_web_1 flask run Up 0.0.0.0:5000->5000/tcp
3.打开浏览器输入IP:5000 ,查看是否运行应用程序
参考Docker官方学习文档的地址: https://docs.docker.com/compose/gettingstarted/