docker-compose.yml 语法说明

5,555 阅读18分钟
原文链接: www.iigrowing.cn
默认的模板文件是 docker-compose.yml,其中定义的每个服务都必须通过 image 指令指定镜像或 build 指令(需要 Dockerfile)来自动构建。
其它大部分指令都跟 docker run 中的类似。
如果使用 build 指令,在 Dockerfile 中设置的选项(例如:CMD, EXPOSE, VOLUME, ENV 等) 将会自动被获取,无需在 docker-compose.yml 中再次设置。
image
指定为镜像名称或镜像 ID。如果镜像在本地不存在,Compose 将会尝试拉去这个镜像。
例如:
image: ubuntu
image: orchardup/postgresql
image: a4bc65fd

build

指定 Dockerfile 所在文件夹的路径。 Compose 将会利用它自动构建这个镜像,然后使用这个镜像。
build: /path/to/build/dir

command

覆盖容器启动后默认执行的命令。
command: bundle exec thin -p 3000

链接到其它服务中的容器。使用服务名称(同时作为别名)或服务名称:服务别名 (SERVICE:ALIAS) 格式都可以。
links:
– db
– db:database
– redis
使用的别名将会自动在服务容器中的 /etc/hosts 里创建。例如:
172.17.2.186 db
相应的环境变量也将被创建。

链接到 docker-compose.yml 外部的容器,甚至 并非 Compose 管理的容器。参数格式跟 links 类似。
external_links:
– redis_1
– project_db_1:mysql
– project_db_1:postgresql

ports

暴露端口信息。
使用宿主:容器 (HOST:CONTAINER)格式或者仅仅指定容器的端口(宿主将会随机选择端口)都可以。

ports:

– “3000”
– “8000:8000″
– “127.0.0.1:8001:8001″
注:当使用 HOST:CONTAINER 格式来映射端口时,如果你使用的容器端口小于 60 你可能会得到错误得结果,因为 YAML 将会解析 xx:yy 这种数字格式为 60 进制。所以建议采用字符串格式。

expose

暴露端口,但不映射到宿主机,只被连接的服务访问。
仅可以指定内部端口为参数
expose:
– “3000”
– “8000”

volumes

卷挂载路径设置。可以设置宿主机路径 (HOST:CONTAINER) 或加上访问模式 (HOST:CONTAINER:ro)。
volumes:
– /var/lib/mysql
– cache/:/tmp/cache
– ~/configs:/etc/configs/:ro

volumes_from

从另一个服务或容器挂载它的所有卷。
volumes_from:
– service_name
– container_name

environment

设置环境变量。你可以使用数组或字典两种格式。
只给定名称的变量会自动获取它在 Compose 主机上的值,可以用来防止泄露不必要的数据。
environment:
– RACK_ENV=development
– SESSION_SECRET

env_file

从文件中获取环境变量,可以为单独的文件路径或列表。
如果通过 docker-compose -f FILE 指定了模板文件,则 env_file 中路径会基于模板文件路径。
如果有变量名称与 environment 指令冲突,则以后者为准。
env_file: .env
env_file:
– ./common.env
– ./apps/web.env
– /opt/secrets.env
环境变量文件中每一行必须符合格式,支持 # 开头的注释行。
# common.env: Set Rails/Rack environment
RACK_ENV=development

extends

基于已有的服务进行扩展。例如我们已经有了一个 webapp 服务,模板文件为 common.yml。
# common.yml
webapp:
build: ./webapp
environment:
– DEBUG=false
– SEND_EMAILS=false
编写一个新的 development.yml 文件,使用 common.yml 中的 webapp 服务进行扩展。

development.yml

web:
extends:
file: common.yml
service: webapp
ports:
– “8000:8000″
links:
– db
environment:
– DEBUG=true
db:
image: postgres
后者会自动继承 common.yml 中的 webapp 服务及相关环节变量。

net

设置网络模式。使用和 docker client 的 –net 参数一样的值。
net: “bridge”
net: “none”
net: “container:[name or id]”
net: “host”

pid

跟主机系统共享进程命名空间。打开该选项的容器可以相互通过进程 ID 来访问和操作。
pid: “host”

dns

配置 DNS 服务器。可以是一个值,也可以是一个列表。
dns: 8.8.8.8
dns:
– 8.8.8.8
– 9.9.9.9

cap_add, cap_drop

添加或放弃容器的 Linux 能力(Capabiliity)。
cap_add:
– ALL
cap_drop:
– NET_ADMIN
– SYS_ADMIN

