This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Docker compose has great learning significance in the application of Docker container. Docker compose is a powerful tool for integrating and publishing applications. When using Docker Compose, it’s important to know how to orchestrate the Docker Compose profile.

A preface.

You can view the official docker compose document about docker compose technology

The following content is to establish in have downloaded good Docker and Docker Compose, can see the Docker Compose the official installation guide Install Docker Compose

Build parameters for the Docker Compose configuration file

First, a standard example of a docker-compose. Yml configuration file is officially available

version: "3"
services:

  redis:
    image: redis:alpine
    ports:
      - "6379"
    networks:
      - frontend
    deploy:
      replicas: 2
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

  db:
    image: postgres:9.4
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - backend
    deploy:
      placement:
        constraints: [node.role == manager]

  vote:
    image: dockersamples/examplevotingapp_vote:before
    ports:
      - 5000:80
    networks:
      - frontend
    depends_on:
      - redis
    deploy:
      replicas: 2
      update_config:
        parallelism: 2
      restart_policy:
        condition: on-failure

  result:
    image: dockersamples/examplevotingapp_result:before
    ports:
      - 5001:80
    networks:
      - backend
    depends_on:
      - db
    deploy:
      replicas: 1
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

  worker:
    image: dockersamples/examplevotingapp_worker
    networks:
      - frontend
      - backend
    deploy:
      mode: replicated
      replicas: 1
      labels: [APP=VOTING]
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 120s
      placement:
        constraints: [node.role == manager]

  visualizer:
    image: dockersamples/visualizer:stable
    ports:
      - "8080:8080"
    stop_grace_period: 1m30s
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
      placement:
        constraints: [node.role == manager]

networks:
  frontend:
  backend:

volumes:
  db-data:
Copy the code

This file configures multiple services, and the meaning of each statement in this configuration file requires understanding the meaning of the configuration options

Configuration file

The compose file is a YAML file that defines the service, network, and volume. The default path for the Compose file is./docker-compose. Yml

Tip: You can use.yml or.yaml as the file extension

The service definition contains the configuration applied to each container started for the service, just like passing command line arguments docker Container Create. Similarly, networks and volumes are defined similarly to docker Network CREATE and Docker Volume CREATE.

Just as Docker Container Create specifies options for Dockerfile, such as CMD, EXPOSE, VOLUME, and ENV, by default, you don’t need to specify them again docker-compose. Yml.

You can use the Bash class ${VARIABLE} syntax to use environment variables in configuration values.

Configuration options

1. Bulid

In addition to the image specified, the service can be based on a Dockerfile. The build tag is called Build, which specifies the path to the folder where the Dockerfile is located. Compose will use this to automatically build the image, which will then be used to start the service container

build: /path/to/build/dir1
Copy the code

It could be a relative path

build: ./dir1
Copy the code

Set the context root directory, and then specify Dockerfile as that directory

build: context: .. / dockerfile: path/of/Dockerfile123Copy the code

example

version: '3'
services:
  webapp:
    build: ./dir
Copy the code

If the specified path is in the context, you can select Dockerfile and args. The args tag, like the ARG directive in Dockerfile, can specify an environment variable during the build process, but is cancelled after the build, and is supported in docker-compose. Yml:

version: '3'
services:
  webapp:
    build:
      context: ./dir
      dockerfile: Dockerfile-alternate
      args:
        buildno: 1
Copy the code

Unlike ENV, the args value can be null

args:
  - buildno
  - password
Copy the code

To specify image and build, the option format is

build: ./dir
image: webapp:tag
Copy the code

This generates a tagged image named webaapp in the./dir directory

Note: This option is ignored when deploying the stack in cluster mode with the (Version 3) Compose file. Because the Docker stack command only accepts prebuilt images

2. context

The context option can be either the file path to the Dockerfile or the URL to the git repository that links to it.

When the supplied value is relative to the path, it is resolved relative to the path of the writing file, which is also the context sent to the Docker daemon

build:
  context: ./dir
Copy the code

3. Dockerfile

To use this dockerfile file to build, you must specify the build path

build:
  context: .
  dockerfile: Dockerfile-alternate
Copy the code

4. The args

Add build parameters, which are environment variables that are accessible only during the build process

