Search or ask Docker

Define services in Docker Compose

Explore all the attributes the services top-level element can have.

View Markdown

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.

Where attributes are defined

Services, jobs, and init containers share many attributes. Each attribute is documented once, on one of the following pages.

PageServicesJobspre_start init containers
Container specification✓✓✓
Workload specification✓✓
Services✓
Jobs✓
  • The container specification covers the attributes of a single container, such as image, command, and environment.
  • The workload specification covers how Compose builds, exposes, and health-checks a workload, which can be a service or a job, and whether it is included in a given run. It uses attributes such as build, ports, healthcheck, and profiles.

Some attributes are shared but behave differently for services and jobs: depends_on and extends. The workload specification describes each difference.

Examples

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.

services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"

  db:
    image: postgres:18
    environment:
      POSTGRES_USER: example
      POSTGRES_DB: exampledb

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.

services:
  proxy:
    image: nginx
    volumes:
      - type: bind
        source: ./proxy/nginx.conf
        target: /etc/nginx/conf.d/default.conf
        read_only: true
    ports:
      - 80:80
    depends_on:
      - backend

  backend:
    build:
      context: backend
      target: builder

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

Attributes

attach

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.

container_name

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

container_name: my-web-container

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

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

deploy

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

develop

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

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.

external_links:
  - redis
  - database:mysql
  - database:postgresql

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.

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

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 as depends_on, so they determine the order of service startup.

post_start

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.

  • command: Specifies the command to run once the container starts. This attribute is required, and you can choose to use either the shell form or the exec form.
  • user: The user to run the command. If not set, the command is run with the same user as the main service command.
  • privileged: Lets the post_start command run with privileged access.
  • working_dir: The working directory in which to run the command. If not set, it is run in the same working directory as the main service command.
  • environment: Sets environment variables specifically for the post_start command. While the command inherits the environment variables defined for the service’s main command, this section lets you add new variables or override existing ones.
services:
  test:
    post_start:
      - command: ./do_something_on_startup.sh
        user: root
        privileged: true
        environment:
          - FOO=BAR

For more information, see Use lifecycle hooks.

pre_start

Requires: Docker Compose 5.3.0 and later

pre_start defines a sequence of init containers to run before the service container is started. Each step runs to completion, in declared order, and the service container only starts once every step has exited 0. A non-zero exit fails the bring-up of the service and its dependents.

Unlike post_start and pre_stop, which run a command inside the running service container, each pre_start step runs in its own ephemeral container, created after the service container is created but before it is started.

A pre_start step is a full container specification, so you can declare any container attribute on the step. The step inherits every attribute it doesn't declare from the service. A pre_start container is the service container with the image, the command, and anything else the step declares replaced. In particular:

  • image: If omitted, the parent service's image is used.
  • command: Optional when the chosen image's entrypoint already runs the intended command.
  • environment: The step inherits the environment of the service's main command. Declared values are appended to the inherited ones or override them.
  • volumes: If omitted, the step shares the service's declared volume mounts. Re-declaring a mount overrides how the step mounts it, for example read-write where the service mounts it read-only.

Re-declaring an inherited attribute follows the same rules as merging Compose files: mappings merge, scalars replace, sequences append, and the !reset and !override tags are available.

Attributes that only apply to an orchestrated workload aren't part of the container specification, so you can't declare them on a step. These include ports, healthcheck, depends_on, and build. The workload specification defines them.

In addition to container attributes, a step supports:

  • per_replica: Whether the step runs once per service replica (true), or once for the service as a whole before any replica starts (false, the default). Set it to true for per-instance work, such as initializing a replica's anonymous volumes or registering a per-replica network identity.

pre_start steps only run once the service's depends_on conditions have been satisfied, so a step can rely on those dependencies the same way the main service command does. Apre_start container joins the same networks as the service, so it can reach services declared in depends_on, and shares the service's declared volume mounts so files it produces in a shared volume are visible to the service.

With per_replica: false and a scaled service, only mounts that are shared across replicas (named volumes, bind mounts) are usable. Per-instance mounts (tmpfs, anonymous volumes) cannot be addressed by a single run. This is not an error. The steps run without access to per-instance mounts. Data a per_replica: false step must share with the service belongs in a named volume or bind mount.

A pre_start step that has already succeeded for its current definition is not re-run on a subsequent up, nor when the service container restarts under its restart policy. A step runs again when its definition changes, when the previous run did not succeed, or when the service is recreated. For example, after a change to the service configuration or an explicit forced recreation.

services:
  app:
    image: myapp:latest
    depends_on:
      db:
        condition: service_healthy
    pre_start:
      - command: ["./manage.py", "migrate"]
      - image: busybox
        command: sh -c 'chown -R 1000:1000 /data'
    volumes:
      - data:/data

  db:
    image: postgres:16

volumes:
  data:

pre_stop

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.

provider

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.

  database:
    provider:
      type: awesomecloud
      options:
        type: mysql
        foo: bar
  app:
    image: myapp
    depends_on:
       - database

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 in the Compose extensibility documentation.

For more information on using the provider attribute, see Use 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

restart

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

  • no: The default restart policy. It does not restart the container under any circumstances.
  • always: The policy always restarts the container until its removal.
  • on-failure[:max-retries]: The policy restarts the container if the exit code indicates an error. Optionally, limit the number of restart retries the Docker daemon attempts.
  • unless-stopped: The policy restarts the container irrespective of the exit code but stops restarting when the service is stopped or removed.
    restart: "no"
    restart: always
    restart: on-failure
    restart: on-failure:3
    restart: unless-stopped

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

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.