Detailed explanation of docker-compose template file instructions

Template files are the core of using compose, and there are many key instructions involved. Most of the instructions are similar to the meaning of docker run related parameters.
The default template file name is "docker-compose.yml" and the format is YAML format.

version: "3"

services:
  webapp:
    image: examples/web
    ports:
      - "80:80"
    volumes:
      - "/data"

Note: Each service must use the image instruction to specify the image or build instruction (dockerfile required) to automatically build and generate the required image.
If you use the build command, the options set in the Dockerfile (for example: CMD, EXPOSE, VOLUME, ENV, etc.) will be automatically obtained, and there is no need to repeat settings in compose.yml.

Instruction meaning and usage
build
specifies the file directory path where the Dockerfile is located (it can be an absolute path or a relative path) and needs to be in the path of docker-compose.yml.
Compose will use it to automatically build this image and then use it.

version: '3'
services:

  webapp:
    build: ./dir

You can also use the context command to specify the path to the folder where the Dockerfile is located.
Use the dockerfile instruction to specify the Dockerfile file name.
Use the arg instruction to specify the variables when building the image.

version: '3'
services:

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

Use cache_from to specify the cache for building the image

build:
  context: .
  cache_from:
    - alpine:latest
    - corp/web_app:3.14

cap_add, cap_drop
specify the kernel capacity (capacity) allocation of the container.

For example, let the container have all the capabilities can be specified as:

cap_add:
  - ALL

The ability to remove NET_ADMIN can be specified as:

cap_drop:
  - NET_ADMIN

command
overrides the command executed by default after the container is started.

command: echo "hello world"

configs
are only used in swarm mode

cgroup_parent
specifies the parent cgroup group, which means it will inherit the resource limit of the group.
For example, a cgroup group name is created cgroups_1.

cgroup_parent: cgroups_1

container_name
specifies the name of the container. By default, the format of project name_service name_serial number will be used.

container_name: docker-web-container

Note: After specifying the container name, the service cannot be scaled, because Docker does not allow multiple containers to have the same name.

Deploy
is only used for Swarm mode
devices to
specify the device mapping relationship.

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

depends_on
solves the problem of container dependency and startup sequence. In the following example, redis db will be started before web

version: '3'

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

  redis:
    image: redis

  db:
    image: postgres

Note: The web service does not wait for the redis db "complete startup" to start.

dns
custom DNS server. It can be a value or a list.

dns: 8.8.8.8

dns:
  - 8.8.8.8
  - 114.114.114.114

dns_search
configures the DNS search domain. It can be a value or a list.

dns_search: example.com

dns_search:
  - domain1.example.com
  - domain2.example.com

tmpfs
mounts a tmpfs file system to the container.

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

env_file
obtains environment variables from a file, which can be a separate file path or list.

If you specify the Compose template file by docker-compose -f FILE, the path of the variable in env_file will be based on the template file path.

If there is a variable name that conflicts with the environment directive, follow the convention, and the latter shall prevail.

env_file: .env

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

Each line in the environment variable file must conform to the format, and comment lines starting with # are supported.

# common.env: Set development environment
PROG_ENV=development

environment
sets environment variables. You can use two formats: array or dictionary.

A variable with only a given name will automatically obtain the value of the corresponding variable on the host running Compose, which can be used to prevent unnecessary data leakage.

environment:
  RACK_ENV: development
  SESSION_SECRET:

environment:
  - RACK_ENV=development
  - SESSION_SECRET

If true|false, yes|no and other words expressing boolean meaning are used in the variable name or value, it is best to put it in quotation marks to prevent YAML from automatically parsing certain content into the corresponding boolean semantics. These specific words include

y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF

Expose the
port, but it is not mapped to the host, only accessed by connected services.

Only internal ports can be specified as parameters

expose:
 - "3000"
 - "8000"

external_links
Note: It is not recommended to use this command.
Link to a container outside docker-compose.yml, not even an external container managed by Compose.

external_links:
 - redis_1
 - project_db_1:mysql
 - project_db_1:postgresql

extra_hosts is
similar to the --add-host parameter in Docker, which specifies additional host name mapping information.

extra_hosts:
 - "googledns:8.8.8.8"
 - "dockerhub:52.1.157.61"

The following two entries will be added to the /etc/hosts file in the service container after startup.

8.8.8.8 googledns
52.1.157.61 dockerhub

healthcheck
uses commands to check whether the container is healthy.

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

image is
specified as the image name or image ID. If the mirror does not exist locally, Compose will try to pull the mirror.

image: ubuntu
image: orchardup/postgresql
image: a4bc65fd

Labels
add Docker metadata information for the container. For example, you can add auxiliary information to the container.

labels:
  com.startupteam.description: "webapp for a startup team"
  com.startupteam.department: "devops department"
  com.startupteam.release: "rc3 for v1.0"

links
Note: This directive is not recommended.
Link to containers in other services. Either service name (also used as an alias) or service name: service alias (SERVICE:ALIAS) format is acceptable.

links:
- db
- db:database
- redis

logging
configures logging options.

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

Currently, three log driver types are supported.

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

options Configure the relevant parameters of the log driver.

options:
  max-size: "200k"
  max-file: "10"

E.g:

nginx:
  image: nginx:1.12.1
  restart: always
  logging:
    driver: "json-file"
    options:
      max-size: "5g"

