Services top-level elements (original) (raw)

A service is an abstract definition of a computing resource within an application which can be scaled or replaced independently from other components. Services are backed by a set of containers, run by the platform according to replication requirements and placement constraints. As services are backed by containers, they are defined by a Docker image and set of runtime arguments. All containers within a service are identically created with these arguments.

A Compose file must declare a services top-level element as a map whose keys are string representations of service names, and whose values are service definitions. A service definition contains the configuration that is applied to each service container.

Each service may also include a build section, which defines how to create the Docker image for the service. Compose supports building Docker images using this service definition. If not used, the build section is ignored and the Compose file is still considered valid. Build support is an optional aspect of the Compose Specification, and is described in detail in the Compose Build Specification documentation.

Each service defines runtime constraints and requirements to run its containers. The deploy section groups these constraints and lets the platform adjust the deployment strategy to best match containers' needs with available resources. Deploy support is an optional aspect of the Compose Specification, and is described in detail in the Compose Deploy Specification documentation. If not implemented the deploy section is ignored and the Compose file is still considered valid.

Simple example

The following example demonstrates how to define two simple services, set their images, map ports, and configure basic environment variables using Docker Compose.

Advanced example

In the following example, the proxy service uses the Nginx image, mounts a local Nginx configuration file into the container, exposes port 80 and depends on the backend service.

The backend service builds an image from the Dockerfile located in the backend directory that is set to build at stage builder.

For more example Compose files, explore the Awesome Compose samples.

annotations

annotations defines annotations for the container. annotations can use either an array or a map.

attach

Requires: Docker Compose2.20.0 and later

When attach is defined and set to false Compose does not collect service logs, until you explicitly request it to.

The default service configuration is attach: true.

build

build specifies the build configuration for creating a container image from source, as defined in the Compose Build Specification.

blkio_config

blkio_config defines a set of configuration options to set block I/O limits for a service.

device_read_bps, device_write_bps

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

device_read_iops, device_write_iops

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

weight

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

weight_device

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

cpu_count

cpu_count defines the number of usable CPUs for service container.

cpu_percent

cpu_percent defines the usable percentage of the available CPUs.

cpu_shares

cpu_shares defines, as integer value, a service container's relative CPU weight versus other containers.

cpu_period

cpu_period configures CPU CFS (Completely Fair Scheduler) period when a platform is based on Linux kernel.

cpu_quota

cpu_quota configures CPU CFS (Completely Fair Scheduler) quota when a platform is based on Linux kernel.

cpu_rt_runtime

cpu_rt_runtime configures CPU allocation parameters for platforms with support for real-time scheduler. It can be either an integer value using microseconds as unit or a duration.

cpu_rt_period

cpu_rt_period configures CPU allocation parameters for platforms with support for real-time scheduler. It can be either an integer value using microseconds as unit or a duration.

cpus

cpus define the number of (potentially virtual) CPUs to allocate to service containers. This is a fractional number.0.000 means no limit.

When set, cpus must be consistent with the cpus attribute in the Deploy Specification.

cpuset

cpuset defines the explicit CPUs in which to permit execution. Can be a range 0-3 or a list 0,1

cap_add

cap_add specifies additional container capabilitiesas strings.

cap_drop

cap_drop specifies container capabilities to drop as strings.

cgroup

Requires: Docker Compose2.15.0 and later

cgroup specifies the cgroup namespace to join. When unset, it is the container runtime's decision to select which cgroup namespace to use, if supported.

cgroup_parent

cgroup_parent specifies an optional parent cgroup for the container.

command

command overrides the default command declared by the container image, for example by Dockerfile's CMD.

If the value is null, the default command from the image is used.

If the value is [] (empty list) or '' (empty string), the default command declared by the image is ignored, or in other words overridden to be empty.

Unlike the CMD instruction in a Dockerfile, the command field doesn't automatically run within the context of theSHELL instruction defined in the image. If your command relies on shell-specific features, such as environment variable expansion, you need to explicitly run it within a shell. For example:

The value can also be a list, similar to theexec-form syntaxused by theDockerfile.

configs

configs let services adapt their behaviour without the need to rebuild a Docker image. Services can only access configs when explicitly granted by the configs attribute. Two different syntax variants are supported.

Compose reports an error if config doesn't exist on the platform or isn't defined in theconfigs top-level element in the Compose file.

There are two syntaxes defined for configs: a short syntax and a long syntax.