配置 DNS 搜索域。可以是一个值,也可以是一个列表。
dns_search: example.com
dns_search:
– domain1.example.com
– domain2.example.com
working_dir, entrypoint, user, hostname, domainname, mem_limit, privileged, restart, stdin_open, tty, cpu_shares
这些都是和 docker run 支持的选项类似。
cpu_shares: 73
working_dir: /code
entrypoint: /code/entrypoint.sh
user: postgresql
hostname: foo
domainname: foo.com
mem_limit: 1000000000
privileged: true
restart: always
stdin_open: true
tty: true

 

官方文档地址:

https://docs.docker.com/compose/compose-file/compose-file-v2/#network

 

Compose file version 2 reference

Estimated reading time: 37 minutes

Reference and guidelines

These topics describe version 2 of the Compose file format.

Compose and Docker compatibility matrix

There are several versions of the Compose file format – 1, 2, 2.x, and 3.x The table below is a quick look. For full details on what each version includes and how to upgrade, see About versions and upgrading.

This table shows which Compose file versions support specific Docker releases.

Compose file formatDocker Engine release
3.4 17.09.0+
3.3 17.06.0+
3.2 17.04.0+
3.1 1.13.1+
3.0 1.13.0+
2.3 17.06.0+
2.2 1.13.0+
2.1 1.12.0+
2.0 1.10.0+
1.0 1.9.1.+

In addition to Compose file format versions shown in the table, the Compose itself is on a release schedule, as shown in Compose releases, but file format versions do not necessairly increment with each release. For example, Compose file format 3.0 was first introduced in Compose release 1.10.0, and versioned gradually in subsequent releases.

Service configuration reference

The Compose file is a YAML file defining services, networks and volumes. The default path for a Compose file is ./docker-compose.yml.

Tip: You can use either a .yml or .yaml extension for this file. They both work.

A container definition contains configuration which will be applied to each container started for that service, much like passing command-line parameters to docker run. Likewise, network and volume definitions are analogous to docker network create and docker volume create.

As with docker run, options specified in the Dockerfile (e.g., CMDEXPOSEVOLUMEENV) are respected by default – you don’t need to specify them again in docker-compose.yml.

You can use environment variables in configuration values with a Bash-like ${VARIABLE} syntax – see variable substitution for full details.

This section contains a list of all configuration options supported by a service definition in version 2.

blkio_config

A set of configuration options to set block IO limits for this service.

version: '2.2'
services:
  foo:
    image: busybox
    blkio_config:
      weight: 300
      weight_device:
        - path: /dev/sda
          weight: 400
      device_read_bps:
        - path: /dev/sdb
          rate: '12mb'
      device_read_iops:
        - path: /dev/sdb
          rate: 120
      device_write_bps:
        - path: /dev/sdb
          rate: '1024k'
      device_write_iops:
        - path: /dev/sdb
          rate: 30

DEVICE_READ_BPS, DEVICE_WRITE_BPS

Set a limit in bytes per second for read / write operations on a given device. Each item in the list must have two keys:

  • path, defining the symbolic path to the affected device
  • rate, either as an integer value representing the number of bytes or as a string expressing a byte value.

DEVICE_READ_IOPS, DEVICE_WRITE_IOPS

Set a limit in operations per second for read / write operations on a given device. Each item in the list must have two keys:

  • path, defining the symbolic path to the affected device
  • rate, as an integer value representing the permitted number of operations per second.

WEIGHT

Modify the proportion of bandwidth allocated to this service relative to other services. Takes an integer value between 10 and 1000, with 500 being the default.

WEIGHT_DEVICE

Fine-tune bandwidth allocation by device. Each item in the list must have two keys:

  • path, defining the symbolic path to the affected device
  • weight, an integer value between 10 and 1000

build

Configuration options that are applied at build time.

build can be specified either as a string containing a path to the build context, or an object with the path specified under context and optionally dockerfile and args.

build: ./dir

build:
  context: ./dir
  dockerfile: Dockerfile-alternate
  args:
    buildno: 1

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This will result in an image named webapp and tagged tag, built from ./dir.

CONTEXT

Version 2 file format and up. In version 1, just use build.

Either a path to a directory containing a Dockerfile, or a url to a git repository.

When the value supplied is a relative path, it is interpreted as relative to the location of the Compose file. This directory is also the build context that is sent to the Docker daemon.

Compose will build and tag it with a generated name, and use that image thereafter.

build:
  context: ./dir

DOCKERFILE

Alternate Dockerfile.

Compose will use an alternate file to build with. A build path must also be specified.

build:
  context: .
  dockerfile: Dockerfile-alternate

ARGS

Version 2 file format and up.

Add build arguments, which are environment variables accessible only during the build process.

First, specify the arguments in your Dockerfile:

