Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Docker Compose

Docker Compose

Introduction to Compose

Compose is a tool for defining and running multi-container Docker applications. With Compose, you can use a YML file to configure all the services your application needs. Then, with a single command, you can create and start all services from the YML file configuration.

If you are not yet familiar with YML file configuration, you can first read YAML Getting Started Tutorial。

Three steps for using Compose:

A sample docker-compose.yml configuration is as follows (see below for configuration parameters):

Example

yaml configuration example

version

:

'

3

'

services

:

  web

:

    build

:

.

    ports

:

   -

"5000:5000"

    volumes

:

   - .:/code

    - logvolume01:/var/log

    links

:

   - redis

  redis

:

    image

:

redis

volumes

:

  logvolume01

:

{

}


Compose installation

On Linux, we can download its binary package from GitHub to use it. The address of the latest release is:https://github.com/docker/compose/releases。

Run the following command to download the current stable version of Docker Compose:

$ sudo curl -L "https://github.com/docker/compose/releases/download/v2.2.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

To install another version of Compose, replace v2.2.2.

Docker Compose is hosted on GitHub, which is not very stable.

You can also install Docker Compose quickly by running the following command.

curl -L https://get.daocloud.io/docker/compose/releases/download/v2.4.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

Apply executable permissions to the binary file:

$ sudo chmod +x /usr/local/bin/docker-compose

Create a symbolic link:

$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

Test whether the installation was successful:

$ docker-compose version

cker-compose version 1.24.1, build 4667896b

Note: For Alpine, the following dependency packages are required: py-pip, python-dev, libffi-dev, openssl-dev, gcc, libc-dev, and make.

macOS

Docker Desktop for Mac and Docker Toolbox already include Compose and other Docker applications, so Mac users do not need to install Compose separately. For Docker installation instructions, see MacOS Docker installation。

windows PC

Docker Desktop for Windows and Docker Toolbox already include Compose and other Docker applications, so Windows users do not need to install Compose separately. For Docker installation instructions, seeWindows Docker installation。


Use

1. Preparation

Create a test directory:

$ mkdir composetest

$ cd composetest

In the test directory, create a file named app.py and copy and paste the following content:

composetest/app.py file code

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

)

In this example, redis is the hostname of the redis container on the application network, and this host uses port 6379.

In the composetest directory, create another file named requirements.txt with the following content:

flask

redis

2. Create the Dockerfile

In the composetest directory, create a file named Dockerfile with the following content:

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

COPY . .

CMD ["flask", "run"]

Dockerfile content explanation:

ENV FLASK_RUN_HOST 0.0.0.0

Sets the environment variables used by the flask command.

RUN pip install -r requirements.txt

Copies requirements.txt and installs Python dependencies.

3. Create docker-compose.yml

In the test directory, create a file named docker-compose.yml and paste the following content:

docker-compose.yml configuration file

yaml configuration

version

:

'

3

'

services

:

  web

:

    build

:

.

    ports

:

     -

"5000:5000"

  redis

:

    image

:

"redis:alpine"

This Compose file defines two services: web and redis.

4. Build and run your application with Compose commands

In the test directory, run the following command to start the application:

docker-compose up

If you want to run the service in the background, you can add the -d argument:

docker-compose up -d


yml configuration directive reference

version

Specifies which version of Compose this yml complies with.

build

Specifies the build image context path:

For example, the webapp service, specifying an image built from the context path ./dir/Dockerfile:

version: "3.7"

services:

  webapp:

    build: ./dir

Or, as an object with the path specified in context, along with optional Dockerfile and args:

version: "3.7"

services:

  webapp:

    build:

      context: ./dir

      dockerfile: Dockerfile-alternate

      args:

        buildno: 1

      labels:

        - "com.example.description=Accounting webapp"

        - "com.example.department=Finance"

        - "com.example.label-with-empty-value"

      target: prod

cap_add,cap_drop

Adds or removes kernel capabilities of the host that the container has.

cap_add:

  - ALL # 开启全部权限



cap_drop:

  - SYS_PTRACE # 关闭 ptrace权限

cgroup_parent

Specifies a parent cgroup for the container, meaning it will inherit the resource limits of that group.

cgroup_parent: m-executor-abcd

command

Overrides the default command when the container starts.

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

container_name

Specifies a custom container name instead of the generated default name.

container_name: my-web-container

depends_on

Sets dependencies.

version: "3.7"

services:

  web:

    build: .

    depends_on:

      - db

      - redis

  redis:

    image: redis

  db:

    image: postgres

Note: The web service does not wait until redis db is fully started before starting.

deploy

Specifies configuration related to the deployment and running of services. Only useful in swarm mode.

version: "3.7"

services:

  redis:

    image: redis:alpine

    deploy:

      mode:replicated

      replicas: 6

      endpoint_mode: dnsrr

      labels: 

        description: "This redis service label"

      resources:

        limits:

          cpus: '0.50'

          memory: 50M

        reservations:

          cpus: '0.25'

          memory: 20M

      restart_policy:

        condition: on-failure

        delay: 5s

        max_attempts: 3

        window: 120s

Optional parameters:

endpoint_mode: The way to access cluster services.

endpoint_mode: vip 

# Docker cluster services an external virtual IP. All requests will reach the machines inside the cluster service through this virtual IP.

endpoint_mode: dnsrr

# DNS round-robin (DNSRR). All requests will automatically round-robin through one of the IPs in the cluster IP list.

labels: Sets labels on the service. Labels under deploy can be overridden by labels on the container (configured at the same level as deploy).

mode: Specifies the mode provided by the service.

replicas:mode When using replicated, this argument is needed to configure the specific number of nodes to run.

