20230318--Docker Compose设置文件详解

开发者 2024-9-19 01:24:10 36 0 来自 中国
Docker Compose设置文件是Docker Compose的核心,用于界说服务、网络和数据卷。格式为YAML,默认路径为./docker-compose.yml,可以利用.yml或.yaml扩展名,现在Compose设置文件格式的最新版本为V3。

一)version

Docker Compose版本紧张有1, 2, 2.x, and 3.x,以下表格是docker-compose支持的docker版本。
Docker Compose file formatDocker Engine release3.819.03.0+3.718.06.0+3.618.02.0+3.517.12.0+3.417.09.0+3.317.06.0+3.217.04.0+3.11.13.1+3.01.13.0+2.417.12.0+2.317.06.0+2.21.13.0+2.11.12.0+2.01.10.0+# docker-compose versiondocker-compose version 1.26.0, build d4451659docker-py version: 4.2.1CPython version: 3.7.7OpenSSL version: OpenSSL 1.1.0l  10 Sep 20191.Version 2.x

通过YAML的根设置项version来指定,具体设置如version: '2'或version: '2.1'等。
必须在Compose设置文件根选项指定版本号,而且主版本数字为2,且全部服务必须在services设置项下声明。1.6.0+版本的Compose都支持V2,Docker Engine的版本须要1.10.0+版本。
支持数据卷和网络的设置。
默认环境下,每个容器都加入了应用范围的默认网络,而且可以在与服务名称雷同的主机名下发现。很洪流平上links不是须要的。
V2中加入了环境变量更换。
2.Version 3.x

最新版本,也是保举利用版本,推出该版的目的是为了在Compose和Docker Engine的swarm模式之间形成交织兼容。通过YAML的根设置项version来指定,具体设置如version: '3'或version: '3.1'等。
在指定Compose设置文件要利用的版本时,需同时指定主版本数字和次版本数字。假如未给定次版本数字,则默认利用0而不是最新版本,因此将不支持再更高版本中才加入的新功能。比如version: '3',利用的是3.0版本而不是现在最新的3.9版本
二)networks

通过顶层networks设置项可以指定要创建的网络。
# docker network inspect docker_redis_network[    {        "Name": "docker_redis_network",        "Id": "74f09926f4d034f2ae63ff1a46590d883562e711814a0dcce7e683284e407c31",        "Created": "2023-03-13T09:50:44.80943824+08:00",        "Scope": "local",        "Driver": "bridge",        "EnableIPv6": false,        "IPAM": {            "Driver": "default",            "Options": null,            "Config": [                {                    "Subnet": "172.21.0.0/16",                    "Gateway": "172.21.0.1"                }            ]        },        "Internal": false,        "Attachable": true,        "Ingress": false,        "ConfigFrom": {            "Network": ""        },        "ConfigOnly": false,        "Containers": {            "91abfc78b2fecc20f5fe2fdfdd575b0b30b9a5e1a3ec8fb459a336fb287e9be7": {                "Name": "docker_redis_1",                "EndpointID": "812224986f60105aa06b201b47a4568a38379e2a07ae5f942c3fcb6125b8aa5a",                "MacAddress": "02:42:ac:15:00:02",                "IPv4Address": "172.21.0.2/16",                "IPv6Address": ""            }        },        "Options": {},        "Labels": {            "com.docker.compose.network": "redis_network",            "com.docker.compose.project": "docker",            "com.docker.compose.version": "1.26.0"        }    }]1.Name

为该网络设置一个自界说名称。
networks:  network1:    name: my-app-net2.Driver

指定该网络所要利用的驱动。默认驱动取决于所利用的Docker Engine的设置方式,但是在大多数环境下,单个主机上用的bridge,Swarm上用的overlay。
docker网络模式紧张有Host、Container、None、Bridge、overlay
Host:容器不会假造出自己的网卡、设置主机的IP,而是利用宿主机的IP和端口;
Container:创建的容器不会创建自己的网卡,设置自己的IP,而是和一个指定的容器共享IP、端口的范围;
None:该模式关闭了容器的网络功能;
Bridge:默以为该模式,桥接,此模式会为每一个容器分配,设置IP等,并将容器毗连到假造网桥docker0,通过docker0 网桥以及iptables nat表设置与宿主机通讯;
overlay:overlay驱动在一个swarm中的多个节点之间创建一个定名网络。
networks:  network1:    driver: overlay3.EnableIPv6

在该网络上启用IPv6网络(假如要利用enable_ipv6设置项,则须要利用V2版Compose设置文件)。
4.IPAM

指定自界说IPAM设置。
有以下设置选项:
driver:自界说IPAM驱动以代替默认驱动。
config:包罗零个或多个设置块的列表,每个设置块可以有以下设置选项。
subnet:设置表现网段的CIDR格式的子网。
gateway:设置表现网段的子网掩码。仅适用于V2版Compose设置文件
networks:  network1:    ipam:      driver: default      config:        - subnet: 172.28.0.0/165.Internal

指定是否创建一个与外部隔离的overlay网络。默认环境下,Docker也会将桥接网络毗连到它以提供外部毗连。假如要创建一个与外部隔离的overlay网络,需将此设置项设置为true。
6.Attachable

指定是否答应除服务之外的独立容器毗连到该网络。仅在driver设置为overlay时利用。假如设置为true,则除了服务之外的独立容器也可以毗连到该网络。假如独立容器毗连到了overlay网络,那它可以与那些也从其他Docker保卫进程毗连到overlay网络的服务和独立容器举行通讯。
networks:  mynet1:    driver: overlay    attachable: true7.Options

以键值对的情势指定用来转达给该网络所利用的驱动的列表选项。这些选项取决于驱动,可以参考驱动步伐文档。
networks:   mynet1:     driver_opts:       foo: "bar"       baz: 18.Labels

将元数据以标签的情势添加到容器中。可以利用数组或字典两种格式。
networks:  mynet1:    labels:      - "com.example.description=Financial transaction network"      - "com.example.department=Finance"      - "com.example.label-with-empty-value"9.external

指定该网络是否是外部网络。假如设置为true,则指定该网络是在Compose外部创建的。由于docker-compose up不会实行创建该网络,假如该网络不存在则会引发错误。在3.3及以下版本的Compose设置文件格式中,external设置项不能与包罗driver、driver_opts、ipam和internal等在内的其他网络设置项同时利用,在3.4及以上版本中则没有此限制。
三)volumes

在services中可以声明并直接创建数据卷,但是从团体规划以及实现多个服务重用的须要,通过顶层volumes设置项界说数据卷更规范,而且顶层volumes设置项界说的数据卷可以利用命令行或API轻松举行检索和查抄。
docker cli检察界说的数据卷# docker volume inspect docker_redis_vol[    {        "CreatedAt": "2023-03-13T09:50:45+08:00",        "Driver": "local",        "Labels": {            "com.docker.compose.project": "docker",            "com.docker.compose.version": "1.26.0",            "com.docker.compose.volume": "redis_vol"            "com.example.department": "IT/Ops",            "com.example.description": "Database volume",            "com.example.label-with-empty-value": ""        },        "Mountpoint": "/var/lib/docker/volumes/docker_redis_vol/_data",        "Name": "docker_redis_vol",        "Options": null,        "Scope": "local"    }]1.Driver

指定该数据卷所要利用的数据卷驱动。默以为Docker Engine中设置利用的无论哪种驱动,大多数环境下为local驱动。假如驱动不可用,则引擎会在docker-compose up实行创建数据卷时返回一个错误。
volumes:  redis_vol:    driver: local2.Labels

将元数据以标签的情势添加到容器中。可以利用数组或字典两种格式。
volumes:  redis_vol:    labels:      - "com.example.description=Database volume"      - "com.example.department=IT/Ops"      - "com.example.label-with-empty-value"3.Name

为该数据卷设置一个自界说名称。
volumes:  redis_vol:    name: my-app-data4.Options

以键值对的情势指定用来转达给该数据卷所利用的数据卷驱动的列表选项。
挂在nfs文件目次/docker/examplevolumes:  redis_vol:    driver_opts:      type: "nfs"      o: "addr=10.40.0.199,nolock,soft,rw"      device: ":/docker/example"5.external