First, specify parameters in the Dockerfile:

ARG buildno
ARG password

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

Then specify parameters under build, which can be either a map or a list

build:
  context: .
  args:
    buildno: 1
    password: secret
Copy the code

or

build:
  context: .
  args:
    - buildno=1
    - password=secret
Copy the code

This value can be omitted when specifying a build parameter, in which case the built-time value defaults to the value in the run environment

args:
  - buildno
  - password
Copy the code

Note: YAML booleans (true, false, yes, no, on, off) must be enclosed in quotes in order to be properly parsed as strings

5. Cache_from

Write a list of cache resolution mirrors

Build: context:.cache_from: -alpine :latest - corp/web_app:3.14Copy the code

6. labels

The metadata is added to the generated image using the Docker tag, using either an array or a dictionary.

It is recommended to use the reverse DNS flag to prevent the signature from conflicting with that used by other software

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

or

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

7.shm_size

Sets the size of the /dev/shm partition in the container to an integer value representing bytes or a character string

build:
  context: .
  shm_size: '2gb'
Copy the code

or

build:
  context: .
  shm_size: 10000000
Copy the code

8. target

The Stage is specified according to the corresponding Dockerfile build

build:
    context: .
    target: prod
Copy the code

9. Cap_add, cap_drop

To add or remove a container, see Man 7 Capabilities

cap_add:
  - ALL

cap_drop:
  - NET_ADMIN
  - SYS_ADMIN
Copy the code

Note: This option is ignored when deploying the stack in cluster mode with the (Version 3) Compose file. Because the Docker stack command only accepts prebuilt images

10. command

Overrides the default command executed after the container starts

command: bundle exec thin -p 30001
Copy the code

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

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

11. configs

Use the service configs configuration to assign access to each service, which supports two different syntax.

Note: Configuration must exist or be defined at the top level of this stack file configs otherwise stack deployment is invalid

  • SHORT grammar

The SHORT syntax specifies only the configuration name, which allows the container to access the configuration and install it in the /<config_name> container, with both the source name and the target mount point set to the configuration name.

Version: "3.3" services: redis: image: redis:latest Deploy: replicas: 1 configs: -my_config-my_other_config configs: my_config: file: ./my_config.txt my_other_config: external: trueCopy the code

The above instance grants access to the Redis service to my_config and my_other_config using SHORT syntax and is defined by my_other_config as an external resource, which means it is already defined in Docker. It can be deployed via the Docker config create command or through another stack. If none of the external deployment configurations exist, the stack deployment fails with a Config not found error.

Note: The config definition is only supported in 3.3 and later author-file formats. YAML booleans (true, false, yes, no, on, off) must be enclosed in quotes (either single or double), otherwise they are parsed as strings.

  • LONG grammar

The LONG syntax provides more detailed information about creating a service configuration

  • Source: The name of the configuration that exists in Docker

  • Target: The path or name of the file to be loaded in the service’s task. If not specified, the default is /

  • Uid and GID: The numeric UID or GID that owns the installed configuration file in the service’s task container. If not specified, the default is on Linux. Windows does not support this.

  • Mode: Specifies the permission to install files in the service’s task container, expressed in octal notation. For example, 0444 stands for file readable. The default is 0444. If the configuration files cannot be written because they are installed on a temporary file system, it will be ignored if the writable bit is set. Executable bits can be set. If you are not familiar with UNIX file permission patterns, UNIX Permissions Calculator

The following example sets the name my_config to redis_config in the container, the mode to 0440 (group-readable), and the user and group to 103. The ‘redis service cannot access the my_other_config configuration.

Version: "3.3" services: redis: image: redis:latest Deploy: replicas: 1 configs: -source: my_config target: /redis_config uid: '103' gid: '103' mode: 0440 configs: my_config: file: ./my_config.txt my_other_config: external: trueCopy the code

You can grant access to multiple configured services at the same time, or you can mix LONG and SHORT syntax. Defining a configuration does not mean granting access to a service.

12. cgroup_parent

You can select an optional parent, cgroup_parent, for the container

cgroup_parent: m-executor-abcd
Copy the code

Note: Ignore this option when deploying the stack in cluster mode using the (Version 3) Compose file

13. container_name