You can grant a service access to multiple configs, and you can mix long and short syntax.

Short syntax

The short syntax variant only specifies the config name. This grants the container access to the config and mounts it as files into a service’s container’s filesystem. The location of the mount point within the container defaults to /<config_name> in Linux containers, and C:\<config-name> in Windows containers.

The following example uses the short syntax to grant the redis service access to the my_config and my_other_config configs. The value ofmy_config is set to the contents of the file ./my_config.txt, andmy_other_config is defined as an external resource, which means that it has already been defined in the platform. If the external config does not exist, the deployment fails.

Long syntax

The long syntax provides more granularity in how the config is created within the service's task containers.

The following example sets the name of my_config to redis_config within the container, sets the mode to 0440 (group-readable) and sets the user and group to 103. The redis service does not have access to the my_other_configconfig.

container_name

container_name is a string that specifies a custom container name, rather than a name generated by default.

Compose does not scale a service beyond one container if the Compose file specifies acontainer_name. Attempting to do so results in an error.

container_name follows the regex format of [a-zA-Z0-9][a-zA-Z0-9_.-]+

credential_spec

credential_spec configures the credential spec for a managed service account.

If you have services that use Windows containers, you can use file: andregistry: protocols for credential_spec. Compose also supports additional protocols for custom use-cases.

The credential_spec must be in the format file://<filename> or registry://<value-name>.

When using registry:, the credential spec is read from the Windows registry on the daemon's host. A registry value with the given name must be located in:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs

The following example loads the credential spec from a value named my-credential-specin the registry:

Example gMSA configuration

When configuring a gMSA credential spec for a service, you only need to specify a credential spec with config, as shown in the following example:

depends_on

With the depends_on attribute, you can control the order of service startup and shutdown. It is useful if services are closely coupled, and the startup sequence impacts the application's functionality.

Short syntax

The short syntax variant only specifies service names of the dependencies. Service dependencies cause the following behaviors:

Simple example:

Compose guarantees dependency services have been started before starting a dependent service. Compose waits for dependency services to be "ready" before starting a dependent service.

Long syntax

The long form syntax enables the configuration of additional fields that can't be expressed in the short form.

Service dependencies cause the following behaviors:

Compose guarantees dependency services are started before starting a dependent service. Compose guarantees dependency services marked withservice_healthy are "healthy" before starting a dependent service.

deploy

deploy specifies the configuration for the deployment and lifecycle of services, as defined in the Compose Deploy Specification.

develop

Requires: Docker Compose2.22.0 and later

develop specifies the development configuration for maintaining a container in sync with source, as defined in the Development Section.

device_cgroup_rules

device_cgroup_rules defines a list of device cgroup rules for this container. The format is the same format the Linux kernel specifies in the Control Groups Device Whitelist Controller.

devices

devices defines a list of device mappings for created containers in the form ofHOST_PATH:CONTAINER_PATH[:CGROUP_PERMISSIONS].

devices can also rely on the CDI syntax to let the container runtime select a device:

dns

dns defines custom DNS servers to set on the container network interface configuration. It can be a single value or a list.

dns_opt

dns_opt list custom DNS options to be passed to the container’s DNS resolver (/etc/resolv.conf file on Linux).

dns_search defines custom DNS search domains to set on container network interface configuration. It can be a single value or a list.

domainname

domainname declares a custom domain name to use for the service container. It must be a valid RFC 1123 hostname.

driver_opts

Requires: Docker Compose2.27.1 and later

driver_opts specifies a list of options as key-value pairs to pass to the driver. These options are driver-dependent.

Consult thenetwork drivers documentation for more information.

entrypoint

entrypoint declares the default entrypoint for the service container. This overrides the ENTRYPOINT instruction from the service's Dockerfile.

If entrypoint is non-null, Compose ignores any default command from the image, for example the CMDinstruction in the Dockerfile.

See also command to set or override the default command to be executed by the entrypoint process.

In its short form, the value can be defined as a string:

Alternatively, the value can also be a list, in a manner similar to theDockerfile:

If the value is null, the default entrypoint from the image is used.

If the value is [] (empty list) or '' (empty string), the default entrypoint declared by the image is ignored, or in other words, overridden to be empty.

env_file

The env_file attribute is used to specify one or more files that contain environment variables to be passed to the containers.