指定该数据卷是否是外部数据卷。假如设置为true,则指定该数据卷是在Compose外部创建的。由于docker-compose up不会实行创建该数据卷,假如该数据卷不存在则会引发错误。在3.3及以下版本的Compose设置文件格式中,external设置项不能与包罗driver、driver_opts和labels在内的其他数据卷设置项同时利用,在3.4及以上版本中则没有此限制。
四)services

一个比力完备的docker service具体设置内容# docker inspect bf76418f4ab6[    {        "Id": "bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980",        "Created": "2023-03-16T23:29:10.470087985Z",        "ath": "docker-entrypoint.sh",        "Args": [            "redis-server",            "/etc/redis/redis.conf"        ],        "State": {            "Status": "running",            "Running": true,            "aused": false,            "Restarting": false,            "OOMKilled": false,            "Dead": false,            "id": 1858657,            "ExitCode": 0,            "Error": "",            "StartedAt": "2023-03-16T23:29:11.643425486Z",            "FinishedAt": "0001-01-01T00:00:00Z",            "Health": {                "Status": "unhealthy",                "FailingStreak": 11,                "Log": [                    {                        "Start": "2023-03-17T07:39:42.421770498+08:00",                        "End": "2023-03-17T07:39:42.520933467+08:00",                        "ExitCode": -1,                        "Output": "OCI runtime exec failed: exec failed: unable to start container process: exec: \"curl\": executable file not found in $PATH: unknown"                    },                    {                        "Start": "2023-03-17T07:41:12.527300168+08:00",                        "End": "2023-03-17T07:41:12.618813081+08:00",                        "ExitCode": -1,                        "Output": "OCI runtime exec failed: exec failed: unable to start container process: exec: \"curl\": executable file not found in $PATH: unknown"                    },                    {                        "Start": "2023-03-17T07:42:42.624743521+08:00",                        "End": "2023-03-17T07:42:42.721798285+08:00",                        "ExitCode": -1,                        "Output": "OCI runtime exec failed: exec failed: unable to start container process: exec: \"curl\": executable file not found in $PATH: unknown"                    },                    {                        "Start": "2023-03-17T07:44:12.725901737+08:00",                        "End": "2023-03-17T07:44:12.800762299+08:00",                        "ExitCode": -1,                        "Output": "OCI runtime exec failed: exec failed: unable to start container process: exec: \"curl\": executable file not found in $PATH: unknown"                    },                    {                        "Start": "2023-03-17T07:45:42.80707081+08:00",                        "End": "2023-03-17T07:45:42.958008502+08:00",                        "ExitCode": -1,                        "Output": "OCI runtime exec failed: exec failed: unable to start container process: exec: \"curl\": executable file not found in $PATH: unknown"                    }                ]            }        },        "Image": "sha256:7614ae9453d1d87e740a2056257a6de7135c84037c367e1fffa92ae922784631",        "ResolvConfPath": "/var/lib/docker/containers/bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980/resolv.conf",        "HostnamePath": "/var/lib/docker/containers/bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980/hostname",        "HostsPath": "/var/lib/docker/containers/bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980/hosts",        "LogPath": "/var/lib/docker/containers/bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980/bf76418f4ab69dff5892b1f53adcddbb5add2b4ed7b610359c1405a4dc7ab980-json.log",        "Name": "/docker_redis_1",        "RestartCount": 0,        "Driver": "overlay2",        "latform": "linux",        "MountLabel": "",        "rocessLabel": "",        "AppArmorProfile": "",        "ExecIDs": null,        "HostConfig": {            "Binds": [                "docker_redis_vol:/data:rw",                "/root/docker/redis.conf:/etc/redis/redis.conf:rw"            ],            "ContainerIDFile": "",            "LogConfig": {                "Type": "json-file",                "Config": {                    "max-file": "10",                    "max-size": "200k"                }            },            "NetworkMode": "docker_redis_network",            "ortBindings": {                "6379/tcp": [                    {                        "HostIp": "",                        "HostPort": "6379"                    }                ]            },            "RestartPolicy": {                "Name": "always",                "MaximumRetryCount": 0            },            "AutoRemove": false,            "VolumeDriver": "",            "VolumesFrom": [],            "CapAdd": null,            "CapDrop": null,            "CgroupnsMode": "host",            "Dns": [                "8.8.8.8"            ],            "DnsOptions": null,            "DnsSearch": [                "example.com"            ],            "ExtraHosts": [                "somehost:162.242.195.82",                "otherhost:50.31.209.229"            ],            "GroupAdd": null,            "IpcMode": "shareable",            "Cgroup": "",            "Links": null,            "OomScoreAdj": 0,            "idMode": "host",            "rivileged": false,            "ublishAllPorts": false,            "ReadonlyRootfs": false,            "SecurityOpt": [                "label:user:USER",                "label:role:ROLE",                "label=disable"            ],            "Tmpfs": {                "/run": ""            },            "UTSMode": "",            "UsernsMode": "host",            "ShmSize": 67108864,            "Sysctls": {                "net.core.somaxconn": "1024",                "net.ipv4.tcp_syncookies": "0"            },            "Runtime": "runc",            "ConsoleSize": [                0,                0            ],            "Isolation": "default",            "CpuShares": 0,            "Memory": 0,            "NanoCpus": 0,            "CgroupParent": "",            "BlkioWeight": 0,            "BlkioWeightDevice": null,            "BlkioDeviceReadBps": null,            "BlkioDeviceWriteBps": null,            "BlkioDeviceReadIOps": null,            "BlkioDeviceWriteIOps": null,            "CpuPeriod": 0,            "CpuQuota": 0,            "CpuRealtimePeriod": 0,            "CpuRealtimeRuntime": 0,            "CpusetCpus": "",            "CpusetMems": "",            "Devices": null,            "DeviceCgroupRules": null,            "DeviceRequests": null,            "KernelMemory": 0,            "KernelMemoryTCP": 0,            "MemoryReservation": 0,            "MemorySwap": 0,            "MemorySwappiness": null,            "OomKillDisable": false,            "idsLimit": null,            "Ulimits": [                {                    "Name": "nproc",                    "Hard": 65535,                    "Soft": 65535                },                {                    "Name": "nofile",                    "Hard": 40000,                    "Soft": 20000                }            ],            "CpuCount": 0,            "CpuPercent": 0,            "IOMaximumIOps": 0,            "IOMaximumBandwidth": 0,            "MaskedPaths": [                "/proc/asound",                "/proc/acpi",                "/proc/kcore",                "/proc/keys",                "/proc/latency_stats",                "/proc/timer_list",                "/proc/timer_stats",                "/proc/sched_debug",                "/proc/scsi",                "/sys/firmware"            ],            "ReadonlyPaths": [                "/proc/bus",                "/proc/fs",                "/proc/irq",                "/proc/sys",                "/proc/sysrq-trigger"            ],            "Init": true        },        "GraphDriver": {            "Data": {                "LowerDir": "/var/lib/docker/overlay2/fdd65a7b3dd4e2d3904fe5d38656a6ef209f838f7fb4eff82387cf58e63fd665-init/diff:/var/lib/docker/overlay2/f40df8bee5df02139b8842b49df50204a209f20ea55e90c5e679155d47f14052/diff:/var/lib/docker/overlay2/f262ebf707b84c4aaf15ad95fb5f3762a3de9f00e3fa80eb200e7d2974b47a71/diff:/var/lib/docker/overlay2/d7238b1c8820c4cc6345df77afe0f8a7d7074dee0d1483b78f794aca4730ab5c/diff:/var/lib/docker/overlay2/fea75636a73398782f4ce75ae4f2649857dcda914ac1a8978ede85dc612b7dd6/diff:/var/lib/docker/overlay2/03388075cf9f8ecaab7c1f0cd70bac5ca3cde5398b5b6910ff56400cac7d7c66/diff:/var/lib/docker/overlay2/04f6770d7d1240e23c1dff9a8302a998ecd99506d465de78ecc42463282538d3/diff",                "MergedDir": "/var/lib/docker/overlay2/fdd65a7b3dd4e2d3904fe5d38656a6ef209f838f7fb4eff82387cf58e63fd665/merged",                "UpperDir": "/var/lib/docker/overlay2/fdd65a7b3dd4e2d3904fe5d38656a6ef209f838f7fb4eff82387cf58e63fd665/diff",                "WorkDir": "/var/lib/docker/overlay2/fdd65a7b3dd4e2d3904fe5d38656a6ef209f838f7fb4eff82387cf58e63fd665/work"            },            "Name": "overlay2"        },        "Mounts": [            {                "Type": "volume",                "Name": "docker_redis_vol",                "Source": "/var/lib/docker/volumes/docker_redis_vol/_data",                "Destination": "/data",                "Driver": "local",                "Mode": "rw",                "RW": true,                "Propagation": ""            },            {                "Type": "bind",                "Source": "/root/docker/redis.conf",                "Destination": "/etc/redis/redis.conf",                "Mode": "rw",                "RW": true,                "Propagation": "rprivate"            }        ],        "Config": {            "Hostname": "bf76418f4ab6",            "Domainname": "",            "User": "",            "AttachStdin": false,            "AttachStdout": false,            "AttachStderr": false,            "ExposedPorts": {                "6379/tcp": {}            },            "Tty": false,            "OpenStdin": false,            "StdinOnce": false,            "Env": [                "affinity:container==c3d082140a07e61738084405939a53abd90ad6d56450d70ca4347e3307db167c",                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",                "GOSU_VERSION=1.12",                "REDIS_VERSION=6.2.6",                "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz",                "REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab"            ],            "Cmd": [                "redis-server",                "/etc/redis/redis.conf"            ],            "Healthcheck": {                "Test": [                    "CMD",                    "curl",                    "-f",                    "http://localhost"                ],                "Interval": 90000000000,                "Timeout": 10000000000,                "Retries": 3            },            "Image": "redis:latest",            "Volumes": {                "/data": {},                "/etc/redis/redis.conf": {}            },            "WorkingDir": "/data",            "Entrypoint": [                "docker-entrypoint.sh"            ],            "OnBuild": null,            "Labels": {                "com.docker.compose.config-hash": "09aaa807a7358703e1a719294b4167daaf9bc7845d27af4dc753fa3407204e78",                "com.docker.compose.container-number": "1",                "com.docker.compose.oneoff": "False",                "com.docker.compose.project": "docker",                "com.docker.compose.project.config_files": "docker-compose.yml",                "com.docker.compose.project.working_dir": "/root/docker",                "com.docker.compose.service": "redis",                "com.docker.compose.version": "1.26.0",                "com.example.department": "Finance",                "com.example.description": "Accounting webapp",                "com.example.label-with-empty-value": ""            },            "StopSignal": "SIGUSR1",            "StopTimeout": 90        },        "NetworkSettings": {            "Bridge": "",            "SandboxID": "275e877c39e11427ae85da409e87d6853571c86a215293f1367c7e8d9521b81a",            "HairpinMode": false,            "LinkLocalIPv6Address": "",            "LinkLocalIPv6PrefixLen": 0,            "Ports": {                "6379/tcp": [                    {                        "HostIp": "0.0.0.0",                        "HostPort": "6379"                    },                    {                        "HostIp": "::",                        "HostPort": "6379"                    }                ]            },            "SandboxKey": "/var/run/docker/netns/275e877c39e1",            "SecondaryIPAddresses": null,            "SecondaryIPv6Addresses": null,            "EndpointID": "",            "Gateway": "",            "GlobalIPv6Address": "",            "GlobalIPv6PrefixLen": 0,            "IPAddress": "",            "IPPrefixLen": 0,            "IPv6Gateway": "",            "MacAddress": "",            "Networks": {                "docker_redis_network": {                    "IPAMConfig": null,                    "Links": [                        "redis_1:redis_1"                    ],                    "Aliases": [                        "bf76418f4ab6",                        "redis",                        "alias3",                        "alias1"                    ],                    "NetworkID": "74f09926f4d034f2ae63ff1a46590d883562e711814a0dcce7e683284e407c31",                    "EndpointID": "caf62eb67f9f47fe3de0cb65900cfcead21e3c6d935778e22874953a1c9be9f3",                    "Gateway": "172.21.0.1",                    "IPAddress": "172.21.0.2",                    "IPPrefixLen": 16,                    "IPv6Gateway": "",                    "GlobalIPv6Address": "",                    "GlobalIPv6PrefixLen": 0,                    "MacAddress": "02:42:ac:15:00:02",                    "DriverOpts": null                }            }        }    }]1.build

