Docker从入门到精通之Docker Compose

202阅读模式

Compose是一个用于定义和运行多容器Docker应用程序的工具。使用Compose,您可以使用YAML文件来配置应用程序的服务。然后,只需一个命令,就可以从配置中创建并启动所有服务。文章源自懂站帝-http://www.sfdkj.com/12951.html

Install Docker Compose

  1. 下载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
  1. 给docker compose设置可执行权限
$ sudo chmod +x /usr/local/bin/docker-compose
  1. 验证
$ docker-compose --version

Uninstallation

$ sudo rm /usr/local/bin/docker-compose

Getting Started

用python构建一个简易网页统计网页点击量,docker-compose进行发布文章源自懂站帝-http://www.sfdkj.com/12951.html

Step1:创建项目文章源自懂站帝-http://www.sfdkj.com/12951.html

  1. 创建项目目录
  2. $ mkdir test_web $ cd test_web
  3. 在项目目录中创建app.py文件,并把下面代码复制进去
  4. 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)
  5. 创建requirements.txt文件,以下内容复制进去
flask
redis

Step2:创建Dockerfile文件文章源自懂站帝-http://www.sfdkj.com/12951.html

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文章源自懂站帝-http://www.sfdkj.com/12951.html

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

Step4:用Docker compose构建和运行app文章源自懂站帝-http://www.sfdkj.com/12951.html

  1. 进入项目目录,运行docker-compose up
  2. $ docker-compose up
  3. 在浏览器访问http://localhost:5000/ ,刷新页面看变化
  4. 查看使用compose构建的镜像
  5. $ docker images

Step5:绑定一个数据卷文章源自懂站帝-http://www.sfdkj.com/12951.html

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"

将当前目录与容器的/code目录绑定,这样可以动态修改代码文章源自懂站帝-http://www.sfdkj.com/12951.html

Step6:重新构建和运行app文章源自懂站帝-http://www.sfdkj.com/12951.html

先docker-compose down停止服务,在构建文章源自懂站帝-http://www.sfdkj.com/12951.html

$ docker-compose down
$ docker-compose up

Compose file

用YAML文件定义服务,默认文件是docker-compose.yml,包含4个顶级key,version、services、networks、volumes文章源自懂站帝-http://www.sfdkj.com/12951.html

参考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub文章源自懂站帝-http://www.sfdkj.com/12951.html

version

指定本 yml 依从的 compose版本文章源自懂站帝-http://www.sfdkj.com/12951.html

services

定义多个应用服务,包含环境配置、镜像构建等文章源自懂站帝-http://www.sfdkj.com/12951.html

build

指定构建镜像的路径文章源自懂站帝-http://www.sfdkj.com/12951.html

version: "3.9"
services:
  webapp:
    build: ./app

blkio_config

定义服务的block IO配置,参考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub文章源自懂站帝-http://www.sfdkj.com/12951.html

container_name

指定自定义容器名称文章源自懂站帝-http://www.sfdkj.com/12951.html

depends_on

定义服务间启动或关闭的依赖关系文章源自懂站帝-http://www.sfdkj.com/12951.html

services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

command

覆盖容器启动的默认命令文章源自懂站帝-http://www.sfdkj.com/12951.html

command: [ "bundle", "exec", "thin", "-p", "3000" ]

domainname

domainname declares a custom domain name to use for the service container.文章源自懂站帝-http://www.sfdkj.com/12951.html

entrypoint

覆盖容器默认的entrypoint文章源自懂站帝-http://www.sfdkj.com/12951.html

env_file

从文件中添加环境变量到容器,可以是一个或多个文件文章源自懂站帝-http://www.sfdkj.com/12951.html

env_file: .env
env_file:
  - ./a.env
  - ./b.env

文件格式:文章源自懂站帝-http://www.sfdkj.com/12951.html

# Set Rails/Rack environment
RACK_ENV=development
VAR="quoted"

environment

添加环境变量文章源自懂站帝-http://www.sfdkj.com/12951.html

environment:
  RACK_ENV: development
  SHOW: "true"
  USER_INPUT:

expose

暴露端口,但不映射到宿主机,只被连接的服务访问,仅可以指定内部端口文章源自懂站帝-http://www.sfdkj.com/12951.html

expose:
  - "3000"
  - "8000"

healthcheck

用于检测 docker 服务是否健康运行。文章源自懂站帝-http://www.sfdkj.com/12951.html

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"] # 设置检测程序
  interval: 1m30s  # 设置检测间隔
  timeout: 10s # 设置检测超时时间
  retries: 3 # 设置重试次数
  start_period: 40s # 启动后,多少秒开始启动检测程序

image

指定容器运行的镜像文章源自懂站帝-http://www.sfdkj.com/12951.html

image: redis:5

labels

设置容器标签文章源自懂站帝-http://www.sfdkj.com/12951.html

labels:
  com.example.description: "Accounting webapp"
  com.example.department: "Finance"
labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"

links

连接到另一个容器的网络,简单将就是让容器相互连通文章源自懂站帝-http://www.sfdkj.com/12951.html

web:
  links:
    - db
    - db:database
    - redis

logging

服务的日志记录配置,driver:指定服务容器的日志记录驱动程序,默认值为json-file。有以下三个选项文章源自懂站帝-http://www.sfdkj.com/12951.html

driver: "json-file"
driver: "syslog"
driver: "none"

仅在 json-file 驱动程序下,可以使用以下参数,限制日志得数量和大小。文章源自懂站帝-http://www.sfdkj.com/12951.html

logging:
  driver: json-file
  options:
    max-size: "200k" # 单个文件大小为200k
    max-file: "10" # 最多10个文件

syslog 驱动程序下,可以使用 syslog-address 指定日志接收地址。文章源自懂站帝-http://www.sfdkj.com/12951.html

logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"

network_mode

设置网络模式,格式如下:文章源自懂站帝-http://www.sfdkj.com/12951.html

network_mode: "bridge" #桥接模式
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"

networks

配置容器连接的网络文章源自懂站帝-http://www.sfdkj.com/12951.html

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地址文章源自懂站帝-http://www.sfdkj.com/12951.html

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文章源自懂站帝-http://www.sfdkj.com/12951.html

ports:
     - "5000:5000"

restart

容器重启策略文章源自懂站帝-http://www.sfdkj.com/12951.html

restart: "no"
restart: always
restart: on-failure
restart: unless-stopped

secrets

存储敏感数据,比如密码文章源自懂站帝-http://www.sfdkj.com/12951.html

services:
  frontend:
    image: awesome/webapp
    secrets:
      - server-certificate
secrets:
  server-certificate:
    file: ./server.cert

volumes

将主机数据卷挂载到容器文章源自懂站帝-http://www.sfdkj.com/12951.html

services:
  db:
    image: postgres:latest
    volumes:
      - "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
      - "/localhost/data:/var/lib/postgresql/data"

working_dir

覆盖容器工作目录文章源自懂站帝-http://www.sfdkj.com/12951.html

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

Swarm集群

文章源自懂站帝-http://www.sfdkj.com/12951.html
懂站帝
  • 本文由 发表于 2022年5月14日 12:24:30
  • 版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至395045033@qq.com举报,一经查实,本站将立刻删除。