Relative paths are resolved from the Compose file's parent folder. As absolute paths prevent the Compose file from being portable, Compose warns you when such a path is used to set env_file.

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

env_file can also be a list. The files in the list are processed from the top down. For the same variable specified in two environment files, the value from the last file in the list stands.

List elements can also be declared as a mapping, which then lets you set additional attributes.

required

Requires: Docker Compose2.24.0 and later

The required attribute defaults to true. When required is set to false and the .env file is missing, Compose silently ignores the entry.

format

Requires: Docker Compose2.30.0 and later

The format attribute lets you use an alternative file format for the env_file. When not set, env_file is parsed according to the Compose rules outlined in Env_file format.

raw format lets you use an env_file with key=value items, but without any attempt from Compose to parse the value for interpolation. This let you pass values as-is, including quotes and $ signs.

Env_file format

Each line in an .env file must be in VAR[=[VAL]] format. The following syntax rules apply:

VAL may be omitted, in such cases the variable value is an empty string.=VAL may be omitted, in such cases the variable is unset.

environment

The environment attribute defines environment variables set in the container. environment can use either an array or a map. Any boolean values; true, false, yes, no, should be enclosed in quotes to ensure they are not converted to True or False by the YAML parser.

Environment variables can be declared by a single key (no value to equals sign). In this case Compose relies on you to resolve the value. If the value is not resolved, the variable is unset and is removed from the service container environment.

Map syntax:

Array syntax:

When both env_file and environment are set for a service, values set by environment have precedence.

expose

expose defines the (incoming) port or a range of ports that Compose exposes from the container. These ports must be accessible to linked services and should not be published to the host machine. Only the internal container ports can be specified.

Syntax is <portnum>/[<proto>] or <startport-endport>/[<proto>] for a port range. When not explicitly set, tcp protocol is used.

If the Dockerfile for the image already exposes ports, it is visible to other containers on the network even if expose is not set in your Compose file.

extends

extends lets you share common configurations among different files, or even different projects entirely. With extends you can define a common set of service options in one place and refer to it from anywhere. You can refer to another Compose file and select a service you want to also use in your own application, with the ability to override some attributes for your own needs.

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

Restrictions

When a service is referenced using extends, it can declare dependencies on other resources. These dependencies may be explicitly defined through attributes like volumes, networks, configs, secrets, links, volumes_from, or depends_on. Alternatively, dependencies can reference another service using the service:{name} syntax in namespace declarations such as ipc, pid, or network_mode.

Compose does not automatically import these referenced resources into the extended model. It is your responsibility to ensure all required resources are explicitly declared in the model that relies on extends.

Circular references with extends are not supported, Compose returns an error when one is detected.

Finding referenced service

file value can be:

A service denoted by service must be present in the identified referenced Compose file. Compose returns an error if:

Merging service definitions

Two service definitions, the main one in the current Compose file and the referenced one specified by extends, are merged in the following way:

Mappings

The following keys should be treated as mappings: annotations, build.args, build.labels,build.extra_hosts, deploy.labels, deploy.update_config, deploy.rollback_config,deploy.restart_policy, deploy.resources.limits, environment, healthcheck,labels, logging.options, sysctls, storage_opt, extra_hosts, ulimits.

One exception that applies to healthcheck is that the main mapping cannot specifydisable: true unless the referenced mapping also specifies disable: true. Compose returns an error in this case. For example, the following input:

Produces the following configuration for the cli service. The same output is produced if array syntax is used.

Items under blkio_config.device_read_bps, blkio_config.device_read_iops,blkio_config.device_write_bps, blkio_config.device_write_iops, devices andvolumes are also treated as mappings where key is the target path inside the container.

For example, the following input:

Produces the following configuration for the cli service. Note that the mounted path now points to the new volume name and ro flag was applied.

If the referenced service definition contains extends mapping, the items under it are simply copied into the new merged definition. The merging process is then kicked off again until no extends keys are remaining.

For example, the following input:

Produces the following configuration for the cli service. Here, cli services gets user key from common service, which in turn gets this key from baseservice.

Sequences

The following keys should be treated as sequences: cap_add, cap_drop, configs,deploy.placement.constraints, deploy.placement.preferences,deploy.reservations.generic_resources, device_cgroup_rules, expose,external_links, ports, secrets, security_opt. Any duplicates resulting from the merge are removed so that the sequence only contains unique elements.

For example, the following input:

Produces the following configuration for the cli service.