Specify a name for the custom container instead of using the default name

container_name: my-web-container
Copy the code

Because docker container names must be unique, you cannot extend a service by more than 1 containers if you specify a custom name

14. credential_spec

Configure credential specifications for managed service accounts. This option applies only to Windows container services

The configuration list on credential_spec is formatted as file:// or registry://

Use file: It should be noted that the referenced file must exist in a subdirectory of the CredentialSpecs, Docker data directory. On Windows, this directory defaults to C:\ProgramData\Docker\. The following example loads the credential specification from a file named C:\ProgramData\Docker\CredentialSpecs\my-credential-spec.json:

credential_spec:
  file: my-credential-spec.json
Copy the code

Use Registry: The credential specification is read from the Windows registry on the daemon host. Its registry value must be located at:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs
Copy the code

The following example loads a credential specification with a value specified in the my-Credential-spec registry:

credential_spec:
  registry: my-credential-spec
Copy the code

15. deploy

Specify the configurations associated with deploying and running the service

version: '3'
services:
  redis:
    image: redis:alpine
    deploy:
      replicas: 6
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure
Copy the code

There are a couple of subchoices here

  • endpoint_mode

Specifies the method for discovering the client service connected to the external group

  • Endpoint_mode: VIP: Docker assigns a virtual IP address (VIP) to the service as the “front end” part of the client to access the service on the network.

  • Endpoint_mode: DNSRR: The DNS polling (DNSRR) service does not use a single virtual IP address. Docker sets the DNS entry for the service so that a DNS query for the service name returns a list of IP addresses, and the client connects directly to one of them. The DNS round-robin feature is useful if you want to use your own load balancer, or if you want to mix Windows and Linux applications.

    Version: “3.3”

    services: wordpress: image: wordpress ports: – 8080:80 networks: – overlay deploy: mode: replicated replicas: 2 endpoint_mode: vip

    mysql: image: mysql volumes: – db-data:/var/lib/mysql/data networks: – overlay deploy: mode: replicated replicas: 2 endpoint_mode: dnsrr

    volumes: db-data:

    networks: overlay:

Swarm mode CLI command, Configure service discovery

  • labels

Specifies the labels for the service, which are set only on the service.

version: "3"
services:
  web:
    image: web
    deploy:
      labels:
        com.example.description: "This label will appear on the web service"
Copy the code

The labels on the container are set by placing the labels outside deploy

version: "3"
services:
  web:
    image: web
    labels:
      com.example.description: "This label will appear on all containers for the web service"
Copy the code
  • mode

Global: There is only one container per set node

Replicated: Specifies number of containers (default)

version: '3'
services:
  worker:
    image: dockersamples/examplevotingapp_worker
    deploy:
      mode: global
Copy the code
  • placement

Specify Constraints and Preferences

version: '3' services: db: image: postgres deploy: placement: constraints: - node. Role = = manager - engine. Labels. The operatingsystem = = ubuntu 14.04 preferences: - spread: node. Labels. The zoneCopy the code
  • replicas

If the service is replicated (the default), you need to specify the number of containers running

version: '3'
services:
  worker:
    image: dockersamples/examplevotingapp_worker
    networks:
      - frontend
      - backend
    deploy:
      mode: replicated
      replicas: 6
Copy the code
  • resources

Configuring Resource Restrictions

Version: '3' services: redis: image: redis:alpine deploy: resources: limits: cpus: '0.50' memory: 50M Reservations: Cpus: '0.25' memory: 20 mCopy the code

In this example, the Redis service is limited to 50 MB of memory and 0.50 (50%) of available processing time (CPU), with 20 MB of memory and 0.25 CPU time reserved

  • restart_policy

Configure a container restart instead of restart

Condition: value can be none, on-failure, or any(default)

Delay: indicates the wait time for a restart attempt. The default value is 0

Max_attempts: The number of times the container tries to restart before giving up (default: never giving up). If the restart does not succeed in the configuration window, this attempt is not counted in the configuration max_attempts value. For example, if the max_Attempts value is 2 and the first attempt at a restart fails, more than two restarts may be attempted. Windows: The time to wait before deciding whether the restart was successful, specified as the duration (default: immediately).