在创建服务时利用
services:  webapp:    build: ./dir1)context

指定包罗Dockerfile的目次路径或git堆栈url。该目次是发送给Docker保卫进程(Daemon)的构建上下文(context)。当设置的值是相对路径时,它将被解释为相对于Compose设置文件的路径。
services:  webapp:    build:      context: ./dir2)dockerfile

指定Dockerfile文件。Compose会利用指定的Dockerfile文件构建镜像,但必须要指定构建上下文路径。
services:  webapp:    build:      context: ./dir      dockerfile: Dockerfile-alternate3)args

添加构建参数,这些只能在构建过程中访问的环境变量。
services:  webapp:    build:      context: ./dir      dockerfile: Dockerfile-alternate      args:        - buildno=1        - gitcommithash=cdc3b194)cache_from

指定缓存剖析镜像列表
services:  webapp:    build:      context: ./dir      cache_from:        - alpine:latest        - corp/web_app:3.145)labels

将元数据以标签的情势添加到天生的镜像中。可以利用数组或字典两种格式。保举利用反向DNS写法以克制和其他应用的标签辩论。
services:  webapp:    build:      context: ./dir      labels:        com.example.description: "Accounting webapp"        com.example.department: "Finance"        com.example.label-with-empty-value: ""6)network

设置容器网络毗连以获取构建过程中的RUN指令。
services:  webapp:    build:      context: ./dir      network: custom_network_17)shm_size(shared memory size)

指定容器的/dev/shm分区巨细。指定的值为表现字节数的整数值或表现字节值的字符串。
services:  webapp:    build:      context: ./dir      shm_size: 100000008)target

指定在Dockerfile中界说的构建阶段,即镜像只构建到指定阶段(dev、test、prod等)就停止构建。
services:  webapp:    build:      context: ./dir      target: prod2.cap_add、cap_drop

添加或删除容器内核本领(capability)
容器拥有全部内核本领services:  webapp:    build:      cap_add:        - ALL容器拥有删除NET_ADMIN和SYS_ADMIN本领services:  webapp:    cap_drop:      - NET_ADMIN      - SYS_ADMIN# docker inspect --format='{{.Name}}|''{{.HostConfig.CapAdd}}|''{{ .HostConfig.CapDrop}}' 91abfc78b2fe/docker_redis_1|[]|[]3.cgroup_parent

为容器指定一个可选的父控制组。
services:  webapp:    cgroup_parent: m-executor-abcd# docker inspect --format='{{.Name}}|''{{.HostConfig.CgroupParent}}' 91abfc78b2fe/docker_redis_1|4.command

覆盖容器启动后默认实行的命令。可以写成字符串情势。
services:  webapp:    command: bundle exec thin -p 3000# docker inspect --format='{{.Name}}|''{{.Config.Cmd}}' 91abfc78b2fe/docker_redis_1|[redis-server /etc/redis/redis.conf]5.config

为每个服务授予对设置(configs)的访问权限。支持short和long两种格式的语法。
注意:该设置(config)必须已存在大概在堆栈文件顶层configs设置项中界说,否则堆栈摆设将失败。
1)Short syntax

Short syntax仅指定config名称来授予容器访问config的权限并将其挂载到容器的/<config_name>上。source名称和目的挂载点都设置为config名称。
services:  redis:    image: redis:latest    deploy:      replicas: 1    configs:      - my_config      - my_other_configconfigs:  my_config:    file: ./my_config.txt  my_other_config:    external: true2)Long syntax