In case list syntax is used, the following keys should also be treated as sequences:dns, dns_search, env_file, tmpfs. Unlike sequence fields mentioned previously, duplicates resulting from the merge are not removed.

Scalars

Any other allowed keys in the service definition should be treated as scalars.

external_links link service containers to services managed outside of your Compose application.external_links define the name of an existing service to retrieve using the platform lookup mechanism. An alias of the form SERVICE:ALIAS can be specified.

extra_hosts adds hostname mappings to the container network interface configuration (/etc/hosts for Linux).

Short syntax

Short syntax uses plain strings in a list. Values must set hostname and IP address for additional hosts in the form of HOSTNAME=IP.

IPv6 addresses can be enclosed in square brackets, for example:

The separator = is preferred, but : can also be used. Introduced in Docker Compose version2.24.1. For example:

Long syntax

Alternatively, extra_hosts can be set as a mapping between hostname(s) and IP(s)

Compose creates a matching entry with the IP address and hostname in the container's network configuration, which means for Linux /etc/hosts get extra lines:

gpus

Requires: Docker Compose2.30.0 and later

gpus specifies GPU devices to be allocated for container usage. This is equivalent to a device request with an implicit gpu capability.

gpus also can be set as string all to allocate all available GPU devices to the container.

group_add

group_add specifies additional groups, by name or number, which the user inside the container must be a member of.

An example of where this is useful is when multiple containers (running as different users) need to all read or write the same file on a shared volume. That file can be owned by a group shared by all the containers, and specified ingroup_add.

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

healthcheck

The healthcheck attribute declares a check that's run to determine whether or not the service containers are "healthy". It works in the same way, and has the same default values, as the HEALTHCHECK Dockerfile instruction set by the service's Docker image. Your Compose file can override the values set in the Dockerfile.

For more information on HEALTHCHECK, see theDockerfile reference.

interval, timeout, start_period, and start_interval are specified as durations. Introduced in Docker Compose version2.20.2

test defines the command Compose runs to check container health. It can be either a string or a list. If it's a list, the first item must be either NONE, CMD or CMD-SHELL. If it's a string, it's equivalent to specifying CMD-SHELL followed by that string.

Using CMD-SHELL runs the command configured as a string using the container's default shell (/bin/sh for Linux). Both of the following forms are equivalent:

NONE disables the healthcheck, and is mostly useful to disable the Healthcheck Dockerfile instruction set by the service's Docker image. Alternatively, the healthcheck set by the image can be disabled by setting disable: true:

hostname

hostname declares a custom host name to use for the service container. It must be a valid RFC 1123 hostname.

image

image specifies the image to start the container from. image must follow the Open Container Specificationaddressable image format, as [<registry>/][<project>/]<image>[:<tag>|@<digest>].

If the image does not exist on the platform, Compose attempts to pull it based on the pull_policy. If you are also using the Compose Build Specification, there are alternative options for controlling the precedence of pull over building the image from source, however pulling the image is the default behavior.

image may be omitted from a Compose file as long as a build section is declared. If you are not using the Compose Build Specification, Compose won't work if image is missing from the Compose file.

init

init runs an init process (PID 1) inside the container that forwards signals and reaps processes. Set this option to true to enable this feature for the service.

The init binary that is used is platform specific.

ipc

ipc configures the IPC isolation mode set by the service container.

isolation

isolation specifies a container’s isolation technology. Supported values are platform specific.

labels

labels add metadata to containers. You can use either an array or a map.

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

Compose creates containers with canonical labels:

The com.docker.compose label prefix is reserved. Specifying labels with this prefix in the Compose file results in a runtime error.

label_file

Requires: Docker Compose2.32.2 and later

The label_file attribute lets you load labels for a service from an external file or a list of files. This provides a convenient way to manage multiple labels without cluttering the Compose file.

The file uses a key-value format, similar to env_file. You can specify multiple files as a list. When using multiple files, they are processed in the order they appear in the list. If the same label is defined in multiple files, the value from the last file in the list overrides earlier ones.

If a label is defined in both the label_file and the labels attribute, the value in labels takes precedence.

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

Containers for the linked service are reachable at a hostname identical to the alias, or the service name if no alias is specified.

Links are not required to enable services to communicate. When no specific network configuration is set, any service is able to reach any other service at that service’s name on the default network. If services specify the networks they are attached to, links does not override the network configuration. Services that are not connected to a shared network are not be able to communicate with each other. Compose doesn't warn you about a configuration mismatch.

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