ARG buildno
ARG password

RUN echo "Build number: $buildno"
RUN script-requiring-password.sh "$password"

Then specify the arguments under the build key. You can pass either a mapping or a list:

build:
  context: .
  args:
    buildno: 1
    password: secret

build:
  context: .
  args:
    - buildno=1
    - password=secret

You can omit the value when specifying a build argument, in which case its value at build time is the value in the environment where Compose is running.

args:
  - buildno
  - password
Note: YAML boolean values (truefalseyesnoonoff) must be enclosed in quotes, so that the parser interprets them as strings.

LABELS

Added in version 2.1 file format

Add metadata to the resulting image using Docker labels. You can use either an array or a dictionary.

It’s recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.

build:
  context: .
  labels:
    com.example.description: "Accounting webapp"
    com.example.department: "Finance"
    com.example.label-with-empty-value: ""


build:
  context: .
  labels:
    - "com.example.description=Accounting webapp"
    - "com.example.department=Finance"
    - "com.example.label-with-empty-value"

NETWORK

Added in version 2.2 file format

Set the network containers will connect to for the RUN instructions during build.

build:
  context: .
  network: host


build:
  context: .
  network: custom_network_1

SHM_SIZE

Added in version 2.3 file format

Set the size of the /dev/shm partition for this build’s containers. Specify as an integer value representing the number of bytes or as a string expressing a byte value.

build:
  context: .
  shm_size: '2gb'


build:
  context: .
  shm_size: 10000000

TARGET

Added in version 2.3 file format

Build the specified stage as defined inside the Dockerfile. See the multi-stage build docs for details.

  build:
    context: .
    target: prod

cap_add, cap_drop

Add or drop container capabilities. See man 7 capabilities for a full list.

cap_add:
  - ALL

cap_drop:
  - NET_ADMIN
  - SYS_ADMIN

command

Override the default command.

command: bundle exec thin -p 3000

The command can also be a list, in a manner similar to dockerfile:

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

cgroup_parent

Specify an optional parent cgroup for the container.

cgroup_parent: m-executor-abcd

container_name

Specify a custom container name, rather than a generated default name.

container_name: my-web-container

Because Docker container names must be unique, you cannot scale a service beyond 1 container if you have specified a custom name. Attempting to do so results in an error.

devices

List of device mappings. Uses the same format as the --device docker client create option.

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

depends_on

Version 2 file format and up.

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and rediswill be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Simple example:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres
Notedepends_on will not wait for db and redis to be “ready” before starting web – only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

Added in version 2.1 file format.

A healthcheck indicates that you want a dependency to wait for another container to be “healthy” (i.e. its healthcheck advertises a successful state) before starting.

Example:

version: '2.1'
services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: redis
    healthcheck:
      test: "exit 0"

In the above example, Compose will wait for the redis service to be started (legacy behavior) and the dbservice to be healthy before starting web.

See the healthcheck section for complementary information.

dns

Custom DNS servers. Can be a single value or a list.

dns: 8.8.8.8
dns:
  - 8.8.8.8
  - 9.9.9.9

dns_opt

List of custom DNS options to be added to the container’s resolv.conf file.

dns_opt:
  - use-vc
  - no-tld-query

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

dns_search: example.com
dns_search:
  - dc1.example.com
  - dc2.example.com

tmpfs

Mount a temporary file system inside the container. Can be a single value or a list.

tmpfs: /run
tmpfs:
  - /run
  - /tmp

entrypoint

Override the default entrypoint.

entrypoint: /code/entrypoint.sh

The entrypoint can also be a list, in a manner similar to dockerfile:

entrypoint:
    - php
    - -d
    - zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
    - -d
    - memory_limit=-1
    - vendor/bin/phpunit
Note: Setting entrypoint will both override any default entrypoint set on the service’s image with the ENTRYPOINT Dockerfile instruction, and clear out any default command on the image – meaning that if there’s a CMD instruction in the Dockerfile, it will be ignored.

env_file

Add environment variables from a file. Can be a single value or a list.

If you have specified a Compose file with docker-compose -f FILE, paths in env_file are relative to the directory that file is in.

Environment variables declared in the environment section override these values – this holds true even if those values are empty or undefined.

env_file: .env

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

Compose expects each line in an env file to be in VAR=VAL format. Lines beginning with # (i.e. comments) are ignored, as are blank lines.

# Set Rails/Rack environment
RACK_ENV=development
Note: If your service specifies a build option, variables defined in environment files will not be automatically visible during the build. Use the args sub-option of build to define build-time environment variables.

The value of VAL is used as is and not modified at all. For example if the value is surrounded by quotes (as is often the case of shell variables), the quotes will be included in the value passed to Compose.