Long syntax提供了在服务的使命容器内怎样创建config的更多粒度:
source:Docker中存在的config名称。
target:指定要挂载到服务的使命容器的文件的路径加名称。假如未指定,默以为/。
uid和gid:指定服务的使命容器所拥有的该文件的UID或GID。假如在LInux中未指定,两者都默以为0。不支持Windows。
mode:以八进制表现法指定要挂载到服务的使命容器的文件权限。比方,0444代表可读。默认值就为0444。config内容已挂载到临时文件体系中,以是不可写,假如设置了可写位将被忽略。可以设置可实行位。假如不熟悉UNIX文件权限模式,可以利用权限盘算器 。
services:  redis:    image: redis:latest    deploy:      replicas: 1    configs:      - source: my_config        target: /redis_config        uid: '103'        gid: '103'        mode: 0440configs:  my_config:    file: ./my_config.txt  my_other_config:    external: true6.container_name

指定自界说容器的名称,而不是利用默认名称。由于Docker容器的名称必须唯一,以是为一个服务指定了自界说容器名称后,该服务不能举行扩展。假如实举动该服务扩容将会导致错误。
services:  webapp:    container_name: my-web-container# docker inspect --format='{{.Name}}' 91abfc78b2fe/docker_redis_17.credential_spec

设置托管服务帐户的根据规格(credential spec)。此选项仅用于利用Windows容器的服务。credential_spec设置必须接纳file://或registry://格式。利用file:时,引用的文件必须存在于Docker数据目次的CredentialSpecs子目次中,在Windows上,Docker数据目次默以为C:\ProgramData\Docker\。以下示例从名为C:\ProgramData\Docker\CredentialSpecs\my-credential-spec.json的文件加载根据规格:
services:  myservice:    image: myimage:latest    credential_spec:      file: my-credential-spec.jsonservices:  myservice:    image: myimage:latest    credential_spec:      config: my_credential_spec configs:  my_credentials_spec:    file: ./my-credential-spec.json|8.depends_on

指定服务之间的依赖关系,办理服务启动先后序次问题。指定服务之间的依赖关系,将会导致以下举动:
docker-compose up以依赖序次启动服务。
docker-compose up SERVICE会主动包罗SERVICE的依赖项。
docker-compose stop以依赖序次停止服务。
但是服务不会等待该服务所依赖的服务完全启动或停止之后才启动或停止。
services:  web:    build: .    depends_on:      - db      - redis  redis:    image: redis  db:    image: postgres利用docker-compose up启动时会先启动db和redis,末了才启动web。利用docker-compose up web启动web时,也会启动db和redis,由于在web服务中指定了依赖关系。利用docker-compose stop在停止时也在web之前先停止db和redis。9.deploy

指定摆设和运行服务的相干设置。该设置仅在swarm mode下收效,并只能通过docker stack deploy命令摆设,docker-compose up和docker-compose run命令将被忽略。
services:  redis:    image: redis:alpine    deploy:      replicas: 6      placement:        max_replicas_per_node: 1      update_config:        parallelism: 2        delay: 10s      restart_policy:        condition: on-failuredeploy设置项中包罗endpoint_mode、labels、mode、placement、max_replicas_per_node、replicas、resources、restart_policy、rollback_config、update_config等子设置项。
# docker service inspect 3x9ypsh2sx5a[    {        "ID": "3x9ypsh2sx5amr4wrs1or2zt8",        "Version": {            "Index": 40        },        "CreatedAt": "2023-03-16T07:34:04.154820913Z",        "UpdatedAt": "2023-03-16T07:34:04.154820913Z",        "Spec": {            "Name": "sharp_mendeleev",            "Labels": {},            "TaskTemplate": {                "ContainerSpec": {                    "Image": "redis:latest@sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339",                    "Init": false,                    "StopGracePeriod": 10000000000,                    "DNSConfig": {},                    "Isolation": "default"                },                "Resources": {                    "Limits": {},                    "Reservations": {}                },                "RestartPolicy": {                    "Condition": "any",                    "Delay": 5000000000,                    "MaxAttempts": 0                },                "Placement": {                    "Platforms": [                        {                            "Architecture": "amd64",                            "OS": "linux"                        },                        {                            "OS": "linux"                        },                        {                            "OS": "linux"                        },                        {                            "Architecture": "arm64",                            "OS": "linux"                        },                        {                            "Architecture": "386",                            "OS": "linux"                        },                        {                            "Architecture": "mips64le",                            "OS": "linux"                        },                        {                            "Architecture": "ppc64le",                            "OS": "linux"                        },                        {                            "Architecture": "s390x",                            "OS": "linux"                        }                    ]                },                "ForceUpdate": 0,                "Runtime": "container"            },            "Mode": {                "Replicated": {                    "Replicas": 1                }            },            "UpdateConfig": {                "Parallelism": 1,                "FailureAction": "pause",                "Monitor": 5000000000,                "MaxFailureRatio": 0,                "Order": "stop-first"            },            "RollbackConfig": {                "Parallelism": 1,                "FailureAction": "pause",                "Monitor": 5000000000,                "MaxFailureRatio": 0,                "Order": "stop-first"            },            "EndpointSpec": {                "Mode": "vip"            }        },        "Endpoint": {            "Spec": {}        }    }]1)endpoint_mode

为外部客户端毗连到swarm指定服务发现方式:
endpoint_mode: vip:Docker为服务分配了一个前端的假造IP,客户端通过该假造IP访问网络上的服务。Docker在客户端和服务的可用工作节点之间举行路由哀求,而无须关系有多少节点正在加入该服务或这些节点的IP地点大概端口。这是默认设置。
endpoint_mode: dnsrr:DNS轮询(DNSRR),Docker设置服务的DNS条目,以便对服务名称的DNS查询返回IP地点列表,而且客户端通过轮询的方式直接毗连到此中之一。
version: "3.2"services:  wordpress:    ...    deploy:      mode: replicated      replicas: 2      endpoint_mode: vip默以为endpoint_mode: vip# docker service inspect --format='{{.Spec.TaskTemplate.ContainerSpec.Image}}----''{{.Spec.EndpointSpec.Mode}}' 3x9ypsh2sx5aredis:latest@sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339----vip2)labels

指定服务的标签。这些标签仅在服务上设置,而不在服务的任何容器上设置。
version: "3.8"services:  web:    image: web    deploy:      labels:        com.example.description: "This label will appear on the web service"默认Lables为空# docker service inspect --format='{{.Spec.TaskTemplate.ContainerSpec.Image}}----''{{.Spec.Labels}}' 3x9ypsh2sx5aredis:latest@sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339----map[]3)mode

指定服务的容器副本模式。可以为:
global:每个swarm节点只有一个该服务容器。
replicated:整个集群中存在指定份数的服务容器副本,为默认值。
services:  worker:    image: dockersamples/examplevotingapp_worker    deploy:      mode: global# docker service inspect --format '{{.Spec.Mode.Replicated.Replicas}}' 3x9ypsh2sx5a14)placement

指定constraints和preferences。constraints可以指定只有符合要求的节点上才能运行该服务容器,preferences可以指定容器分配战略。比方,指定集群中只有满意node.rolemanager和engine.labels.operatingsystemubuntu 18.04条件的节点上能运行db服务容器,而且在满意node.labels.zone的节点上匀称分配:
services:  db:    image: postgres    deploy:      placement:        constraints:          - "node.role==manager"          - "engine.labels.operatingsystem==ubuntu 18.04"        preferences:          - spread: node.labels.zone# docker service inspect --format '{{.Spec.TaskTemplate.Placement.Platforms}}' 3x9ypsh2sx5a[{amd64 linux} { linux} { linux} {arm64 linux} {386 linux} {mips64le linux} {ppc64le linux} {s390x linux}]5)max_replicas_per_node

假如服务的容器副本模式为replicated(默认),可以指定每个节点上运行的最大容器副本数量。当指定的容器副本数量大于最大容器副本数量时,将引发no suitable node (max replicas per node limit exceed)错误。
version: "3.8"services:  worker:    ...    deploy:      mode: replicated      replicas: 6      placement:        max_replicas_per_node: 16)replicas

假如服务的容器副本模式为replicated(默认),指定运行的容器副本数量。
services:  worker:    ...    deploy:      mode: replicated      replicas: 6# docker service inspect --format '{{.Spec.Mode.Replicated.Replicas}}' 3x9ypsh2sx5a7)resources