version: "3"
services:
  redis:
    image: redis:alpine
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s
Copy the code
  • update_config

Configuring the update service for seamless rolling Update applications

Parallelism: The number of containers that are updated at one time

Delay: The wait time between updating a set of containers.

Failure_action: Continue, rollback, or pause can be performed if the update fails (default)

Monitor: monitor after each task update failure time (ns | us | | | s | m h ms) (the default is 0)

Max_failure_ratio: Acceptable failure rate during updates

Order: Update order setting, top-first (old task is stopped before new task is started), start-first (new task is started first and running tasks overlap briefly) (default stop-first)

Version: '3.4' services: vote: image: dockersamples/examplevotingapp_vote: before depends_on: - redis deploy: replicas: 2 update_config: parallelism: 2 delay: 10s order: stop-firstCopy the code

Several suboptions of Docker Stack desploy are not supported Build, cgroup_parent, container_name, Devices, TMPFS, external_links, inks, network_mode, restart, security_opt, stop_signal, and sysct Ls, userns_mode

16. devices

Set the mapping list, similar to the Docker client’s –device parameter:

devices:
  - "/dev/ttyUSB0:/dev/ttyUSB0"
Copy the code

17. depends_on

This option solves the boot order problem

One of the main benefits of using Compose is that you don’t need to start the container in any order, but if you start the container directly from top to bottom, you will inevitably fail because of container dependencies. For example, if the application container is started before the database container is started, then the application container will exit because the database cannot be found. In order to avoid this, we need to add a label called depends_on. This label resolves the dependency and startup order issue.

Specifying dependencies between services has two effects

Docker-compose up SERVICE: docker-compose up SERVICE: docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE: Docker-compose up SERVICE For example, the following container starts the Redis and DB services first, and then starts the Web service last:

version: '3'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres
Copy the code

Note that by default, starting a web service with docker-compose up Web also starts redis and DB because of the dependencies defined in the configuration file

18. dns

Custom DNS server, which has the same purpose as — DNS, can be a single value or a list

DNS: 8.8.8.8 DNS: -8.8.8.8-9.9.9.9Copy the code

19. dns_search

User-defined DNS search domains, which can be single values or lists

dns_search: example.com
dns_search:
  - dc1.example.com
  - dc2.example.com
Copy the code

20. tmpfs

Mount the temporary file directory inside the container, just like the run argument, and can be a single value or a list

tmpfs: /run
tmpfs:
  - /run
  - /tmp
Copy the code

21. entrypoint

There is a directive in the Dockerfile called the ENTRYPOINT directive that specifies the access point. You can define the access point in docker-compose. Yml, overriding the definition in Dockerfile:

entrypoint: /code/entrypoint.sh
Copy the code

Entrypoint can also be a list, with methods 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
Copy the code

21. env_file

Add environment variables from files. If you have already specified the compose FILE with docker-compose -f FILE, then the env_file path value is relative to the directory in which the FILE is located

However, variables set in the environment will override these values, whether they are undefined or None

env_file: .env
Copy the code

Or set multiple according to docker-compose. Yml:

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env
Copy the code

Declarations in the env_file environment configuration file are in the VAR=VAL format on each line, where those beginning with # are parsed as comments and ignored

Note the order * of the environment variable configuration list, as in the following example

docker_compose.yml

services:
  some-service:
    env_file:
      - a.env
      - b.env
Copy the code

A.e nv file

# a.env
VAR=1
Copy the code

B.e nv file

# b.env
VAR=2
Copy the code

For the same variable specified in the file a. filename but assigned a different value in the file B. filename, if b. filename is after a.filename as listed below, then the value just set in A.filename is overwritten by the value of the same variable in B. filename, in which case the $VAR value is hello. In addition, the environment variables in question are for the host’s Compose, and are not included in the build process if there is a build operation in the configuration file. The arG tag is preferred if you want to use variables in a build

22. environment

Add environment variables, either using an array or a dictionary. Unlike the env_file option above, this tag is similar to arg. It is used to set the variables in the mirror. It is used to store the variables in the mirror, which means that the starting container will also contain the variables. Generally, arG tag variables are only used during the build process. ENV in Dockerfile saves variables in images and containers, similar to docker run-e

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:
Copy the code

