docker compose
批处理
默认名称 docker-compose.yml
推荐使用Version3版本
图为docker-compose于docker版本配对
https://docs.docker.com/compose/compose-file/
V2和V3的区别:V2单机,V3多机
Service
一个service代表一个container,container可以从dockerhub的image创建,也可以从本地Dockerfile build出来的image创建
Service启动类似docker run,我们可以给其指定network和volume
- dockerhub的image创建
services: db: #名称 image: postgres:9.4 #镜像 volumes: - "db-data:/var/lib/postgresql/data" network: - back-tier
docker run -d --network back-tier -v db-data:/var/lib/postgresql/data postgres:9.4
docker volume create db-data
- 本地Dockerfile build出来的image创建
services: worker: build: ./worker # 本地构建dockfiles路径 links: - db - redis network: - back-tier # 如果使用自定义网络,其实不需要links
源码示例:
version: ‘3‘ services: wordpress: image: wordpress ports: - 8080:80 enviroment: WORDPRESS_DB_HOST: mysql WORDPRESS_DB_PASSWORD: root networks: - my-bridge mysql: image: mysql enviroment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: wordpress volumes: - mysql-data:/var/lib/mysql networks: - my-bridge volumes: mysql-data: networks: mybridge: driver: bridge
docker compose 使用
docker-compose --version
linux用户需要单独安装docker-compose
`
sudo curl -L "https://github.com/docker/compose/releases/download/1.25.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
`
指定要启动的yml文件
docker-compose -f docker-compose.yml up
不打印log后台启动
docker-compose up -d
查看compose状态:
docker-compose ps
停止启动compose:
docker-compose stop/start
删除compose,image保留:
docker-compose down
查看compose 镜像:
docker-compose images
进入mysql容器命令行:
docker-compose exec mysql bash
docker-compose exec wordpress bash
docker-compose实例
version: "3" services: redis: redis web: build: context: dockerfile: Dockerfile # 使用dockerfile去build ports: - 8080:5000 enviroment: REDIS_HOST: redis
scale 扩展服务数量
yml文件中绑定本地端口不能有,删除port
docker-compose up --scale web=3 -d
配合scale添加负载均衡
docker-compose.yml实例
version: "3" services: redis: image: redis web: build: context: dockerfile: Dockerfile # 使用dockerfile去build enviroment: REDIS_HOST: redis lb: image: dockercloud/haproxy links: - web ports: - 8080:80 volumes: - /var/run/docker.sock:/var/run/docker.sock app.py from flask import Flask from redis import Redis import os import socket app = Flask(__name__) redis = Redis(host=os.environ.get(‘REDIS_HOST‘, ‘127.0.0.1‘), port=6379) @app.reoute(‘/‘) def hello(): redis.incr(‘hits‘) return ‘Hello container world!‘ if __name__ == "__main__": app.run(host="0.0.0.0", port=80, debug=True)
Dockerfile
FROM pyton:2.7 LABEL maintaner="wyx" COPY . /app WORKDIR /app RUN pip install flask redis EXPOSE 80 CMD ["python", "app.py"]
docker-compose up -
docker-compose up --scale web=3 -d