设置资源限制。比方,指定redis服务利用的cpu份额为25%到50%,内存为20M到50M:
在V3版Compose设置文件中的改变:resources代替了V3版之前的Compose设置文件中旧的资源限制的设置项,包罗cpu_shares、cpu_quota、cpuset、mem_limit、memswap_limit、mem_swappiness。
在非swarm mode容器上设置资源限制:此处的resources设置项只有效于deploy设置项之下和swarm mode。假如要在非swarm mode摆设中设置资源限制,需利用V2版Compose设置文件中CPU、memory和其他资源的设置项。
services:  redis:    ...    deploy:      resources:        limits:          cpus: '0.50'          memory: 50M        reservations:          cpus: '0.25'          memory: 20M# docker service inspect --format '{{.Spec.TaskTemplate.Resources.Limits}}---{{.Spec.TaskTemplate.Resources.Reservations}}' 3x9ypsh2sx5a{0 0 0}---{0 0 []}8)restart_policy

指定容器的重启战略。代替restart。有以下设置选项:
condition:重启战略。值可以为none、on-failure或any,默以为any。
delay:实行重启的等待时间。指定为一连时间(durations)。默认值为0。
max_attempts:重启最多实行的次数,凌驾该次数将放弃。默以为永不放弃。假如在window设置的时间之内未乐成重启,则此次实行不计入max_attempts的值。
window:在决定重启是否乐成之前的等待时间。指定为一连时间(durations)。默认值为立即决定。
比方,指定重启战略为失败时重启,等待5s,重启最多实行3次,决定重启是否乐成前的等待时间为120s:
services:  redis:    ...    deploy:      restart_policy:        condition: on-failure        delay: 5s        max_attempts: 3        window: 120s# docker service inspect --format '{{.Spec.TaskTemplate.RestartPolicy.Condition}},''{{.Spec.TaskTemplate.RestartPolicy.Delay}},'{{.Spec.TaskTemplate.RestartPolicy.MaxAttempts}}'' 3x9ypsh2sx5aany,5s,09)rollback_config

设置在更新失败的环境下怎样回滚服务。有以下设置选项:
parallelism:一次回滚的容器数量。假如设置为0,则全部容器同时回滚。
delay:每个容器组之间的回滚所等待的时间。默认值为0s。
failure_action:回滚失败后的举动。有continue和pause两种,默认值为pause。
monitor:每次使命更新后监督失败的时间(ns|us|ms|s|m|h)。默认值为0s。
max_failure_ratio:在回滚期间可以或许容忍的最大失败率。默认值为0。
order:设置回滚序次。stop-first为在开启新使命之前停止旧使命,start-first为起首启动新使命,和正在运行使命短暂重叠,默认值为stop-first。
            "RollbackConfig": {                "Parallelism": 1,                "FailureAction": "pause",                "Monitor": 5000000000,                "MaxFailureRatio": 0,                "Order": "stop-first"            },# docker service inspect --format '{{index .Spec.RollbackConfig}}' 3x9ypsh2sx5a{1 0s pause 5s 0 stop-first}10)update_config

设置怎样更新服务。该设置对滚动更新很有效。有以下设置选项:
parallelism:一次更新的容器数量。
delay:更新一组容器之间的等待时间。
failure_action:更新失败后的举动。有continue、rollback和pause三种,默认值为pause。
monitor:每次使命更新后监督失败的时间(ns|us|ms|s|m|h)。默认值为0s。
max_failure_ratio:在更新期间可以或许容忍的最大失败率。
order:设置更新序次。stop-first为在开启新使命之前停止旧使命,start-first为起首启动新使命,和正在运行使命短暂重叠,默认值为stop-first。注意该设置项在3.4版的设置文件格式中加入,仅支持3.4或更高版本。
比方,指定每次更新2个容器,更新等待时间10s,更新序次为先停止旧使命再开启新使命:
services:  vote:    ...    deploy:      replicas: 2      update_config:        parallelism: 2        delay: 10s        order: stop-first            "UpdateConfig": {                "Parallelism": 1,                "FailureAction": "pause",                "Monitor": 5000000000,                "MaxFailureRatio": 0,                "Order": "stop-first"            },# docker service inspect --format '{{index .Spec.UpdateConfig}}' 3x9ypsh2sx5a{1 0s pause 5s 0 stop-first}11)Not supported for docker stack deploy

以下为支持docker-compose up和docker-compose run,不支持docker stack deploy或deploy设置项的设置项:
buildcgroup_parentcontainer_namedevicestmpfsexternal_linkslinksnetwork_moderestartsecurity_optuserns_mode10.devices

指定装备映射列表。与Docker客户端create的--device选项类似。
  devices:    - "/dev/ttyUSB0:/dev/ttyUSB0"# docker inspect --format '{{.HostConfig.Devices}}' 241f80a43637[]11.dns

自界说DNS服务器。可以是一个值或一个列表。比方:
services:  redis:    ...    dns: 8.8.8.8        dns:      - 8.8.8.8      - 9.9.9.9# docker inspect --format '{{.HostConfig.Dns}}' b03c7080b0b6[8.8.8.8]12.dns_search

自界说DNS搜刮域。可以是一个值或一个列表。比方:
services:
redis:
...
dns_search: example.com
dns_search:  - dc1.example.com  - dc2.example.com# docker inspect --format '{{.HostConfig.DnsSearch}}' 1c705ea79a52[example.com]13.entrypoint

覆盖默认的入口命令。注意设置entrypoint会覆盖全部在服务镜像上利用Dockerfile的ENTRYPOINT指令设置的默认入口命令,并扫撤消服务镜像上任何利用Dockerfile的CMD指令设置的启动容器时默认实行的命令。可以写成字符串情势,比方:
services:  redis:    ...    entrypoint: /code/entrypoint.sh也可以写成JSON数组情势,比方:    entrypoint: ["php", "-d", "memory_limit=-1", "vendor/bin/phpunit"]# docker inspect --format '{{.Config.Entrypoint}}' 1c705ea79a52[docker-entrypoint.sh]14.env_file

从文件中获取环境变量。可以是一个值或一个列表。比方:
services:  redis:    ...    env_file: .env    env_file:      - ./common.env      - ./apps/web.env      - /opt/runtime_opts.env假如指定了Compose设置文件,env_file路径为相对于该文件所在目次的路径。假如环境文件中设置有与environment选项同名的变量,将以后者为准,无论这些变量的值是空照旧未界说。此中环境文件每行都以VAR=VAL格式声明环境变量,以#开头的行被剖析为解释,和空行一样将被忽略。环境文件示比方下:
# Set Rails/Rack environmentRACK_ENV=development假如变量的值被引号引起来(通常是shell变量),则引号也包罗在转达给Compose的值中。假如以列表的情势同时指定了多个环境文件,列表中文件的序次对于给多次出现的环境变量确定值十分紧张,且列表中的文件是从上到下处理的。假如指定了多个环境文件且有至少两个文件声明白雷同名称但差别值的环境变量,那么指定列表中序次靠下的文件将覆盖序次靠上的文件中的雷同名称的环境变量的值。比方:
services:  some-service:    env_file:      - a.env      - b.env假如a.env中有VAR=1,b.env中有VAR=2,则终极$VAR=2。
注意:这里所说的环境变量是针对宿主机的Compose而言的,假如在服务中指定了build设置项,那么这些变量并不会进入构建过程中,假如要界说构建时用的环境变量首选build的arg子选项。
15.environment

设置环境变量。可以利用数组或字典两种格式。任何布尔范例的值都必须用引号引起来,以便剖析器将它们解释为字符串。值设置了键没设置值的环境变量可以在运行Compose的主机环境中剖析它们的值,这对于利用密钥和特定于主机的值用处很大。比方:
services:  some-service:    environment:      RACK_ENV: development      SHOW: 'true'      SESSION_SECRET:      environment:      - RACK_ENV=development      - SHOW=true      - SESSION_SECRET注意:这里所说的环境变量是针对宿主机的Compose而言的,假如在服务中指定了build设置项,那么这些变量并不会进入构建过程中,假如要界说构建时用的环境变量首选build的arg子选项。
# docker inspect --format '{{.Config.Env}}' 1c705ea79a52[affinity:container==b03c7080b0b697c58833d7ee59a74301dd76e46655c994befc1eca99ef760e03 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin GOSU_VERSION=1.12 REDIS_VERSION=6.2.6 REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab]16.expose