Keep in mind that the order of files in the list is significant in determining the value assigned to a variable that shows up more than once. The files in the list are processed from the top down. For the same variable specified in file a.env and assigned a different value in file b.env, if b.env is listed below (after), then the value from b.env stands. For example, given the following declaration in docker_compose.yml:

services:
  some-service:
    env_file:
      - a.env
      - b.env

And the following files:

# a.env
VAR=1

and

# b.env
VAR=hello

$VAR will be hello.

environment

Add environment variables. You can use either an array or a dictionary. Any boolean values; true, false, yes no, need to be enclosed in quotes to ensure they are not converted to True or False by the YML parser.

Environment variables with only a key are resolved to their values on the machine Compose is running on, which can be helpful for secret or host-specific values.

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:

environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET
Note: If your service specifies a build option, variables defined in environment will not be automatically visible during the build. Use the args sub-option of build to define build-time environment variables.

expose

Expose ports without publishing them to the host machine – they’ll only be accessible to linked services. Only the internal port can be specified.

expose:
 - "3000"
 - "8000"

extends

Extend another service, in the current file or another, optionally overriding configuration.

You can use extends on any service together with other configuration keys. The extends value must be a dictionary defined with a required service and an optional file key.

extends:
  file: common.yml
  service: webapp

The service the name of the service being extended, for example web or database. The file is the location of a Compose configuration file defining that service.

If you omit the file Compose looks for the service configuration in the current file. The file value can be an absolute or relative path. If you specify a relative path, Compose treats it as relative to the location of the current file.

You can extend a service that itself extends another. You can extend indefinitely. Compose does not support circular references and docker-compose returns an error if it encounters one.

For more on extends, see the the extends documentation.

Link to containers started outside this docker-compose.yml or even outside of Compose, especially for containers that provide shared or common services. external_links follow semantics similar to linkswhen specifying both the container name and the link alias (CONTAINER:ALIAS).

external_links:
 - redis_1
 - project_db_1:mysql
 - project_db_1:postgresql
Note: For version 2 file format, the externally-created containers must be connected to at least one of the same networks as the service which is linking to them.

extra_hosts

Add hostname mappings. Use the same values as the docker client --add-host parameter.

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

An entry with the ip address and hostname will be created in /etc/hosts inside containers for this service, e.g:

162.242.195.82  somehost
50.31.209.229   otherhost

group_add

Specify additional groups (by name or number) which the user inside the container will be a member of. Groups must exist in both the container and the host system to be added. An example of where this is useful is when multiple containers (running as different users) need to all read or write the same file on the host system. That file can be owned by a group shared by all the containers, and specified in group_add. See theDocker documentation for more details.

A full example:

version: '2'
services:
  myservice:
    image: alpine
    group_add:
      - mail

Running id inside the created container will show that the user belongs to the mail group, which would not have been the case if group_add were not used.

healthcheck

Version 2.1 file format and up.

Configure a check that’s run to determine whether or not containers for this service are “healthy”. See the docs for the HEALTHCHECK Dockerfile instruction for details on how healthchecks work.

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]
  interval: 1m30s
  timeout: 10s
  retries: 3
  start_period: 40s

intervaltimeout and start_period are specified as durations.

test must be either a string or a list. If it’s a list, the first item must be either NONECMD or CMD-SHELL. If it’s a string, it’s equivalent to specifying CMD-SHELL followed by that string.

# Hit the local web app
test: ["CMD", "curl", "-f", "http://localhost"]

# As above, but wrapped in /bin/sh. Both forms below are equivalent.
test: ["CMD-SHELL", "curl -f http://localhost && echo 'cool, it works'"]
test: curl -f https://localhost && echo 'cool, it works'

To disable any default healthcheck set by the image, you can use disable: true. This is equivalent to specifying test: ["NONE"].

healthcheck:
  disable: true
Note: The start_period option is a more recent feature and is only available with the 2.3 file format.

image

Specify the image to start the container from. Can either be a repository/tag or a partial image ID.

image: redis
image: ubuntu:14.04
image: tutum/influxdb
image: example-registry.com:4000/postgresql
image: a4bc65fd

If the image does not exist, Compose attempts to pull it, unless you have also specified build, in which case it builds it using the specified options and tags it with the specified tag.

init

Added in version 2.2 file format.

Run an init inside the container that forwards signals and reaps processes. Either set a boolean value to use the default init, or specify a path to a custom one.

version: '2.2'
services:
  web:
    image: alpine:latest
    init: true


version: '2.2'
services:
  web:
    image: alpine:latest
    init: /usr/libexec/docker-init

