什么是 Docker Compose?
Docker Compose 是docker 官方的一个开源项目。Compose 是一个作用于 定义和运行多个docker容器的工具。通过 compose 工具,你可以使用一个 yaml 文件来配置你的应用服务。然后,只需要一个命令,就可以从配置中创建并启动所有服务。
作用: 多容器编排
文件名:docker-compose.yml
Compose 重要概念
- 服务service
容器、应用(web、redis、mysql...)
- 项目project
一组关联的容器(博客:web、mysql)
安装 Docker Compose | 官网安装
Docker Compose 存放在Git Hub,不太稳定。
你可以也通过执行下面的命令,高速安装Docker Compose。
curl -L https://get.daocloud.io/docker/compose/releases/download/1.27.4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
官方 快速体验 Docker compose
python 写一个 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)
- 定义 导入的 py 包
- 定义 web 项目 的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
EXPOSE 5000
COPY . .
CMD ["flask", "run"]
定义 Compose的配置文件 docker-compose.yml
version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
执行 docker-compose up 命令
流程分析
Creating network "composetest_default" with the default driver
Building web
Step 1/10 : FROM python:3.7-alpine
.....
.....
Step 10/10 : CMD ["flask", "run"]
---> Running in 8b865f31c3c4
Removing intermediate container 8b865f31c3c4
---> d167d462718e
Successfully built d167d462718e
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
.....
.....
Digest: sha256:2cd821f730b90a197816252972c2472e3d1fad3c42f052580bc958d3ad641f96
Status: Downloaded newer image for redis:alpine
Creating composetest_web_1 ... done
Creating composetest_redis_1 ... done
Attaching to composetest_web_1, composetest_redis_1
....
....
- 创建网络
- 执行 docker-compose.yml
- 启动服务
延伸遗留一个问题
[root@localhost ~]# docker service ls
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
默认的服务名: 项目名_服务名_num
多个服务器、集群
集群状态、 服务不可能只有一个集群实例
工程、服务、容器
- 工程:
- 服务:
- 容器:
网友评论