Or add when the command line starts:

docker run -d --log-opt max-size=1g nginx

Or modify the docker daemon file:

{
    
    
        "log-opts": {
    
    
                "max-size": "1G"
        }
}

network_mode
sets the network mode. Use the same value as the --network parameter of docker run.

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

networks
Configure the network to which the container is connected.

version: "3"
services:

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

networks:
  some-network:
  other-network:

E.g:

 version: '3'
                services: 
                    nginx: 
                        image: nginx:v1
                        container_name: mynginx
                        command: ip addr
                        networks: 
                            app_web:                                # 调用 networks 定义的 app_we 网络
                            ipv4_address: 172.18.0.4				# IP V4 格式
                networks:
                    app_web:
                        driver: bridge								# 指定日志记录驱动程序
                        ipam:							# 自定义 IPAM 配置. 这是一个具有多个属性的对象, 每个属性都是可选的
                            driver: default				# IPAM 驱动程序, bridge 或者 default
                            config:						# 配置项
                                - subnet: 172.18.0.0/24	#子网,网段

The pid
shares the process namespace with the host system. The containers with this option turned on, as well as between the container and the host system, can access and operate each other through the process ID.

pid: "host"

ports
expose port information.
Use host port: container port (HOST:CONTAINER) format, or just specify the port of the container (the host will randomly select the port).

ports:
 - "3000"
 - "8000:8000"
 - "49100:22"
 - "127.0.0.1:8001:8001"

Note: When using the HOST:CONTAINER format to map ports, if you use a container port less than 60 and it is not enclosed in quotation marks, you may get wrong results, because YAML will automatically parse the number format of xx:yy as 60 hexadecimal . In order to avoid this problem, it is recommended that all numeric strings adopt the string format enclosed in quotation marks.

Secrets
store sensitive data, such as the mysql service password.

version: "3.1"
services:

mysql:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
  secrets:
    - db_root_password
    - my_other_secret

secrets:
  my_secret:
    file: ./my_secret.txt
  my_other_secret:
    external: true

security_opt
specifies the default attributes (user, role, type, level, etc.) of the container template label mechanism. For example, configure the user name and role name of the label.

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

stop_signal
sets another signal to stop the container. SIGTERM is used by default to stop the container.

stop_signal: SIGUSR1

sysctls
configures container kernel parameters.

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

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

ulimits
specifies the ulimits limit value of the container.

For example, the specified maximum number of processes is 65535, and the specified number of file handles is 20000 (soft limit, the application can be modified at any time, cannot exceed the hard limit) and 40000 (system hard limit, only root user can increase).

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


The mounting path setting of the volumes data volume. It can be set to host path (HOST:CONTAINER) or data volume name (VOLUME:CONTAINER), and access mode (HOST:CONTAINER:ro) can be set.

The path in this instruction supports relative paths.

volumes:
 - /var/lib/mysql
 - cache/:/tmp/cache
 - ~/configs:/etc/configs/:ro

If the path is the data volume name, the data volume must be configured in the file.

version: "3"

services:
  my_src:
    image: mysql:8.0
    volumes:
      - mysql_data:/var/lib/mysql

volumes:
  mysql_data:

Other instructions
In addition, there are instructions including domainname, entrypoint, hostname, ipc, mac_address, privileged, read_only, shm_size, restart, stdin_open, tty, user, working_dir, etc., which are basically the same as the corresponding parameters in docker run.

Specify the entry file to be executed after the service container is started.
In fact, it is the ENTRYPOINT and CMD in the dockerfile.

entrypoint: /code/entrypoint.sh

Specify the user name of the application running in the container.

user: nginx

Specify the working directory in the container.

working_dir: /code

Search for domain names, host names, mac addresses, etc. in the specified container.

domainname: your_website.com
hostname: test
mac_address: 08-00-27-00-0C-0A

Allow some privileged commands to run in the container.

privileged: true

Specifies that the restart strategy after the container exits is always restart. This command is very effective to keep the service running at all times. It is recommended to configure it as always or unless-stopped in a production environment.

restart: always

Mounting the root file system of the container in read-only mode means that the contents of the container cannot be modified.

read_only: true

Open the standard input, you can accept external input.

stdin_open: true

Simulate a pseudo terminal.

tty: true

Read Variables
Compose template files support dynamic reading of the host's system environment variables and variables in the .env file in the current directory.
For example, the following Compose file will read the value of the variable ${MONGO_VERSION} from the environment in which it is run and write it into the executed instruction.
If MONGO_VERSION=3.2 docker-compose up is executed, a mongo:3.2 mirrored container will be started; if MONGO_VERSION=2.8 docker-compose up is executed, a mongo:2.8 mirrored container will be started.

If there is a .env file in the current directory, the variables will be read from this file when the docker-compose command is executed.

Create a new .env file in the current directory and write the following content.

# 支持 # 号注释
MONGO_VERSION=3.6

Executing docker-compose up will start a mongo:3.6 mirrored container.
Only some commonly used options are introduced here, and others need to consult the official documents to learn how to use them.

Help document:
https://yeasy.gitbooks.io/docker_practice/compose/compose_file.html

Guess you like

Origin blog.csdn.net/ZhanBiaoChina/article/details/105467835