袒露指定端口,但不映射到宿主机,只被毗连的服务访问。只能指定内部端口。比方:
services:  some-service:    expose:      - "3000"      - "8000"# docker inspect --format '{{.Config.ExposedPorts}}' 1c705ea79a52map[6379/tcp:{}]17.external_links

链接到docker-compose.yml外部的容器,以致并非Compose管理的外部容器,特殊是对于提供共享或公共服务的容器。在同时指定容器名称和链接别名(CONTAINER:ALIAS)时,external_links与旧版本中的设置项links有类似的语义。比方:
services:  some-service:    external_links:      - redis_1      - project_db_1:mysql      - project_db_1:postgresql注意:Compose项目内里的容器毗连到外部容器的条件条件是外部容器中必须至少有一个容器毗连到与项目内的服务的同一个网络内里。发起利用networks代替旧版本中的设置项Links。
利用docker stack deploy时的注意事项:在swarm mode下摆设堆栈时,external_links设置项将被忽略。
# docker inspect --format '{{.NetworkSettings.Networks.docker_redis_network.Links}}'  f43a1da40a04[redis_1:redis_1]18.extra_hosts

添加主机名到IP的映射。利用和Docker客户端中的--add-host的参数一样的值。比方:
services:  some-service:    extra_hosts:      - "somehost:162.242.195.82"      - "otherhost:50.31.209.229"会在启动后的服务容器中的/etc/hosts文件中添加如下两条具有主机名和IP地点的条目:
162.242.195.82  somehost50.31.209.229   otherhost# docker inspect --format '{{.HostConfig.ExtraHosts}}' 5ed09a98c65d[somehost:162.242.195.82 otherhost:50.31.209.229]19.healthcheck

设置运行查抄以确定服务容器是否健康。支持以下设置选项:
test:指定健康检测的方法。
interval:启动容器到举行健康查抄的隔断时间以及两次健康查抄的隔断时间。
timeout:单次健康查抄的超时时间,凌驾该时间该次健康查抄失败。
retries:健康查抄失败后的最大重试次数,重试了最大次数依然失败,容器将被视为unhealthy。
start_period:为须要时间引导的容器提供的初始化时间,在此期间查抄失败将不计入最大重试次数,但是假如在启动期间健康查抄乐成,则会将容器视为已启动,而且全部一连失败将计入最大重试次数。
此中interval、timeout和start_period都被指定为一连时间(durations)。start_period是在3.4版的设置文件格式中加入。test必须是字符串或JSON数组格式。假如是JSON数组格式,第一项必须是NONE、CMD或CMD-SHELL此中之一。假如是字符串格式,则等效于指定CMD-SHELL后跟该字符串的JSON数组格式。
比方以下示例,指定检测方法为访问http://localhost,健康查抄隔断时间为1m30s,健康查抄超时时间为10s,重试次数为3,启动容器后等待健康查抄的初始化时间为40s:
services:  some-service:    healthcheck:    test: ["CMD", "curl", "-f", "http://localhost"]    interval: 1m30s    timeout: 10s    retries: 3    start_period: 40s比方以下示例,两种情势等效:
test: ["CMD-SHELL", "curl -f http://localhost || exit 1"]test: curl -f https://localhost || exit 1利用disable: true可以设置镜像禁用全部健康查抄,相对于test: ["NONE"]。比方:
services:  some-service:    healthcheck:      disable: true# docker inspect --format '{{.Config.Healthcheck}}' f1b65c983797{[CMD curl -f http://localhost] 1m30s 10s 0s 3}            "Healthcheck": {                "Test": [                    "CMD",                    "curl",                    "-f",                    "http://localhost"                ],                "Interval": 90000000000,                "Timeout": 10000000000,                "Retries": 3            },20.image

指定要从中启动容器的镜像。可以写堆栈/标签(repository/tag)或镜像ID。示比方下:
services:  redis:    image: redis:latest        image: redis    image: ubuntu:18.04    image: tutum/influxdb    image: example-registry.com:4000/postgresql    image: a4bc65fd假如镜像不存在,Compose会主动拉取镜像,除非指定了build,这种环境下会利用指定选项构建镜像并给镜像打上指定标签。
# docker inspect --format '{{.Config.Image}}' f1b65c983797redis:latest21.init

在容器内运行一个初始化步伐以转发信号并获取进程。设置为true即可为服务启动此功能。比方:
version: "3.7"services:  web:    image: alpine:latest    init: true注意:默认利用的初始化二进制文件是Tini,并安装在主机保卫进程的/usr/libexec/docker-init。可以通过Daemon configuration file中的init-path将保卫进程设置为利用自界说的初始化二进制文件 。
# docker inspect --format '{{.HostConfig.Init}}' 77a502571344true22.isolation

指定容器的隔离技术。Linux上只支持default值。Windows上支持default、process和hyperv这三个值。
services:  web:    isolation: default# docker inspect --format '{{.HostConfig.Isolation}}'  6d497ef22a13default23.labels

将元数据以标签的情势添加到容器中。可以利用数组或字典两种格式。比方:
services:  web:    labels:      com.example.description: "Accounting webapp"      com.example.department: "Finance"      com.example.label-with-empty-value: ""# docker inspect --format '{{.Config.Labels}}' 6d497ef22a13map[com.docker.compose.config-hash:cfba4c9fafbd05de296e709055a74dfd9391f7de20e9c3f25cdc49801db6393b com.docker.compose.container-number:1 com.docker.compose.oneoff:False com.docker.compose.project:docker com.docker.compose.project.config_files:docker-compose.yml com.docker.compose.project.working_dir:/root/docker com.docker.compose.service:redis com.docker.compose.version:1.26.0 com.example.department:Finance com.example.description:Accounting webapp com.example.label-with-empty-value:]24.links

告诫:--link是Docker的遗留功能。它终极大概会被删除。发起您利用用户自界说网络代替--link来举行两个容器间的通讯。用户自界说的网络不支持--link在容器之间共享的环境变量的功能。但是可以利用比方数据卷之类的其他机制以更可控的方式在容器之间共享环境变量。
链接到其他服务中的容器。可以利用"SERVICE:ALIAS"或"SERVICE"的格式,此中SERVICE为服务名称,ALIAS为链接别名。
services:  web:    links:      - "db"      - "db:database"      - "redis"链接服务的容器可以通过与别名雷同的主机名访问,假如未指定别名,则可以利用服务名。默认环境下,不须要链接即可使服务举行通讯,任何服务都可以利用该服务的名称访问任何其他服务。链接也可以和depends_on一样表现服务之间的依赖关系 ,因此可以确定服务启动的序次。
注意:假如同时界说链接和网络,则它们之间具有链接的服务必须共享至少一个公共网络才能举行通讯。
利用docker stack deploy时的注意事项:在swarm mode下摆设堆栈时,links设置项将被忽略。
# docker inspect --format '{{.NetworkSettings.Networks.docker_redis_network.Links}}'  f43a1da40a0425.logging

服务的日记设置。比方:
services:  web:    logging:      driver: syslog      options:        syslog-address: "tcp://192.168.0.42:123"driver设置项指定服务容器的日记驱动,与docker run中的--log-driver选项一样。默认值为json-file,这里枚举三种日记驱动范例:
driver: "json-file"driver: "syslog"driver: "none"利用options设置项为日记驱动指定日记记载选项,与docker run中的--log-opt选项一样。比方:
默认日记驱动json-file具有限制日记存储量的选项。比方以下示例,max-size设置最大存储巨细为200k,max-file设置存储的最大文件数为10,随着日记凌驾最大限制,将删除较旧的日记文件以答应存储新日记:
services:  web:    logging:      options:        max-size: "200k"        max-file: "10"            "LogConfig": {                "Type": "json-file",                "Config": {                    "max-file": "10",                    "max-size": "200k"                }            },# docker inspect --format '{{.HostConfig.LogConfig}}' 38067601e2e3{json-file map[max-file:10 max-size:200k]}26.network_mode