isolation

Added in version 2.1 file format.

Specify a container’s isolation technology. On Linux, the only supported value is default. On Windows, acceptable values are defaultprocess and hyperv. Refer to the Docker Engine docs for details.

labels

Add metadata to containers using Docker labels. You can use either an array or a dictionary.

It’s recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.

labels:
  com.example.description: "Accounting webapp"
  com.example.department: "Finance"
  com.example.label-with-empty-value: ""

labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"
  - "com.example.label-with-empty-value"

Link to containers in another service. Either specify both the service name and a link alias ("SERVICE:ALIAS"), or just the service name.

Links are a legacy option. We recommend using networks instead.

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

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

Links also express dependency between services in the same way as depends_on, so they determine the order of service startup.

Note: If you define both links and networks, services with links between them must share at least one network in common in order to communicate. We recommend using networks instead.

logging

Logging configuration for the service.

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

The driver name specifies a logging driver for the service’s containers, as with the --log-driver option for docker run (documented here).

The default value is json-file.

driver: "json-file"
driver: "syslog"
driver: "none"
Note: Only the json-file and journald drivers make the logs available directly fromdocker-compose up and docker-compose logs. Using any other driver will not print any logs.

Specify logging options for the logging driver with the options key, as with the --log-opt option for docker run.

Logging options are key-value pairs. An example of syslog options:

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

network_mode

Version 2 file format and up. Replaces the version 1 net option.

Network mode. Use the same values as the docker client --net parameter, plus the special form service:[service name].

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

networks

Version 2 file format and up. Replaces the version 1 net option.

Networks to join, referencing entries under the top-level networks key.

services:
  some-service:
    networks:
     - some-network
     - other-network

ALIASES

Aliases (alternative hostnames) for this service on the network. Other containers on the same network can use either the service name or this alias to connect to one of the service’s containers.

Since aliases is network-scoped, the same service can have different aliases on different networks.

Note: A network-wide alias can be shared by multiple containers, and even by multiple services. If it is, then exactly which container the name will resolve to is not guaranteed.

The general format is shown here.

services:
  some-service:
    networks:
      some-network:
        aliases:
         - alias1
         - alias3
      other-network:
        aliases:
         - alias2

In the example below, three services are provided (webworker, and db), along with two networks (newand legacy). The db service is reachable at the hostname db or database on the new network, and at db or mysql on the legacy network.

version: '2'

services:
  web:
    build: ./web
    networks:
      - new

  worker:
    build: ./worker
    networks:
      - legacy

  db:
    image: mysql
    networks:
      new:
        aliases:
          - database
      legacy:
        aliases:
          - mysql

networks:
  new:
  legacy:

IPV4_ADDRESS, IPV6_ADDRESS

Specify a static IP address for containers for this service when joining the network.

The corresponding network configuration in the top-level networks section must have an ipam block with subnet and gateway configurations covering each static address. If IPv6 addressing is desired, the enable_ipv6 option must be set.

An example:

version: '2.1'

services:
  app:
    image: busybox
    command: ifconfig
    networks:
      app_net:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10

networks:
  app_net:
    driver: bridge
    enable_ipv6: true
    ipam:
      driver: default
      config:
      - subnet: 172.16.238.0/24
        gateway: 172.16.238.1
      - subnet: 2001:3984:3989::/64
        gateway: 2001:3984:3989::1

Added in version 2.1 file format.

Specify a list of link-local IPs. Link-local IPs are special IPs which belong to a well known subnet and are purely managed by the operator, usually dependent on the architecture where they are deployed. Therefore they are not managed by docker (IPAM driver).

Example usage:

version: '2.1'
services:
  app:
    image: busybox
    command: top
    networks:
      app_net:
        link_local_ips:
          - 57.123.22.11
          - 57.123.22.13
networks:
  app_net:
    driver: bridge

pid

pid: "host"
pid: "container:custom_container_1"
pid: "service:foobar"

If set to one of the following forms: container:<container_name>service:<service_name>, the service will share the PID address space of the designated container or service.

If set to “host”, the service’s PID mode will be the host PID mode. This turns on sharing between container and the host operating system the PID address space. Containers launched with this flag will be able to access and manipulate other containers in the bare-metal machine’s namespace and vise-versa.

Note: the service: and container: forms require version 2.1 or above

pids_limit

Added in version 2.1 file format.

Tunes a container’s PIDs limit. Set to -1 for unlimited PIDs.

pids_limit: 10

ports

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