or

environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET
Copy the code

23. expose

The port is exposed, but is not mapped to the host and is accessed only by the connected service. This is the same as the EXPOSE directive in Dockerfile, which specifies which ports to EXPOSE, but only as a reference. Docker-compose. Yml’s port mapping is actually ports

expose:
 - "3000"
 - "8000"
Copy the code

24. external_links

Link to a container outside of docker-compose. Yml, and not even the one managed by the compose project file. The parameter format is similar to links

In order for Compose to connect to containers that are not defined in the docker-compose. Yml configuration file, a special label is required. External_links, which allows the containers in the Compose project to connect to containers that are external to the project configuration (as long as at least one of the external containers is connected to the same network as the services in the project).

Format is as follows

external_links:
 - redis_1
 - project_db_1:mysql
 - project_db_1:postgresql
Copy the code

25. extra_hosts

To add a host name tag, add some records to the /etc/hosts file, similar to –add-host in the Docker client:

Extra_hosts: - "somehost:162.242.195.82" - "otherhost:50.31.209.229"Copy the code

Entries with IP addresses and host names are created in the /etc/hosts internal container. Check the hosts inside the container after startup, for example:

162.242.195.82  somehost
50.31.209.229   otherhost
Copy the code

26.healthcheck

Check whether the container used by the test service is normal

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

Interval, timeout, and start_period are defined as durations

Test must be a string or a list, and if it is a list, the first item must be NONE, CMD, or cmd-shell; If it is a string, it is equivalent to specifying cmd-shell followed by the 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 || exit 1"]
test: curl -f https://localhost || exit
Copy the code

To disable all mirror check items, run disable:true, equivalent to test:[“NONE”]

healthcheck:
  disable: true
Copy the code

27. image

Starts the container from the specified image, which can be the repository, label, and image ID

Image: redis image: ubuntu 14.04 image: tutum/influxdb image: example-registry.com: 4000 / postgresql image: a4bc65fdCopy the code

If the mirror does not exist, Compose will automatically pull the mirror away

28. isolation

On Linux, only the default value is supported

29. labels

Use the Docker tag to add metadata to the container, using either an array or a dictionary. Similar to LABELS in Dockerfile:

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"
Copy the code

30.links

You can specify either the SERVICE name or the link ALIAS (SERVICE: ALIAS), which has the same effect as the Docker client –link, which will connect to the container of other services

web:
  links:
   - db
   - db:database
   - redis
Copy the code

The alias used is automatically created in /etc/hosts in the service container. Such as:

Db 172.12.2.186 database 172.12.2.187 RedisCopy the code

The corresponding environment variable will also be created

31. logging

Configuring the Log Service

Logging: driver: syslog options: syslog-address: "TCP ://192.168.0.42:123"Copy the code

The driver value specifies the logging driver for the server. The default value is json-file, the same as the –log-diver option

driver: "json-file"
driver: "syslog"
driver: "none"
Copy the code

Note: Only the json-file and journald drivers can get logs directly from docker-compose up and Docker-compose logs. Using any other method will not display any logs.

For optional values, you can use options to specify the logging options in logging

Driver: "syslog" options: syslog-address: "TCP ://192.168.0.42:123"Copy the code

The default driver json-file has the option to limit the amount of logs stored, so key-value pairs are used to get the maximum storage size as well as the minimum number of logs stored

options:
  max-size: "200k"
  max-file: "10"
Copy the code

The above instance will store log files until they reach max-size:200kB, and the number of individual log files to store is specified by the max-file value. As logs grow beyond the maximum limit, old log files are deleted to store new logs

Docker-compose. Yml example of limiting log storage

services:
  some-service:
    image: some-service
    logging:
      driver: "json-file"
      options:
        max-size: "200k"
        max-file: "10"
Copy the code

32. network_mode

Network mode, used similar to the –net option on the Docke client, format: service:[service name]

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

You can specify the network to use the service or container

33. networks

Joining a Specified network

services:
  some-service:
    networks:
     - some-network
     - other-network
Copy the code

34. aliases

Other containers on the same network can use the server name or alias to connect to containers for other services

services:
  some-service:
    networks:
      some-network:
        aliases:
         - alias1
         - alias3
      other-network:
        aliases:
         - alias