设置网络模式。利用和Docker客户端中的--network的参数一样的值,格式为service:[service name]。可以指定利用服务大概容器的网络。示比方下:
services:  redis:    ...    network_mode: "bridge"network_mode: "host"network_mode: "none"network_mode: "service:[service name]"network_mode: "container:[container name/id]"注意事项:
在swarm mode下摆设堆栈时,该选项将被忽略。
network_mode: "host"不能与links设置项混用。
network_mode不能与networks设置项混用。
当用netorks设置项时# docker inspect --format '{{.HostConfig.NetworkMode}}' 38067601e2e3docker_redis_network当设置network_mode: "bridge"# docker inspect --format '{{.HostConfig.NetworkMode}}' d137058708ebbridge27.networks

指定所加入的网络。须要在顶层networks设置项中引入具体的网络信息。
services:  redis:    ...    networks:      - redis_network      - other-network# docker inspect --format '{{.HostConfig.NetworkMode}}' 38067601e2e3docker_redis_network1)aliases

指定服务在此网络上的别名(备用主机名)。同一网络上的其他容器可以利用服务名称或此别名来毗连到服务的任何一个容器。由于aliases属于网络范围,因此同一服务在差别的网络上可以具有差别的别名。比方:
services:  redis:    ...    networks:      redis_network:        aliases:          - alias1          - alias3                    "Aliases": [                        "redis",                        "alias1",                        "2c1fc62e6cb1",                        "alias3"                    ],# docker inspect --format '{{.NetworkSettings.Networks.docker_redis_network}}' 2c1fc62e6cb1{<nil> [redis_1:redis_1] [redis alias1 2c1fc62e6cb1 alias3] 74f09926f4d034f2ae63ff1a46590d883562e711814a0dcce7e683284e407c31 a8cca1aecb9a3283a1b49fee318acd956a33358837690632c12209dc21b33894 172.21.0.1 172.21.0.2 16   0 02:42:ac:15:00:02 map[]}# docker inspect --format '{{.NetworkSettings.Networks.docker_redis_network.Aliases}}' 2c1fc62e6cb1[redis alias1 2c1fc62e6cb1 alias3]在以下示例中,提供了web、worker和db三个服务,以及new和legacy两个网络:
services:  web:    image: "nginx:alpine"    networks:      - new  worker:    image: "my-worker-image:latest"    networks:      - legacy  db:    image: mysql    networks:      new:        aliases:          - database      legacy:        aliases:          - mysql  networks:  new:  legacy:在该例中,可以通过主机名db或database在new网络上访问db服务,通过db或mysql在legacy网络上访问db服务。
注意:网络范围内的别名可以被多个容器以致多个服务共享。假如是这样,则不能包管名称恰好剖析到哪一个容器。
2)ipv4_address、ipv6_address

加入网络后,为此服务的容器指定一个静态IP地点。在顶层networks设置项中的相应网络设置必须有子网设置覆盖每个静态地点的ipam设置。比方:
version: "3.8"services:  app:    image: nginx:alpine    networks:      app_net:        ipv4_address: 172.16.238.10        ipv6_address: 2001:3984:3989::10  networks:  app_net:    ipam:      driver: default      config:        - subnet: "172.16.238.0/24"        - subnet: "2001:3984:3989::/64"注意:假如须要IPv6寻址,则必须利用V2.x版本的Compose设置文件并设置顶层networks设置项下的enable_ipv6选项。在当前swarm mode下IPv6选项不会起作用。
28.pid

跟主机体系共享进程定名空间。
services:  redis:    pid: "host"将PID模式设置为主机PID模式,打开该选项的容器之间,以及容器和宿主机利用体系之间可以通过进程ID来相互访问和利用
# docker inspect --format '{{.State.Pid}}' 2c1fc62e6cb11837303# ps -ef|grep 1837303root     1837303 1837284  0 05:58 ?        00:00:00 /sbin/docker-init -- docker-entrypoint.sh redis-server /etc/redis/redis.confsystemd+ 1837351 1837303  0 05:58 ?        00:00:00 redis-server *:637929.posts

袒露端口。
1)Long syntax

注意端口映射与network_mode: host不兼容。支持short和long两种格式的语法。short语法可以利用HOST:CONTAINER的格式指定端口映射,也可以指定容器端口,宿主时机随机选择临时端口举行映射。比方:
services:  redis:    ports:      - "6379:6379"      - "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"      - "12400-12500:1240"注意:当利用HOST:CONTAINE格式来映射端口时,假如利用的容器端口小于60大概会得到错误得效果,由于YAML将会剖析xx:yy这种数字格式为60进制,因此发起始终接纳字符串格式来指定端口映射。
# docker inspect --format '{{.NetworkSettings.Ports}}' 2c1fc62e6cb1map[6379/tcp:[{0.0.0.0 6379} {:: 6379}]]2)Short syntax

long语法支持设置short语法中不支持的附加字段。这些附加字段如下:
target:指定容器内的端口。
published:指定公开的端口。
protocol:指定端口协议(tcp或udp)。
mode:利用host在每个节点公开一个主机端口,或利用ingress对swarm mode端口举行负载均衡。
services:  redis:    ports:      - target: 80        published: 8080        protocol: tcp        mode: host30.restart

指定重启战略。比方想要在容器退出时总是会重启容器,指定以下重启战略:
一共支持以下重启战略:
no:在任何环境下都不会重启容器。默认的重启战略。
always:在容器退出时总是重启容器。
on-failure:在容器以非0状态码退出时才会重启。
unless-stopped:在容器退出时总是重启容器,但是不思量在Docker保卫进程启动时就已经停止了的容器。
services:  redis:    restart: "no"    restart: always    restart: on-failure    restart: unless-stopped利用docker stack deploy时的注意事项:在swarm mode下摆设堆栈时,restart设置项将被忽略。
# docker inspect --format '{{.HostConfig.RestartPolicy}}' 2c1fc62e6cb1{always 0}            "RestartPolicy": {                "Name": "always",                "MaximumRetryCount": 0            },31.secrets

为每个服务授予对保密数据(secrets)的访问权限。支持short和long两种格式的语法。
利用docker stack deploy时的注意事项:该保密数据(secret)必须已存在大概在Compose设置文件顶层secrets设置项中界说,否则堆栈摆设将失败。
1)Short syntax

short语法仅指定secret名称来授予容器访问secret数据的权限并将其挂载到容器的/run/secrets/<secret_name>上。source名称和目的挂载点都设置为secret名称。比方以下示例,授予了redis服务对secrets的my_secret和my_other_secret的访问权限,此中my_secret的值设置到文件./my_secret.txt的内容中,my_other_secret界说为外部资源,这意味着它已经在Docker中通过运行docker secret create命令或其他堆栈摆设举行界说,假如外部secret不存在,堆栈摆设将会失败并表现secret not found错误:
version: "3.9"services:  redis:    image: redis:latest    deploy:      replicas: 1    secrets:      - my_secret      - my_other_secretsecrets:  my_secret:    file: ./my_secret.txt  my_other_secret:    external: true2)Long syntax

long语法提供了在服务的使命容器内怎样创建secret的更多粒度:
source:Docker中存在的secret名称。
target:指定要挂载到服务的使命容器的/run/secrets/中的文件名称。假如未指定,默以为source的值。
uid和gid:指定服务的使命容器的/run/secrets/中所拥有的该文件的UID或GID。假如未指定,两者都默以为0。
mode:以八进制表现法指定要挂载到服务的使命容器的/run/secrets/中的文件权限。比方,0444代表可读。默认值在Docker 1.13.1为0000,在较新版本为0444。secret内容已挂载到临时文件体系中,以是不可写,假如设置了可写位将被忽略。可以设置可实行位。假如不熟悉UNIX文件权限模式,可以利用权限盘算器 。
比方以下示例,指定secret名称为my_secret,授予redis服务对my_secret的访问权限,指定要挂载到redis服务的使命容器的/run/secrets/中的文件名称为redis_secret,指定UID和GID均为103,指定要挂载到服务的使命容器的/run/secrets/中的文件权限为0440(group-readable),但该redis服务没有访问my_other_secret的权限:
version: "3.9"services:  redis:    image: redis:latest    deploy:      replicas: 1    secrets:      - source: my_secret        target: redis_secret        uid: '103'        gid: '103'        mode: 0440secrets:  my_secret:    file: ./my_secret.txt  my_other_secret:    external: true32.security_opt