resources: Configures limits on server resource usage. For example, as in the case above, configure the CPU percentage and memory usage required to run the redis cluster, to avoid exceptions caused by excessive resource usage.

restart_policy: Configures how to restart a container when it exits.

rollback_config: Configures how to roll back a service when an update fails.

update_config: Configures how services should be updated, useful for configuring rolling updates.

Note: Only supported in V3.4 and later.

devices

Specifies a list of device mappings.

devices:

  - "/dev/ttyUSB0:/dev/ttyUSB0"

dns

Custom DNS servers, which can be a single value or multiple values in a list.

dns: 8.8.8.8



dns:

  - 8.8.8.8

  - 9.9.9.9

dns_search

Custom DNS search domains. Can be a single value or a list.

dns_search: example.com



dns_search:

  - dc1.example.com

  - dc2.example.com

entrypoint

Overrides the container's default entrypoint.

entrypoint: /code/entrypoint.sh

Can also be in the following format:

entrypoint:

    - php

    - -d

    - zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so

    - -d

    - memory_limit=-1

    - vendor/bin/phpunit

env_file

Adds environment variables from a file. Can be a single value or multiple values in a list.

env_file: .env

Can also be in list format:

env_file:

  - ./common.env

  - ./apps/web.env

  - /opt/secrets.env

environment

Adds environment variables. You can use an array or dictionary, or any boolean value; booleans need to be quoted to ensure the YML parser does not convert them to True or False.

environment:

  RACK_ENV: development

  SHOW: 'true'

expose

Exposes ports but does not map them to the host; they are only accessible to linked services.

Only internal ports can be specified as arguments:

expose:

 - "3000"

 - "8000"

extra_hosts

Adds hostname mappings. Similar to docker client --add-host.

extra_hosts:

 - "somehost:162.242.195.82"

 - "otherhost:50.31.209.229"

The above creates a mapping of IP address to hostname in /etc/hosts inside this service's container:

162.242.195.82  somehost

50.31.209.229   otherhost

healthcheck

Used to detect whether the docker service is running healthily.

healthcheck:

  test: ["CMD", "curl", "-f", "http://localhost"] # 设置检测程序

  interval: 1m30s # 设置检测间隔

  timeout: 10s # 设置检测超时时间

  retries: 3 # 设置重试次数

  start_period: 40s # 启动后,多少秒开始启动检测程序

image

Specifies the image the container runs. The following formats are all valid:

image: redis

image: ubuntu:14.04

image: tutum/influxdb

image: example-registry.com:4000/postgresql

image: a4bc65fd # 镜像id

logging

Logging configuration for the service.

driver: Specifies the logging driver for the service container; the default is json-file. There are the following three options

driver: "json-file"

driver: "syslog"

driver: "none"

Only with the json-file driver can the following arguments be used to limit the number and size of logs.

logging:

  driver: json-file

  options:

    max-size: "200k" # 单个文件大小为200k

    max-file: "10" # 最多10个文件

When the file limit is reached, old files are automatically deleted.

With the syslog driver, you can use syslog-address to specify the log receiving address.

logging:

  driver: syslog

  options:

    syslog-address: "tcp://192.168.0.42:123"

network_mode

Sets the network mode.

network_mode: "bridge"

network_mode: "host"

network_mode: "none"

network_mode: "service:[service name]"

network_mode: "container:[container name/id]"

networks

Configures the networks the container connects to, referencing entries under the top-level networks.

services:

  some-service:

    networks:

      some-network:

        aliases:

         - alias1

      other-network:

        aliases:

         - alias2

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

aliases : Other containers on the same network can use the service name or this alias to connect to the corresponding container's service.

restart

restart: "no"

restart: always

restart: on-failure

restart: unless-stopped

Note: In swarm cluster mode, use restart_policy instead.

secrets

Stores sensitive data, such as passwords:

version: "3.1"

services:



mysql:

  image: mysql

  environment:

    MYSQL_ROOT_PASSWORD_FILE: /run/secrets/my_secret

  secrets:

    - my_secret



secrets:

  my_secret:

    file: ./my_secret.txt

security_opt

Modifies the container's default schema label.

security-opt:

  - label:user:USER   # 设置容器的用户标签

  - label:role:ROLE   # 设置容器的角色标签

  - label:type:TYPE   # 设置容器的安全策略标签

  - label:level:LEVEL  # 设置容器的安全等级标签

stop_grace_period

Specifies how long to wait after the container fails to handle SIGTERM (or any stop_signal) before sending SIGKILL to shut down the container.

stop_grace_period: 1s # 等待 1 秒

stop_grace_period: 1m30s # 等待 1 分 30 秒 

The default wait time is 10 seconds.

stop_signal

Sets an alternative signal for stopping the container. By default, SIGTERM is used.

The following example uses SIGUSR1 instead of SIGTERM to stop the container.

stop_signal: SIGUSR1

sysctls

Sets kernel parameters in the container; can use array or dictionary format.

sysctls:

  net.core.somaxconn: 1024

  net.ipv4.tcp_syncookies: 0



sysctls:

  - net.core.somaxconn=1024

  - net.ipv4.tcp_syncookies=0

tmpfs

Mounts a temporary filesystem inside the container. Can be a single value or multiple values in a list.

tmpfs: /run



tmpfs:

  - /run

  - /tmp

ulimits

Overrides the container's default ulimit.

ulimits:

  nproc: 65535

  nofile:

    soft: 20000

    hard: 40000

volumes

Mounts host data volumes or files into the container.

version: "3.7"

services:

  db:

    image: postgres:latest

    volumes:

      - "/localhost/postgres.sock:/var/run/postgres/postgres.sock"

      - "/localhost/data:/var/lib/postgresql/data"