logging

logging defines the logging configuration for the service.

The driver name specifies a logging driver for the service's containers. The default and available values are platform specific. Driver specific options can be set with options as key-value pairs.

mac_address

Available with Docker Compose version 2.24.0 and later.

mac_address sets a Mac address for the service container.

Container runtimes might reject this value, for example Docker Engine >= v25.0. In that case, you should use networks.mac_address instead.

mem_limit

mem_limit configures a limit on the amount of memory a container can allocate, set as a string expressing a byte value.

When set, mem_limit must be consistent with the limits.memory attribute in the Deploy Specification.

mem_reservation

mem_reservation configures a reservation on the amount of memory a container can allocate, set as a string expressing a byte value.

When set, mem_reservation must be consistent with the reservations.memory attribute in the Deploy Specification.

mem_swappiness

mem_swappiness defines as a percentage, a value between 0 and 100, for the host kernel to swap out anonymous memory pages used by a container.

The default value is platform specific.

memswap_limit

memswap_limit defines the amount of memory the container is allowed to swap to disk. This is a modifier attribute that only has meaning if memory is also set. Using swap lets the container write excess memory requirements to disk when the container has exhausted all the memory that is available to it. There is a performance penalty for applications that swap memory to disk often.

network_mode

network_mode sets a service container's network mode.

For more information container networks, see theDocker Engine documentation.

When set, the networks attribute is not allowed and Compose rejects any Compose file containing both attributes.

networks

The networks attribute defines the networks that service containers are attached to, referencing entries under thenetworks top-level element. The networks attribute helps manage the networking aspects of containers, providing control over how services are segmented and interact within the Docker environment. This is used to specify which networks the containers for that service should connect to. This is important for defining how containers communicate with each other and externally.

For more information about the networks top-level element, see Networks.

Implicit default network

If networks is empty or absent from the Compose file, Compose considers an implicit definition for the service to be connected to the default network:

This example is actually equivalent to:

If you want the service to not be connected a network, you must set network_mode: none.

aliases

aliases declares alternative hostnames for the service on the network. Other containers on the same network can use either the service name or an alias to connect to one of the service's containers.

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

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

In the following example, service frontend is able to reach the backend service at the hostname backend or database on the back-tier network. The service monitoringis able to reach same backend service at backend or mysql on the admin network.

interface_name

Requires: Docker Compose2.36.0 and later

interface_name lets you specify the name of the network interface used to connect a service to a given network. This ensures consistent and predictable interface naming across services and networks.

Running the example Compose application shows:

ipv4_address, ipv6_address

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

The corresponding network configuration in the top-level networks section must have anipam attribute with subnet configurations covering each static address.

link_local_ips specifies a list of link-local IPs. Link-local IPs are special IPs which belong to a well known subnet and are purely managed by the operator, usually dependent on the architecture where they are deployed.

Example:

mac_address

Requires: Docker Compose2.23.2 and later

mac_address sets the Mac address used by the service container when connecting to this particular network.

gw_priority

Requires: Docker Compose2.33.1 and later

The network with the highest gw_priority is selected as the default gateway for the service container. If unspecified, the default value is 0.

In the following example, app_net_2 will be selected as the default gateway.

priority

priority indicates in which order Compose connects the service’s containers to its networks. If unspecified, the default value is 0.

If the container runtime accepts a mac_address attribute at service level, it is applied to the network with the highest priority. In other cases, use attributenetworks.mac_address.

priority does not affect which network is selected as the default gateway. Use thegw_priority attribute instead.

priority does not control the order in which networks connections are added to the container, it cannot be used to determine the device name (eth0 etc.) in the container.

oom_kill_disable

If oom_kill_disable is set, Compose configures the platform so it won't kill the container in case of memory starvation.

oom_score_adj

oom_score_adj tunes the preference for containers to be killed by platform in case of memory starvation. Value must be within -1000,1000 range.

pid

pid sets the PID mode for container created by Compose. Supported values are platform specific.

pids_limit

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

When set, pids_limit must be consistent with the pids attribute in the Deploy Specification.

platform

platform defines the target platform the containers for the service run on. It uses the os[/arch[/variant]] syntax.

The values of os, arch, and variant must conform to the convention used by the OCI Image Spec.

