Compose是一個用于定義和運行多容器Docker應用程序的工具。使用Compose,您可以使用YAML文件來配置應用程序的服務。然后,只需一個命令,就可以從配置中創建并啟動所有服務。
Install Docker Compose
- 下載docker compose
$ sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
- 給docker compose設置可執行權限
$ sudo chmod +x /usr/local/bin/docker-compose
- 驗證
$ docker-compose --version
Uninstallation
$ sudo rm /usr/local/bin/docker-compose
Getting Started
用Python構建一個簡易網頁統計網頁點擊量,docker-compose進行發布
Step1:創建項目
- 創建項目目錄
- $ mkdir test_web
$ cd test_web - 在項目目錄中創建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文件,以下內容復制進去
flask
redis
Step2:創建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"]
Step3:在docker-compose.yml中定義services
version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
Step4:用Docker compose構建和運行app
- 進入項目目錄,運行docker-compose up
- $ docker-compose up
- 在瀏覽器訪問http://localhost:5000/ ,刷新頁面看變化
- 查看使用compose構建的鏡像
- $ docker images
Step5:綁定一個數據卷
version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
environment:
FLASK_ENV: development
redis:
image: "redis:alpine"
將當前目錄與容器的/code目錄綁定,這樣可以動態修改代碼
Step6:重新構建和運行app
先docker-compose down停止服務,在構建
$ docker-compose down
$ docker-compose up
Compose file
用YAML文件定義服務,默認文件是docker-compose.yml,包含4個頂級key,version、services、networks、volumes
參考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub
version
指定本 yml 依從的 compose版本
services
定義多個應用服務,包含環境配置、鏡像構建等
build
指定構建鏡像的路徑
version: "3.9"
services:
webapp:
build: ./app
blkio_config
定義服務的block IO配置,參考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub
container_name
指定自定義容器名稱
depends_on
定義服務間啟動或關閉的依賴關系
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
command
覆蓋容器啟動的默認命令
command: [ "bundle", "exec", "thin", "-p", "3000" ]
domainname
domainname declares a custom domain name to use for the service container.
entrypoint
覆蓋容器默認的entrypoint
env_file
從文件中添加環境變量到容器,可以是一個或多個文件
env_file: .env
env_file:
- ./a.env
- ./b.env
文件格式:
# Set Rails/Rack environment
RACK_ENV=development
VAR="quoted"
environment
添加環境變量
environment:
RACK_ENV: development
SHOW: "true"
USER_INPUT:
expose
暴露端口,但不映射到宿主機,只被連接的服務訪問,僅可以指定內部端口
expose:
- "3000"
- "8000"
healthcheck
用于檢測 docker 服務是否健康運行。
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"] # 設置檢測程序
interval: 1m30s # 設置檢測間隔
timeout: 10s # 設置檢測超時時間
retries: 3 # 設置重試次數
start_period: 40s # 啟動后,多少秒開始啟動檢測程序
image
指定容器運行的鏡像
image: redis:5
labels
設置容器標簽
labels:
com.example.description: "Accounting webapp"
com.example.department: "Finance"
labels:
- "com.example.description=Accounting webapp"
- "com.example.department=Finance"
links
連接到另一個容器的網絡,簡單將就是讓容器相互連通
web:
links:
- db
- db:database
- redis
logging
服務的日志記錄配置,driver:指定服務容器的日志記錄驅動程序,默認值為json-file。有以下三個選項
driver: "json-file"
driver: "syslog"
driver: "none"
僅在 json-file 驅動程序下,可以使用以下參數,限制日志得數量和大小。
logging:
driver: json-file
options:
max-size: "200k" # 單個文件大小為200k
max-file: "10" # 最多10個文件
syslog 驅動程序下,可以使用 syslog-address 指定日志接收地址。
logging:
driver: syslog
options:
syslog-address: "tcp://192.168.0.42:123"
network_mode
設置網絡模式,格式如下:
network_mode: "bridge" #橋接模式
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
networks
配置容器連接的網絡
services:
some-service:
networks:
- some-network
- other-network
networks:
some-network:
# Use a custom driver
driver: custom-driver-1
other-network:
# Use a custom driver which takes special options
driver: custom-driver-2
services:
frontend:
image: awesome/webapp
networks:
- front-tier
- back-tier
monitoring:
image: awesome/monitoring
networks:
- admin
backend:
image: awesome/backend
networks:
back-tier:
aliases:
- database
admin:
aliases:
- MySQL
networks:
front-tier:
back-tier:
admin:
ipv4_address, ipv6_address
指定ip地址
services:
frontend:
image: awesome/webapp
networks:
front-tier:
ipv4_address: 172.16.238.10
ipv6_address: 2001:3984:3989::10
networks:
front-tier:
ipam:
driver: default
config:
- subnet: "172.16.238.0/24"
- subnet: "2001:3984:3989::/64"
ports
端口映射,映射主機與容器端口,格式:Host:ontainer
ports:
- "5000:5000"
restart
容器重啟策略
restart: "no"
restart: always
restart: on-failure
restart: unless-stopped
secrets
存儲敏感數據,比如密碼
services:
frontend:
image: awesome/webapp
secrets:
- server-certificate
secrets:
server-certificate:
file: ./server.cert
volumes
將主機數據卷掛載到容器
services:
db:
image: postgres:latest
volumes:
- "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
- "/localhost/data:/var/lib/postgresql/data"
working_dir
覆蓋容器工作目錄
Volumes 頂級目錄
services:
backend:
image: awesome/database
volumes:
- db-data:/etc/data
backup:
image: backup-service
volumes:
- db-data:/var/lib/backup/data
volumes:
db-data:
Networks 頂級目錄
services:
frontend:
image: awesome/webapp
networks:
- front-tier
- back-tier
networks:
front-tier:
back-tier:
driver: bridge
docker-compose 命令
$ docker-compose --help
Define and run multi-container applications with Docker.
Usage:
docker-compose [-f <arg>...] [--profile <name>...] [options] [COMMAND] [ARGS...]
docker-compose -h|--help
Options:
-f, --file FILE Specify an alternate compose file
(default: docker-compose.yml)
-p, --project-name NAME Specify an alternate project name
(default: directory name)
--profile NAME Specify a profile to enable
--verbose Show more output
--log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
--no-ansi Do not print ANSI control characters
-v, --version Print version and exit
-H, --host HOST Daemon socket to connect to
--tls Use TLS; implied by --tlsverify
--tlscacert CA_PATH Trust certs signed only by this CA
--tlscert CLIENT_CERT_PATH Path to TLS certificate file
--tlskey TLS_KEY_PATH Path to TLS key file
--tlsverify Use TLS and verify the remote
--skip-hostname-check Don't check the daemon's hostname against the
name specified in the client certificate
--project-directory PATH Specify an alternate working directory
(default: the path of the Compose file)
--compatibility If set, Compose will attempt to convert deploy
keys in v3 files to their non-Swarm equivalent
Commands:
build Build or rebuild services
bundle Generate a Docker bundle from the Compose file
config Validate and view the Compose file
create Create services
down Stop and remove containers, networks, images, and volumes
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker-Compose version information