为每个容器覆盖默认的标签(label)。比方设置标签中的用户名和脚色名:
services:  redis:    ...    security_opt:      - label:user:USER      - label:role:ROLE利用docker stack deploy时的注意事项:在swarm mode下摆设堆栈时,security_opt设置项将被忽略。
# docker inspect --format '{{.HostConfig.SecurityOpt}}' 02a534e927b2 [label:user:USER label:role:ROLE label=disable]33.stop_grace_period

指定在发送SIGKILL之前,假如容器无法处理SIGTERM或利用stop_signal指定的任何停止信号时,试图停止该容器所须要的等待时间。默认环境下,stop在发送SIGKILL之前等待10秒以退出容器。时间指定为duration。具体示比方下:
services:  redis:    ...    stop_grace_period: 1m30s# docker inspect --format '{{.Config.StopTimeout}}' 02010fce43b89034.stop_signal

设置停止容器的信号。默认利用SIGTERM停止容器。比方指定SIGUSR1信号:
services:  redis:    ...    stop_signal: SIGUSR1# docker inspect --format '{{.Config.StopSignal}}' 24b883a4ca86SIGUSR135.sysctls

在容器中设置的内核参数。可以利用数组或字典两种格式。比方指定毗连数为1024和开启TCP的syncookies:
services:  redis:    ...    sysctls:      net.core.somaxconn: 1024      net.ipv4.tcp_syncookies: 0# docker inspect --format '{{.HostConfig.Sysctls}}' 2ac559f58bb2 map[net.core.somaxconn:1024 net.ipv4.tcp_syncookies:0]36.tmpfs

挂载一个临时文件体系到容器内部。可以是一个值或一个列表。比方
services:
redis:
...
tmpfs: /run
tmpfs:  - /run  - /tmp# docker inspect --format '{{.HostConfig.Tmpfs}}' 2f3f969ca726 map[/run:]在容器内挂载一个临时文件体系。Size可以指定挂载的tmpfs巨细,以字节为单元。默认环境下不受限制。比方:
services:  redis:    ...    - type: tmpfs      target: /app      tmpfs:        size: 100037.ulimits

覆盖容器的默认ulimit值。可以单一地将限制值设为一个整数,也可以将soft/hard限制指定为映射。比方,指定最大进程数为65535,指定文件句柄数,此中软限制为20000,体系硬限制为40000,软限制应用可以随时修改,不能凌驾硬限制,硬限制只能root用户进步:
services:  redis:    ...    ulimits:      nproc: 65535      nofile:        soft: 20000        hard: 40000            "Ulimits": [                {                    "Name": "nproc",                    "Hard": 65535,                    "Soft": 65535                },                {                    "Name": "nofile",                    "Hard": 40000,                    "Soft": 20000                }            ],# docker inspect --format '{{.HostConfig.Ulimits}}' c3d082140a07[nproc=65535:65535 nofile=20000:40000]38.userns_mode

指定用户定名空间模式。假如Docker保卫进程设置了用户名称空间,则禁用此服务的用户名称空间。以下是利用主机上的用户定名空间的设置示例:
userns_mode: "host"默认UsernsMode为null# docker inspect --format '{{.HostConfig.UsernsMode}}' c3d082140a07设置UsernsMode为host# docker inspect --format '{{.HostConfig.UsernsMode}}' bf76418f4ab6host利用docker stack deploy时的注意事项:在swarm mode下摆设堆栈时,userns_mode设置项将被忽略。
39.volumes

指定所挂载的主机路径或数据卷名称。支持short和long两种格式的语法。可以将主机路径作为单个服务的一部门举行挂载,而无需在顶层volumes设置项中界说。但是假如想要在多个服务之间重用数据卷,须要在顶层volumes设置项中界说一个数据卷名称。
在3版的设置文件格式中的厘革:在顶层volumes设置项中界说了数据卷名称并从每个服务的volumes列表中引用了该数据卷。这将替换早期版本的Compose设置文件格式中的volumes_from设置项。
1)Long syntax

short语法利用通用的[SOURCE:]TARGET[:MODE]格式,SOURCE可以是主机路径或数据卷名称,TARGET为挂载数据卷的容器路径,MODE可以为ro只读模式或rw读写模式(默认)。可以在主机上挂载相对路径,该路径相对于正在利用的Compose设置文件的目次举行扩展,相对路径应始终以.或..开头。比方:
volumes:  # 只指定一个路径,Docker会主动在创建一个数据卷(这个路径是容器内部的)  # Just specify a path and let the Engine create a volume  - /var/lib/mysql  # 利用绝对路径挂载数据卷  # Specify an absolute path mapping  - /opt/data:/var/lib/mysql  # 利用基于Compose设置文件的相对路径作为数据卷挂载到容器  # Path on the host, relative to the Compose file  - ./cache:/tmp/cache  # 利用基于root用户的相对路径作为数据卷挂载到容器  # User-relative path  - ~/configs:/etc/configs/:ro  # 利用已经存在定名的数据卷挂载到容器  # Named volume  - datavolume:/var/lib/mysql2)Short syntax

long语法支持设置以下short语法中不支持的附加字段:
type:挂载范例,可以为volume、bind、tmpfs或npipe。
source:挂载源,在主机上用于绑定挂载的路径或界说在顶层volumes设置项中的数据卷名称。不适用于tmpfs挂载范例。
target:数据卷挂载在容器中的路径。
read_only:设置数据卷为只读。
bind:设置额外的bind选项。
propagation:用于绑定的传播模式。
volume:设置额外的volume选项。
nocopy:创建数据卷时克制从容器复制数据。
tmpfs:设置额外的tmpfs选项。
size:tmpfs挂载的巨细,以字节为单元。
consistency:挂载的同等性要求,可以为consistent、cached或delegated。此中consistent表现主机和容用具有雷同视图。cached表现读取缓存,主机视图是权势巨子的。delegated表现读写缓存,容器视图是权势巨子的。
version: "3.9"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/staticnetworks:  webnet:volumes:  mydata:services:  redis:    ...    volumes:      - redis_vol:/data      - ./redis.conf:/etc/redis/redis.conf# docker inspect --format '{{.Config.Volumes}}' bf76418f4ab6map[/data:{} /etc/redis/redis.conf:{}]3)Volumes for services, swarms, and stack files

注意:当利用services、swarms和docker-stack.yml文件时,请记取,支持服务的使命(容器)可以摆设在群组中的任何节点上,而且每次更新服务时,这大概是差别的节点。
在没有指定来源的定名卷的环境下,Docker会为支持服务的每个使命创建一个匿名卷。删除关联的容器后,匿名卷不会持久存在。
假如盼望数据持久化,请利用定名卷和支持多主机的卷驱动步伐,以便可以从任何节点访问数据。大概,对服务设置束缚,以便将其使命摆设在具有卷的节点上。
version: "3.9"services:  db:    image: postgres:9.4    volumes:      - db-data:/var/lib/postgresql/data    networks:      - backend    deploy:      placement:        constraints: [node.role == manager]4)domainname, hostname, ipc, mac_address, privileged, read_only, shm_size, stdin_open, tty, user, working_dir

每一个都是一个单独的值,类似于docker run的对应值。请注意,mac_address是一个遗留选项。
user: postgresqlworking_dir: /codedomainname: foo.comhostname: fooipc: hostmac_address: 02:42:ac:11:65:43privileged: trueread_only: trueshm_size: 64Mstdin_open: truetty: true参考URL

https://blog.csdn.net/weixin_67479400/article/details/125864700
https://github.com/docker/compose/releases
https://docs.docker.com/compose/compose-file/compose-versioning/
https://docs.docker.com/compose/compose-file/compose-file-v3/
https://blog.csdn.net/qq_27546717/article/details/125586553
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 22:37, Processed in 0.217328 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表