Note: When mapping ports in the HOST:CONTAINER format, you may experience erroneous results when using a container port lower than 60, because YAML will parse numbers in the format xx:yy as sexagesimal (base 60). For this reason, we recommend always explicitly specifying your port mappings as strings.
ports:
 - "3000"
 - "3000-3005"
 - "8000:8000"
 - "9090-9091:8080-8081"
 - "49100:22"
 - "127.0.0.1:8001:8001"
 - "127.0.0.1:5000-5010:5000-5010"
 - "6060:6060/udp"

scale

Added in version 2.2 file format

Specify the default number of containers to deploy for this service. Whenever you run docker-compose up, Compose will create or remove containers to match the specified number. This value can be overridden using the --scale flag.

web:
  image: busybox:latest
  command: echo 'scaled'
  scale: 3

security_opt

Override the default labeling scheme for each container.

security_opt:
  - label:user:USER
  - label:role:ROLE

stop_grace_period

Specify how long to wait when attempting to stop a container if it doesn’t handle SIGTERM (or whatever stop signal has been specified with stop_signal), before sending SIGKILL. Specified as a duration.

stop_grace_period: 1s
stop_grace_period: 1m30s

By default, stop waits 10 seconds for the container to exit before sending SIGKILL.

stop_signal

Sets an alternative signal to stop the container. By default stop uses SIGTERM. Setting an alternative signal using stop_signal will cause stop to send that signal instead.

stop_signal: SIGUSR1

storage_opt

Added in version 2.1 file format.

Set storage driver options for this service.

storage_opt:
  size: '1G'

sysctls

Added in version 2.1 file format.

Kernel parameters to set in the container. You can use either an array or a dictionary.

sysctls:
  net.core.somaxconn: 1024
  net.ipv4.tcp_syncookies: 0

sysctls:
  - net.core.somaxconn=1024
  - net.ipv4.tcp_syncookies=0

ulimits

Override the default ulimits for a container. You can either specify a single limit as an integer or soft/hard limits as a mapping.

ulimits:
  nproc: 65535
  nofile:
    soft: 20000
    hard: 40000

userns_mode

Added in version 2.1 file format.

userns_mode: "host"

Disables the user namespace for this service, if Docker daemon is configured with user namespaces. See dockerd for more information.

volumes, volume_driver

Mount paths or named volumes, optionally specifying a path on the host machine (HOST:CONTAINER), or an access mode (HOST:CONTAINER:ro). For version 2 files, named volumes need to be specified with the top-level volumes key.

You can mount a relative path on the host, which will expand relative to the directory of the Compose configuration file being used. Relative paths should always begin with . or ...

volumes:
  # Just specify a path and let the Engine create a volume
  - /var/lib/mysql

  # Specify an absolute path mapping
  - /opt/data:/var/lib/mysql

  # Path on the host, relative to the Compose file
  - ./cache:/tmp/cache

  # User-relative path
  - ~/configs:/etc/configs/:ro

  # Named volume
  - datavolume:/var/lib/mysql

If you do not use a host path, you may specify a volume_driver.

volume_driver: mydriver

There are several things to note, depending on which Compose file version you’re using:

  • You can use volume_driver in version 2 files, but it will only apply to anonymous volumes (those specified in the image, or specified under volumes without an explicit named volume or host path). To configure the driver for a named volume, use the driver key under the entry in the top-level volumes option.
  • For version 1 files, both named volumes and container volumes use the specified driver. This changes in version 2 per the above reference to anonymous volumes.
  • No path expansion will be done if you have also specified a volume_driver. For example, if you specify a mapping of ./foo:/data, the ./foo part will be passed straight to the volume driver without being expanded.

See Docker Volumes and Volume Plugins for more information.

volumes_from

Mount all of the volumes from another service or container, optionally specifying read-only access (ro) or read-write (rw). If no access level is specified, then read-write will be used.

volumes_from:
 - service_name
 - service_name:ro
 - container:container_name
 - container:container_name:rw

Notes

  • The container:... formats are only supported in the version 2 file format.
  • In version 1, you can use container names without marking them as such:
    • service_name
    • service_name:ro
    • container_name
    • container_name:rw

restart

no is the default restart policy, and it will not restart a container under any circumstance. When always is specified, the container always restarts. The on-failure policy restarts a container if the exit code indicates an on-failure error.

  - restart: no
  - restart: always
  - restart: on-failure

cpu_count, cpu_percent, cpu_shares, cpu_quota, cpus, cpuset, domainname, hostname, ipc, mac_address, mem_limit, memswap_limit, mem_swappiness, mem_reservation, oom_score_adj, privileged, read_only, shm_size, stdin_open, tty, user, working_dir

Each of these is a single value, analogous to its docker run counterpart.