Compose uses this attribute to determine which version of the image is pulled and/or on which platform the service’s build is performed.

ports

The ports is used to define the port mappings between the host machine and the containers. This is crucial for allowing external access to services running inside containers. It can be defined using short syntax for simple port mapping or long syntax, which includes additional options like protocol type and network mode.

Port mapping must not be used with network_mode: host. Doing so causes a runtime error because network_mode: host already exposes container ports directly to the host network, so port mapping isn’t needed.

Short syntax

The short syntax is a colon-separated string to set the host IP, host port, and container port in the form:

[HOST:]CONTAINER[/PROTOCOL] where:

Ports can be either a single value or a range. HOST and CONTAINER must use equivalent ranges.

You can either specify both ports (HOST:CONTAINER), or just the container port. In the latter case, the container runtime automatically allocates any unassigned port of the host.

HOST:CONTAINER should always be specified as a (quoted) string, to avoid conflicts with YAML base-60 float.

IPv6 addresses can be enclosed in square brackets.

Examples:

If host IP mapping is not supported by a container engine, Compose rejects the Compose file and ignores the specified host IP.

Long syntax

The long form syntax lets you configure additional fields that can't be expressed in the short form.

post_start

Requires: Docker Compose2.30.0 and later

post_start defines a sequence of lifecycle hooks to run after a container has started. The exact timing of when the command is run is not guaranteed.

For more information, seeUse lifecycle hooks.

pre_stop

Requires: Docker Compose2.30.0 and later

pre_stop defines a sequence of lifecycle hooks to run before the container is stopped. These hooks won't run if the container stops by itself or is terminated suddenly.

Configuration is equivalent to post_start.

privileged

privileged configures the service container to run with elevated privileges. Support and actual impacts are platform specific.

profiles

profiles defines a list of named profiles for the service to be enabled under. If unassigned, the service is always started but if assigned, it is only started if the profile is activated.

If present, profiles follow the regex format of [a-zA-Z0-9][a-zA-Z0-9_.-]+.

provider

Requires: Docker Compose2.36.0 and later

provider can be used to define a service that Compose won't manage directly. Compose delegated the service lifecycle to a dedicated or third-party component.

As Compose runs the application, the awesomecloud binary is used to manage the database service setup. Dependent service app receives additional environment variables prefixed by the service name so it can access the resource.

For illustration, assuming awesomecloud execution produced variables URL and API_KEY, the app service runs with environment variables DATABASE_URL and DATABASE_API_KEY.

As Compose stops the application, the awesomecloud binary is used to manage the database service tear down.

The mechanism used by Compose to delegate the service lifecycle to an external binary is described here.

For more information on using the provider attribute, seeUse provider services.

type

type attribute is required. It defines the external component used by Compose to manage setup and tear down lifecycle events.

options

options are specific to the selected provider and not validated by the compose specification

pull_policy

pull_policy defines the decisions Compose makes when it starts to pull images. Possible values are:

read_only

read_only configures the service container to be created with a read-only filesystem.

restart

restart defines the policy that the platform applies on container termination.

You can find more detailed information on restart policies in theRestart Policies (--restart)section of the Docker run reference page.

runtime

runtime specifies which runtime to use for the service’s containers.

For example, runtime can be the name of an implementation of OCI Runtime Spec, such as "runc".

The default is runc. To use a different runtime, seeAlternative runtimes.

scale

scale specifies the default number of containers to deploy for this service. When both are set, scale must be consistent with the replicas attribute in the Deploy Specification.

secrets

The secrets attribute grants access to sensitive data defined by the secrets top-level element on a per-service basis. Services can be granted access to multiple secrets.

Two different syntax variants are supported; the short syntax and the long syntax. Long and short syntax for secrets may be used in the same Compose file.

Compose reports an error if the secret doesn't exist on the platform or isn't defined in thesecrets top-level section of the Compose file.

Defining a secret in the top-level secrets must not imply granting any service access to it. Such grant must be explicit within service specification as secrets service element.

Short syntax

The short syntax variant only specifies the secret name. This grants the container access to the secret and mounts it as read-only to /run/secrets/<secret_name>within the container. The source name and destination mountpoint are both set to the secret name.

The following example uses the short syntax to grant the frontend service access to the server-certificate secret. The value of server-certificate is set to the contents of the file ./server.cert.

Long syntax

The long syntax provides more granularity in how the secret is created within the service's containers.

