我们之前的Docker流程是这样的
DockerFile–>build–>run 都是手动操作,单个容器!
思考:如果我们有100个、1000个微服务,我们也要一个个的手动操作嘛?
结果:为了解决这样的问题,我们引入一个Docker Compose 来轻松高效的管理容器—>定义运行多个容器
官方文档说明
Docker Compose is a tool that was developed to help define and running multi-container applications. With Compose, we can create a YAML file to define the services and with a single command, can spin everything up or tear it all down.
三步骤:
1.Dockerfile保证我们的项目在任何地方可以运行
2.如何写docker-compose.yml
3.启动项目 docker-compose up
Compose是Docker官方的开源项目,需要安装!
Dockerfile
让程序在任何地方运行。
Compose:重要的概念
作用
批量容器编排
下载
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
授权
sudo chmod +x /usr/local/bin/docker-compose
官方地址:https://docs.docker.com/compose/gettingstarted/
1.Create a directory for the project
mkdir composetest
cd composetest
2.Create a file called
app.py
in your project directory and paste this in:
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.Create another file called
requirements.txt
in your project directory and paste this in:
flask
redis
编写一个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文件
Define services in a Compose file
Create a file called
docker-compose.yml
in your project directory and paste the following:
version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
Build and run your app with Compose
From your project directory, start up your application by running
docker-compose up
1.应用 app.py
2.Dockerfile 应用打包为镜像(单机)
3.Docker-compose.yml文件(定义整个服务,需要的环境。web、redis等)
4.启动compose 项目(docker-compose up
)