Note: The following options were added in version 2.2: cpu_countcpu_percentcpus.
cpu_count: 2
cpu_percent: 50
cpus: 0.5
cpu_shares: 73
cpu_quota: 50000
cpuset: 0,1

user: postgresql
working_dir: /code

domainname: foo.com
hostname: foo
ipc: host
mac_address: 02:42:ac:11:65:43

mem_limit: 1000000000
memswap_limit: 2000000000
mem_reservation: 512m
privileged: true

oom_score_adj: 500

read_only: true
shm_size: 64M
stdin_open: true
tty: true

Specifying durations

Some configuration options, such as the interval and timeout sub-options for healthcheck, accept a duration as a string in a format that looks like this:

2.5s
10s
1m30s
2h32m
5h34m56s

The supported units are usmssm and h.

Specifying byte values

Some configuration options, such as the device_read_bps sub-option for blkio_config, accept a byte value as a string in a format that looks like this:

2b
1024kb
2048k
300m
1gb

The supported units are bkm and g, and their alternative notation kbmb and gb. Please note that decimal values are not supported at this time.

Volume configuration reference

While it is possible to declare volumes on the fly as part of the service declaration, this section allows you to create named volumes that can be reused across multiple services (without relying on volumes_from), and are easily retrieved and inspected using the docker command line or API. See the docker volumesubcommand documentation for more information.

Here’s an example of a two-service setup where a database’s data directory is shared with another service as a volume so that it can be periodically backed up:

version: "2.2"

services:
  db:
    image: db
    volumes:
      - data-volume:/var/lib/db
  backup:
    image: backup-service
    volumes:
      - data-volume:/var/lib/backup/data

volumes:
  data-volume:

An entry under the top-level volumes key can be empty, in which case it will use the default driver configured by the Engine (in most cases, this is the local driver). Optionally, you can configure it with the following keys:

driver

Specify which volume driver should be used for this volume. Defaults to whatever driver the Docker Engine has been configured to use, which in most cases is local. If the driver is not available, the Engine will return an error when docker-compose up tries to create the volume.

 driver: foobar

driver_opts

Specify a list of options as key-value pairs to pass to the driver for this volume. Those options are driver-dependent – consult the driver’s documentation for more information. Optional.

 driver_opts:
   foo: "bar"
   baz: 1

external

If set to true, specifies that this volume has been created outside of Compose. docker-compose up will not attempt to create it, and will raise an error if it doesn’t exist.

external cannot be used in conjunction with other volume configuration keys (driverdriver_opts).

In the example below, instead of attempting to create a volume called [projectname]_data, Compose will look for an existing volume simply called data and mount it into the db service’s containers.

version: '2'

services:
  db:
    image: postgres
    volumes:
      - data:/var/lib/postgresql/data

volumes:
  data:
    external: true

You can also specify the name of the volume separately from the name used to refer to it within the Compose file:

volumes:
  data:
    external:
      name: actual-name-of-volume
Note: In newer versions of Compose, the external.name property is deprecated in favor of simply using the name property.

labels

Added in version 2.1 file format.

Add metadata to containers using Docker labels. You can use either an array or a dictionary.

It’s recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.

labels:
  com.example.description: "Database volume"
  com.example.department: "IT/Ops"
  com.example.label-with-empty-value: ""

labels:
  - "com.example.description=Database volume"
  - "com.example.department=IT/Ops"
  - "com.example.label-with-empty-value"

name

Added in version 2.1 file format

Set a custom name for this volume.

version: '2.1'
volumes:
  data:
    name: my-app-data

It can also be used in conjuction with the external property:

version: '2.1'
volumes:
  data:
    external: true
    name: my-app-data

Network configuration reference

The top-level networks key lets you specify networks to be created. For a full explanation of Compose’s use of Docker networking features, see the Networking guide.

driver

Specify which driver should be used for this network.

The default driver depends on how the Docker Engine you’re using is configured, but in most instances it will be bridge on a single host and overlay on a Swarm.

The Docker Engine will return an error if the driver is not available.

driver: overlay

driver_opts

Specify a list of options as key-value pairs to pass to the driver for this network. Those options are driver-dependent – consult the driver’s documentation for more information. Optional.

  driver_opts:
    foo: "bar"
    baz: 1

enable_ipv6

Added in version 2.1 file format.

Enable IPv6 networking on this network.

ipam

Specify custom IPAM config. This is an object with several properties, each of which is optional:

  • driver: Custom IPAM driver, instead of the default.
  • config: A list with zero or more config blocks, each containing any of the following keys:
    • subnet: Subnet in CIDR format that represents a network segment
    • ip_range: Range of IPs from which to allocate container IPs
    • gateway: IPv4 or IPv6 gateway for the master subnet
    • aux_addresses: Auxiliary IPv4 or IPv6 addresses used by Network driver, as a mapping from hostname to IP
  • options: Driver-specific options as a key-value mapping.