Note that support for uid, gid, and mode attributes are not implemented in Docker Compose when the source of the secret is a file. This is because bind-mounts used under the hood don't allow uid remapping.

The following example sets the name of the server-certificate secret file to server.certwithin the container, sets the mode to 0440 (group-readable), and sets the user and group to 103. The value of server-certificate is set to the contents of the file ./server.cert.

security_opt

security_opt overrides the default labeling scheme for each container.

For further default labeling schemes you can override, seeSecurity configuration.

shm_size

shm_size configures the size of the shared memory (/dev/shm partition on Linux) allowed by the service container. It's specified as a byte value.

stdin_open

stdin_open configures a service's container to run with an allocated stdin. This is the same as running a container with the-i flag. For more information, seeKeep stdin open.

Supported values are true or false.

stop_grace_period

stop_grace_period specifies how long Compose must wait when attempting to stop a container if it doesn't handle SIGTERM (or whichever stop signal has been specified withstop_signal), before sending SIGKILL. It's specified as a duration.

Default value is 10 seconds for the container to exit before sending SIGKILL.

stop_signal

stop_signal defines the signal that Compose uses to stop the service containers. If unset containers are stopped by Compose by sending SIGTERM.

storage_opt

storage_opt defines storage driver options for a service.

sysctls

sysctls defines kernel parameters to set in the container. sysctls can use either an array or a map.

You can only use sysctls that are namespaced in the kernel. Docker does not support changing sysctls inside a container that also modify the host system. For an overview of supported sysctls, refer toconfigure namespaced kernel parameters (sysctls) at runtime.

tmpfs

tmpfs mounts a temporary file system inside the container. It can be a single value or a list.

Available options:

tty

tty configures a service's container to run with a TTY. This is the same as running a container with the-t or --tty flag. For more information, seeAllocate a pseudo-TTY.

Supported values are true or false.

ulimits

ulimits overrides the default ulimits for a container. It's specified either as an integer for a single limit or as mapping for soft/hard limits.

user

user overrides the user used to run the container process. The default is set by the image, for example Dockerfile USER. If it's not set, then root.

userns_mode

userns_mode sets the user namespace for the service. Supported values are platform specific and may depend on platform configuration.

uts

Requires: Docker Compose2.15.1 and later

uts configures the UTS namespace mode set for the service container. When unspecified it is the runtime's decision to assign a UTS namespace, if supported. Available values are:

volumes

The volumes attribute define mount host paths or named volumes that are accessible by service containers. You can use volumes to define multiple types of mounts; volume, bind, tmpfs, or npipe.

If the mount is a host path and is only used by a single service, it can be declared as part of the service definition. To reuse a volume across multiple services, a named volume must be declared in the volumes top-level element.

The following example shows a named volume (db-data) being used by the backend service, and a bind mount defined for a single service.

For more information about the volumes top-level element, see Volumes.

Short syntax

The short syntax uses a single string with colon-separated values to specify a volume mount (VOLUME:CONTAINER_PATH), or an access mode (VOLUME:CONTAINER_PATH:ACCESS_MODE).

The SELinux re-labeling bind mount option is ignored on platforms without SELinux.

Relative host paths are only supported by Compose that deploy to a local container runtime. This is because the relative path is resolved from the Compose file’s parent directory which is only applicable in the local case. When Compose deploys to a non-local platform it rejects Compose files which use relative host paths with an error. To avoid ambiguities with named volumes, relative paths should always begin with . or ...

For bind mounts, the short syntax creates a directory at the source path on the host if it doesn't exist. This is for backward compatibility with docker-compose legacy. It can be prevented by using long syntax and setting create_host_path to false.

Long syntax

The long form syntax lets you configure additional fields that can't be expressed in the short form.

Working with large repositories or monorepos, or with virtual file systems that are no longer scaling with your codebase? Compose now takes advantage ofSynchronized file shares and automatically creates file shares for bind mounts. Ensure you're signed in to Docker with a paid subscription and have enabled both Access experimental features and Manage Synchronized file shares with Compose in Docker Desktop's settings.

volumes_from

volumes_from mounts all of the volumes from another service or container. You can optionally specify read-only access ro or read-write rw. If no access level is specified, then read-write access is used.

You can also mount volumes from a container that is not managed by Compose by using the container: prefix.

working_dir

working_dir overrides the container's working directory which is specified by the image, for example Dockerfile's WORKDIR.