Copy the code

In the following example, web, Worker, and DB services are provided along with two networks, New and Legacy.

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:
Copy the code

The same service can have different aliases on different networks

35. Ipv4_address, ipv6_address

Specify a static IP address for the container of the service

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-subnet: 2001:3984:3989::/64Copy the code

36. PID

pid: "host"
Copy the code

Set the PID mode to the host PID mode to open the shared PID address space between the container and the host OS. Containers started with this flag can access and manipulate other containers on the host, and vice versa.

37. ports

Port mapping

  • SHORT grammar

You can specify a port in HOST:CONTAINER or a CONTAINER port (select a temporary HOST port), and the HOST will map the port randomly

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"
Copy the code

Note: When using HOST:CONTAINER to map ports, you may get an error if you use CONTAINER ports less than 60, because YAML will parse xx:yy as a number format in base 60, so it is recommended to use string format.

  • LONG grammar

The LONG syntax supports additional fields that the SHORT syntax does not

Target: indicates the port inside the container

Published: Indicates the public port

Protocol: Port protocol (TCP or UDP)

Mode: Load balancing is performed by using host for each node or a published host port or using ingress for cluster mode ports.

ports:
  - target: 80
    published: 8080
    protocol: tcp
    mode: host
Copy the code

38. secrets

Grant access to each service with secrets

  • SHORT grammar

    Version: “3.1” services: redis: image: redis:latest deploy: replicas: 1 secrets: -my_secret-my_other_secret secrets: my_secret: file: ./my_secret.txt my_other_secret: external: true

  • LONG grammar

The LONG syntax can add additional options

Source: Secret name

Target: The name of the file that needs to be loaded in /run/secrets/ in the service task container. This is the default value if source is not defined

Uid&gid: The UID or GID that owns the file in the service’s task container. If not specified, both default to 0.

Mode: permission to load files into the service’s task container in octal notation /run/secrets/. For example, 0444 stands for readable.

Version: "3.1" services: redis: image: redis:latest Deploy: replicas: 1 secrets: -source: my_secret target: redis_secret uid: '103' gid: '103' mode: 0440 secrets: my_secret: file: ./my_secret.txt my_other_secret: external: trueCopy the code

39. security_opt

Override the default label for each container. In simple terms, it is to manage the labels of all services, such as setting the value of user label for all services to user

security_opt:
  - label:user:USER
  - label:role:ROLE
Copy the code

40. stop_grace_period

Specify stop_signal before sending SIGKILL, the amount of time to wait if you try to stop the container (if it does not handle SIGTERM (or any specified stop signal))

stop_grace_period: 1s
stop_grace_period: 1m30s
Copy the code

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

41. stop_signal

Set another signal to stop the container. The SIGTERM is used by default to stop the container. To set another signal, use the stop_signal TAB:

stop_signal: SIGUSR
Copy the code

42. sysctls

Kernel parameters set in a container, which can be arrays or dictionaries

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

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

43. ulimits

Override the default limit for the container, either by setting the limit value to an integer or by specifying the soft/ Hard limit as a map

ulimits:
  nproc: 65535
  nofile:
    soft: 20000
    hard: 40000
Copy the code

44. userns_mode

userns_mode: "host"
Copy the code

45. volumes

To mount a directory or an existing data volume CONTAINER, use the format HOST:CONTAINER or HOST:CONTAINER:ro, where the data volume is read-only to the CONTAINER. This protects the file system of the HOST

Version: "3.2" services: web: image: nginx:alpine volumes: -type: volume source: mydata target: /data volume: nocopy: true - type: bind source: ./static target: /opt/app/static db: image: postgres:latest volumes: - "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock" - "dbdata:/var/lib/postgresql/data" volumes: mydata: dbdata:Copy the code

The data volume specified path for Compose can be relative, using. Or.. To specify a relative directory.

A data volume can be in one of the following formats:

Volumes: # Just specify a path and Docker will automatically create a data volume (this path is inside the container). - /opt/data:/var/lib/mysql # Use an absolute path for mounting data volumes - /opt/data:/var/lib/mysql # Use a relative path centered on the Compose configuration file to mount data volumes to the container. -./cache:/ TMP /cache # Use the relative path of the user (~/ indicates /home/< user directory >/ or /root/). - ~ / configs: / etc/configs / : ro # named after the existing data volume. - datavolume:/var/lib/mysqlCopy the code