A full example:

ipam:
  driver: default
  config:
    - subnet: 172.28.0.0/16
      ip_range: 172.28.5.0/24
      gateway: 172.28.5.254
      aux_addresses:
        host1: 172.28.1.5
        host2: 172.28.1.6
        host3: 172.28.1.7
  options:
    foo: bar
    baz: "0"

internal

By default, Docker also connects a bridge network to it to provide external connectivity. If you want to create an externally isolated overlay network, you can set this option to true.

labels

Added in version 2.1 file format.

Add metadata to containers using Docker labels. You can use either an array or a dictionary.

It’s recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.

labels:
  com.example.description: "Financial transaction network"
  com.example.department: "Finance"
  com.example.label-with-empty-value: ""

labels:
  - "com.example.description=Financial transaction network"
  - "com.example.department=Finance"
  - "com.example.label-with-empty-value"

external

If set to true, specifies that this network has been created outside of Compose. docker-compose up will not attempt to create it, and will raise an error if it doesn’t exist.

external cannot be used in conjunction with other network configuration keys (driverdriver_optsgroup_addipaminternal).

In the example below, proxy is the gateway to the outside world. Instead of attempting to create a network called [projectname]_outside, Compose will look for an existing network simply called outside and connect the proxy service’s containers to it.

version: '2'

services:
  proxy:
    build: ./proxy
    networks:
      - outside
      - default
  app:
    build: ./app
    networks:
      - default

networks:
  outside:
    external: true

You can also specify the name of the network separately from the name used to refer to it within the Compose file:

networks:
  outside:
    external:
      name: actual-name-of-network

HOST OR NONE

Not supposed for version 2 docker-compose files. Use network_mode instead.

Variable substitution

Your configuration options can contain environment variables. Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSIONenvironment variable in the shell and substitutes its value in. For this example, Compose resolves the imageto postgres:9.3 before running the configuration.

If an environment variable is not set, Compose substitutes with an empty string. In the example above, if POSTGRES_VERSION is not set, the value for the image option is postgres:.

You can set default values for environment variables using a .env file, which Compose will automatically look for. Values set in the shell environment will override those set in the .env file.

Important: The .env file feature only works when you use the docker-compose up command and does not work with docker stack deploy.

Both $VARIABLE and ${VARIABLE} syntax are supported. Additionally when using the 2.1 file format, it is possible to provide inline default values using typical shell syntax:

  • ${VARIABLE:-default} will evaluate to default if VARIABLE is unset or empty in the environment.
  • ${VARIABLE-default} will evaluate to default only if VARIABLE is unset in the environment.

Other extended shell-style features, such as ${VARIABLE/foo/bar}, are not supported.

You can use a ? (double-dollar sign) when your configuration needs a literal dollar sign. This also prevents Compose from interpolating a value, so a ? allows you to refer to environment variables that you don’t want processed by Compose.

web:
  build: .
  command: "?VAR_NOT_INTERPOLATED_BY_COMPOSE"

If you forget and use a single dollar sign ($), Compose interprets the value as an environment variable and will warn you:

The VAR_NOT_INTERPOLATED_BY_COMPOSE is not set. Substituting an empty string.

Extension fields

Added in version 2.1 file format.

It is possible to re-use configuration fragments using extension fields. Those special fields can be of any format as long as they are located at the root of your Compose file and their name start with the x-character sequence.

version: '2.1'
x-custom:
  items:
    - a
    - b
  options:
    max-size: '12m'
  name: "custom"

The contents of those fields will be ignored by Compose, but they can be inserted in your resource definitions using YAML anchors. For example, if you want several of your services to use the same logging configuration:

logging:
  options:
    max-size: '12m'
    max-file: 5
  driver: json-file

You may write your Compose file as follows:

version: '2.1'
x-logging:
  &default-logging
  options:
    max-size: '12m'
    max-file: 5
  driver: json-file

services:
  web:
    image: myapp/web:latest
    logging: *default-logging
  db:
    image: mysql:latest
    logging: *default-logging

It is also possible to partially override values in extension fields using the YAML merge type. For example:

version: '2.1'
x-volumes:
  &default-volume
  driver: foobar-storage

services:
  web:
    image: myapp/web:latest
    volumes: ["vol1", "vol2", "vol3"]
volumes:
  vol1: *default-volume
  vol2:
    << : *default-volume
    name: volume02
  vol3:
    << : *default-volume
    driver: default
    name: volume-local

Compose documentation

Rate