If you don’t use the host’s path, you can specify a volume_driver

volume_driver: mydriver
Copy the code
  • SHORT grammar

You can specify a path on the HOST (HOST:CONTAINER) or access mode (HOST:CONTAINER:ro).

You can mount a relative path on the host that extends relative to the directory of the Compose profile in use. Relative paths should always start with. Or.. At the beginning

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
Copy the code
  • LONG grammar

The LONG syntax has additional fields

Type: installation type. The value can be Volume, bind, or TMPFS

Source: indicates the installation source. It is the directory for binding installation on the host or the name of the volume defined in the top-level volumes key. It is not applicable to TMPFS installation.

Target: indicates the path where the volume is installed in the container

Read_only: indicates that the volume is set to read-only

Bind: Configures additional binding options

Propagation: Propagation mode for binding

Volume: Configures additional volume options

Nocopy: indicates that data cannot be copied from the container when creating a volume

TMPFS: Configure additional TMPFS options

Size: indicates the size of TMPFS in bytes

Version: "3.2" services: web: image: nginx:alpine ports: - "80:80" volumes: -type: volume source: mydata target: /data volume: nocopy: true - type: bind source: ./static target: /opt/app/static networks: webnet: volumes: mydata:Copy the code

46. volumes_from

To mount a data volume from another container or service, the optional parameters are ro or :rw. The former indicates that the container is read-only and the latter indicates that the container is readable and writable to the data volume (the default is readable and writable).

volumes_from:
  - service_name
  - service_name:ro
  - container:container_name
  - container:container_name:rw
Copy the code

47. Volumes for services, clusters, and stack files

When using the service, cluster, and docker-stack.yml files, keep in mind that the task (container) supporting the service can be deployed on any node in the cluster, and may be a different node each time the service is updated.

In the absence of a named volume that specifies the source, Docker creates an anonymous volume for each task that supports the service. After the associated container is removed, the anonymous volume is not retained.

If you want the data to persist, use named volumes and volume drivers that recognize multiple hosts so that the data can be accessed from any node. Alternatively, set constraints on the service so that its tasks are deployed on the node that has the volume.

In the following example, a service called DB is defined in the docker-stack.yml file of the VotingApp example in Docker Labs. It is configured as a named volume to hold data on the population and runs only on nodes. Here’s the part from the file: DB Postgres Manager

Version: "3" services: db: image: postgres: 9.4 volumes: - db - data: / var/lib/postgresql/data networks: - backend deploy: placement: constraints: [node.role == manager]Copy the code

48. restart

The default value is no, meaning that the container will not be restarted under any circumstances; When the value is always, the container is always restarted; When the value is on-Failure, the container restarts when an on-failure error is reported and the container exits.

restart: "no"
restart: always
restart: on-failure
restart: unless-stopped
Copy the code

49. Other options

About labels: Cpu_shares, CPU_quota, CPuse, domainName, HOSTNAME, IPC, MAC_address, privileged, READ_only, SHM_SIZE, stdin_OPEN, tty, user, working_dir

All of the above is a single value tag, similar to the effect of using Docker Run

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 privileged: true read_only: true shm_size: 64M stdin_open: true tty: trueCopy the code

50. Duration

The format of some configuration options such as interval, a sub-option of check, and timeout

2.5s
10s
1m30s
2h32m
5h34m56s
Copy the code

The supported units are US, MS, S, M, and H

51. Specify a byte value

Some options such as the shm_size suboption of bulid

2b
1024kb
2048k
300m
1gb
Copy the code

Supported units are B, K, M, and G, or KB, MB, and GB. Currently, decimal values are not supported

52. extends

This tag can be used to extend another service. The extension content can be from the current file or from another file. In the case of the same service, the later one will selectively overwrite the original configuration

extends:
  file: common.yml
  service: webapp
Copy the code

Users can use this tag anywhere, as long as the tag contains the values file and service. The value of file can be a relative or absolute path. If the value of file is not specified, Compose will read information about the current YML file.