Docker Compose でのサービス定義

サービスとはアプリケーション内でのコンピューターリソースを抽象化した定義のことです。 他のコンポーネントとは独立してスケール変更や置き換えが可能です。 サービスは一連のコンテナーにより構成されるものであり、レプリケーション要件や配置制約に基づくプラットフォーム上で稼働します。 サービスがコンテナーにより構成されるというのは、つまり Docker イメージと数々の実行時引数によって定義されるものであるからです。 サービスに属するコンテナーはすべて、そういった引数により一意に生成されます。

Compose ファイルとは services というトップレベル要素により宣言しなければなりません。 そこではマッピング形式により、キーとしてサービス名を文字表現により、またその値としてサービス定義を指定します。 一つのサービス定義には、各サービスコンテナーに適用される設定を記述します。

各サービスには build セクションを含める場合があります。 これはサービス向けにどのようにして Docker イメージを生成するのかを定めるものです。 Compose ではこのサービス定義を用いて Docker イメージをビルドする機能をサポートしています。 この記述がないのであれば build セクションによる機能は無視されますが、それでも Compose ファイルは文法的に正しいものとして扱われます。 ビルド機能は Compose 仕様においてはオプション的な位置づけであり、その詳細については Compose ビルド仕様 のドキュメントにおいて説明しています。

各サービスでは実行時の制約やコンテナー起動のための要件を定めます。 deploy セクションはその制約を取りまとめ、限られたリソースの中からコンテナー起動要件を満たすプラットフォーム向けのデプロイ戦術を調整します。 デプロイのサポートは Compose 仕様のオプション機能です。 詳しくは Compose デプロイ仕様 のドキュメントを参照してください。 この機能が実装されていない場合 deploy セクションは無視されますが、Compose ファイルは有効なものとして扱われます。

単純な例

以下の例は Docker Compose を使って、2 つの単純なサービスを定義し、そのイメージ、マップポート、基本的な環境変数の設定方法について示すものです。

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

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

応用的な例

以下の例においては proxy サービスが Nginx イメージを利用し、コンテナーに対してローカルにある Nginx 設定ファイルをマウントしています。 ポート 80 を開放し、また backend サービスに依存する設定を行っています。

backend サービスは、ステージ builder においてビルドされるように設定されており、backend ディレクトリに置かれている Dockerfile からイメージがビルドされます。

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

Compose ファイルの例に関しては Awesome Compose サンプル を参照してください。

属性

annotations

annotations はコンテナーの説明文を定義します。 annotations は配列またはマップを用いることが可能です。

annotations:
  com.example.foo: bar
annotations:
  - com.example.foo=bar

attach

必要条件: Docker Compose 2.20.0 およびそれ以降

attach が定義されその値が false である場合、サービスのログを明示的に収集する要求がない限り、その収集を行いません。

サービス設定のデフォルトは attach: true です。

build

build は、ソースからコンテナーイメージを生成するためのビルド設定を定義します。 詳しくは Compose ビルド仕様 に示されています。

blkio_config

blkio_config は、サービスに対するブロック I/O 制限を指示する一連の設定オプションを定義します。

services:
  foo:
    image: busybox
    blkio_config:
       weight: 300
       weight_device:
         - path: /dev/sda
           weight: 400
       device_read_bps:
         - path: /dev/sdb
           rate: '12mb'
       device_read_iops:
         - path: /dev/sdb
           rate: 120
       device_write_bps:
         - path: /dev/sdb
           rate: '1024k'
       device_write_iops:
         - path: /dev/sdb
           rate: 30

device_read_bps, device_write_bps

指定するデバイスにおいて読み書き動作に対する 1 秒あたりのバイト数の制限を設定します。 項目をリスト内に設定し、以下の 2 つのキーがなければなりません。

  • path: 対象デバイスへのシンボリックパスを定義します。
  • rate: バイト数を表す整数値か、あるいはバイト値を表す文字列表現を指定します。

device_read_iops, device_write_iops

指定されたデバイスに対して、読み書き動作に対する 1 秒あたりの処理数の制限を設定します。 項目をリスト内に設定し、以下の 2 つのキーがなければなりません。

  • path: 対象デバイスへのシンボリックパスを定義します。
  • rate: 1 秒あたりの処理数として許容される整数値を指定します。

weight

別のサービスとの対比として 1 つのサービスに割り当てる帯域幅の割合を変更します。 10 から 1000 までの整数値を指定します。 デフォルトは 500 です。

weight_device

デバイスごとに帯域幅の割合を調整します。 項目をリスト内に設定し、以下の 2 つのキーがなければなりません。

  • path: 対象デバイスへのシンボリックパスを定義します。
  • weight: 10 から 1000 の整数値を指定します。

cpu_count

cpu_count はサービスコンテナーにおいて利用する CPU 数を定義します。

cpu_percent

cpu_percent は利用可能な CPU の中から、その利用割合を定義します。

cpu_shares

cpu_shares は整数値を指定するものであり、別コンテナーに対するコンテナーの相対的な CPU 重みを定義します。

cpu_period

プラットフォームが Linux ベースのものである場合に cpu_period は CPU の CFS (Completely Fair Scheduler) 時間を定めます。

cpu_quota

プラットフォームが Linux ベースのものである場合に cpu_period は CPU の CFS (Completely Fair Scheduler) クォータを定めます。

cpu_rt_runtime

cpu_rt_runtime はリアルタイムスケジューラーをサポートするプラットフォームにおいて CPU 割り当てパラメーターを設定します。 ここにはマイクロ秒を単位とする整数値を指定するか 時間 を指定することができます。

 cpu_rt_runtime: '400ms'
 cpu_rt_runtime: '95000'

cpu_rt_period

cpu_rt_runtime はリアルタイムスケジューラーをサポートするプラットフォームにおいて CPU 割り当てパラメーターを設定します。 ここにはマイクロ秒を単位とする整数値を指定するか 時間 を指定することができます。

 cpu_rt_period: '1400us'
 cpu_rt_period: '11000'

cpus

cpus はサービスコンテナーに割り当てる (仮想の) CPU 数を指定します。 小数を用いるものであり 0.000 は無制限を表します。

これを設定する場合は デプロイ仕様 にある cpus 属性と一致していなければなりません。

cpuset

cpuset は実行を許可する CPU を明示的に指定します。 範囲指定 0-3 やリスト形式 0,1 のような指定とします。

cap_add

cap_add は追加コンテナーの ケーパビリティー を文字列で指定します。

cap_add:
  - ALL

cap_drop

cap_drop は削除するコンテナー ケーパビリティーを文字列で指定します。

cap_drop:
  - NET_ADMIN
  - SYS_ADMIN

cgroup

必要条件: Docker Compose 2.15.0 およびそれ以降

cgroup は参加する cgroup 名前空間を指定します。 これが設定されていない場合、どの cgroup 名前空間が用いられるかは、コンテナー実行時に選定されます。 ただしそれはその機能がサポートされている場合に限ります。

  • host: cgroup 名前空間 Container runtime においてコンテナーを実行します。
  • private: 独自のプライベートな cgroup 名前空間においてコンテナーを実行します。

cgroup_parent

cgroup_parent はオプションとしてコンテナーに対する親 cgroup を指定します。

cgroup_parent: m-executor-abcd

command

command は、たとえば Dockerfile 内の CMD のような、コンテナーイメージによって宣言されたデフォルトコマンドを上書きします。

command: bundle exec thin -p 3000

その値が null である場合、イメージ内にあるデフォルトコマンドが用いられます。

その値が [] (空リスト) または '' (空文字列) である場合、イメージ内に宣言されているデフォルトコマンドは無視されます。 つまり空っぽとして上書きされます。

メモ

Dockerfile における CMD 命令とは異なり command フィールドは、イメージ内に定義される SHELL 命令の内部では自動実行されません。 command がたとえば環境変数の展開などのような、シェル固有の機能に基づいている場合、シェル内において明示的に実行する必要があります。 たとえば以下のとおりです。

command: /bin/sh -c 'echo "hello $$HOSTNAME"'

その値はリストにすることもできます。 それはちょうど Dockerfile において用いられる exec 形式の文法 と同様になります。

configs

configs は Docker イメージを再ビルドすることなく、サービスの動作を変更できるようにします。 サービスは configs 属性により明示的にアクセス許可が与えられている場合にのみ config にアクセスすることができます。 文法は 2 つの形式がサポートされています。

config がプラットフォーム上に存在しない場合、あるいは Compose ファイルの トップレベル要素 configs において定義されていない場合、Compose はエラーを出力します。

config に用いられる 2 つの文法とは、短い文法と長い文法です。

サービスへは、複数の config へのアクセス権限を与えることができます。 また短い文法、長い文法は両者を混在させて記述することもできます。

短い文法

短い文法では config 名のみを指定します。 これはコンテナーから config へのアクセスを許可し、その config はサービスのコンテナー内にあるファイルシステムに対してファイルとしてマウントされます。 コンテナーにおけるマウントポイントは、Linux コンテナーでのデフォルトが /<config 名>、Windows コンテナーでのデフォルトが C:\<config 名> です。

以下の例は短い文法を使って、redis サービスが 2 つの config my_configmy_other_config へのアクセスを許可するものです。 my_config の値は ./my_config.txt ファイルの内容を設定しています。 また my_other_config は外部リソースとして定義されています。 外部であるということは、プラットフォーム上においてあらかじめ定義済みであることを意味します。 したがって外部 config が存在しなかった場合、デプロイは失敗します。

services:
  redis:
    image: redis:latest
    configs:
      - my_config
      - my_other_config
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

長い文法

長い文法は、これを使うことでサービスのタスクコンテナー内において config をより詳細に定めることができます。

  • source: プラットフォーム上に存在する config 名。
  • target: サービスのタスクコンテナーにマウントされるファイルのパスおよびファイル名。 指定がなかった場合のデフォルトは /<source>
  • uid および gid: サービスのタスクコンテナー内にマウントされる config ファイルを所有する uid および gid の数値。
  • mode: サービスのタスクコンテナーにマウントされるファイルの パーミッション。 8 進数表現。 デフォルト値はワールド読み込み可 (0444)。 書き込みビットは無視され、実行ビットは設定可能。

以下の例ではコンテナー内の redis_config に対して my_config という名前を設定しています。 そのモードは 0440 (グループ読み込み可) であり、ユーザーとグループは 103 に設定しています。 redis サービスは my_other_config という config に対してのアクセス権限は持っていません。

services:
  redis:
    image: redis:latest
    configs:
      - source: my_config
        target: /redis_config
        uid: "103"
        gid: "103"
        mode: 0440
configs:
  my_config:
    external: true
  my_other_config:
    external: true

container_name

container_name は、カスタムのコンテナー名を文字列にて指定します。 これによってデフォルトで生成されるコンテナー名は用いられなくなります。

container_name: my-web-container

Compose ファイルに container_name の指定を行った場合、そのサービスが複数コンテナーにスケールアップすることはできなくなります。 これを行おうとした場合にはエラーが発生します。

container_name は正規表現では [a-zA-Z0-9][a-zA-Z0-9_.-]+ に従います。

credential_spec

credential_spec は、管理しているサービスアカウントの資格情報スペック (credential spec) を設定します。

そのサービスが Windows コンテナーを利用している場合、資格情報スペックに対しては file: または registry: プロトコルが指定可能です。 Compose はカスタムユースケース向けに、プロトコル追加機能をサポートしています。

credential_specfile://<ファイル名> または registry://<値の名> という書式でなければなりません。

credential_spec:
  file: my-credential-spec.json

registry: を利用した場合、デーモンが稼働するホストの Windows レジストリから資格情報スペックを読み込みます。 レジストリ値と指定された名前は、以下の場所に存在していなければなりません。

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

次の例では、レジストリ内の my-credential-spec という名称に割り振られた値から、資格情報スペックをロードします。

credential_spec:
  registry: my-credential-spec

gMSA 設定例

gMSA 資格情報スペックをサービスに対して設定する場合は、config を使って資格情報スペックを指定するだけで済みます。 その具体例は以下のとおりです。

services:
  myservice:
    image: myimage:latest
    credential_spec:
      config: my_credential_spec

configs:
  my_credentials_spec:
    file: ./my-credential-spec.json

depends_on

depends_on 属性を用いれば、サービスの起動終了の順を制御できます。 複数サービスが互いに密接に結びついていて、起動順序がアプリケーション機能に影響を及ぼすような場合に、この属性が必要になってきます。

短い文法

短い文法では依存するサービス名のみを指定します。 サービスの依存関係に応じて以下の動作となります。

  • Compose はサービスの生成を依存順に行います。 以下の例では dbredisweb よりも先に生成されます。

  • Compose はサービスの削除を依存順に行います。 以下の例で webdbredis よりも前に削除されます。

単純な例

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

依存するサービスを持つ対象サービスは、その依存サービスが起動してから対象サービスが起動するよう、Compose が確実に保証します。 依存するサービスが起動するまで、その対象サービスは「待機状態」に置かれます。

長い文法

長い文法では追加の設定フィールドの指定が可能であり、これは短い文法形式では表現することはできません。

  • restart: これが true に設定されていると、Compose は依存サービスが更新された時に、対象サービスを再起動します。 これは Compose 処理として制御される明示的な再起動を実現します。 そしてコンテナーが停止した際にコンテナーランタイムが行う自動再起動には適用されません。 この機能は Docker Compose バージョン 2.17.0 から導入されたものです。

  • condition: 依存サービスがどのような状態になったときに条件が満たされたとするかを定めます。

    • service_started: 前述した短い文法での内容と同じです。
    • service_healthy: 対象サービスの起動するには、依存サービスが「健康的 (healthy)」(healthcheck に説明) となっていることを指定します。
    • service_completed_successfully: 対象サービスが起動するには、依存サービスが正常に実行していることを指定します。
  • required: これが false に設定されていると、依存サービスが起動されなかったり利用不能である場合に、Compose が警告のみを行います。 required が定義されていない場合のデフォルト値は true です。 この機能は Docker Compose バージョン 2.20.0 から導入されました。

サービスの依存関係に応じて以下の動作となります。

  • Compose はサービスの生成を依存順に行います。 以下の例では dbredisweb よりも先に生成されます。

  • Compose は依存サービスが service_healthy と印づけられる時まで待ちます。 以下の例では db が「健康的」になってから web が生成されます。

  • Compose はサービスの削除を依存順に行います。 以下の例で webdbredis よりも前に削除されます。

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
        restart: true
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: postgres

依存するサービスを持つ対象サービスは、その依存サービスが起動してから対象サービスが起動するよう、Compose が確実に保証します。 service_healthy として印づけられた依存サービスを持つ対象サービスは、対象サービスの起動の際には依存サービスが「健康的」であることを確実に保証します。

deploy

deploy 識別子は、サービスのデプロイとライフサイクルの設定を行います。 これは Compose デプロイ仕様 において定義されています。

develop

必要条件: Docker Compose 2.22.0 およびそれ以降

develop 識別子は、コンテナーとソースを同期するための開発設定を指定します。 これは 開発の節 において定義されています。

device_cgroup_rules

device_cgroup_rules は対象コンテナー向けのデバイス cgroup ルールのリストを定義します。 その書式は Linux カーネルが Control Groups Device Whitelist Controller において指定している書式と同様です。

device_cgroup_rules:
  - 'c 1:3 mr'
  - 'a 7:* rmw'

devices

devices は生成されるコンテナーのデバイスマッピング一覧を定義します。 その形式は HOST_PATH:CONTAINER_PATH[:CGROUP_PERMISSIONS] です。

devices:
  - "/dev/ttyUSB0:/dev/ttyUSB0"
  - "/dev/sda:/dev/xvda:rwm"

devices では CDI 文法の指定も可能であり、これによってコンテナーランタイムがデバイスを選択できるようにします。

devices:
  - "vendor1.com/device=gpu"

dns

dns は、コンテナーのネットワークインターフェースに設定するカスタムな DNS サーバーを指定します。 単一の値かリスト形式による指定が可能です。

dns: 8.8.8.8
dns:
  - 8.8.8.8
  - 9.9.9.9

dns_opt

dns_opt は、カスタム DNS サーバーへのオプションリストであり、コンテナーの DNS リボルバー (Linux における /etc/resolv.conf ファイル) に受け渡されます。

dns_opt:
  - use-vc
  - no-tld-query

dns_search は、コンテナーのネットワークインターフェースに設定するカスタムな DNS 検索ドメインを指定します。 単一の値かリスト形式による指定が可能です。

dns_search: example.com
dns_search:
  - dc1.example.com
  - dc2.example.com

domainname

domainname は、サービスコンテナーにて用いるカスタムドメイン名を宣言します。 RFC 1123 に従ったホスト名でなければなりません。

driver_opts

必要条件: Docker Compose 2.27.1 およびそれ以降

driver_opts はキーバリューペアによるオプションリストを指定するものであり、ドライバーにこれが受け渡されます。 オプションはドライバー固有のものを指定します。

services:
  app:
    networks:
      app_net:
        driver_opts:
          com.docker.network.bridge.host_binding_ipv4: "127.0.0.1"

詳しくは ネットワークドライバーのドキュメント を参照してください。

entrypoint

entrypoint はサービスコンテナーにおけるデフォルトのエントリーポイントを宣言します。 これはサービスの Dockerfile に記述された ENTRYPOINT 命令を上書きします。

entrypoint がヌルではない場合、イメージ内のデフォルトコマンド、たとえば Dockerfile 内の CMD は無視されます。

エントリーポイント処理として実行されるデフォルトコマンドの上書き方法については command も参照してください。

短い書式では値を文字列により指定します。

entrypoint: /code/entrypoint.sh

またはリスト形式により指定することもできます。 その形式は Dockerfile における方法と同様です。

entrypoint:
  - php
  - -d
  - zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
  - -d
  - memory_limit=-1
  - vendor/bin/phpunit

値が null である場合、デフォルトのエントリーポイントはイメージ内のものが用いられます。

その値が [] (空リスト) または '' (空文字列) である場合、イメージ内に宣言されているデフォルトのエントリーポイントは無視されます。 つまり空っぽとして上書きされます。

env_file

env_file 属性は、環境変数の設定をコンテナーに受け渡すために、それを記述した 1 つまたは複数ファイルを指定します。

env_file: .env

相対パスは Compose ファイルの親フォルダーから相対的に解釈されます。 env_file に絶対パスを用いると Compose ファイルの可搬性を損なうため、そういったパスが用いられている場合には Compose が警告出力を行います。

environment セクションに記述されている環境変数は、この値を上書きします。 これは値が空や未定義であっても同様です。

env_file はリスト指定することもできます。 リスト内のファイルはトップダウンにより処理されます。 同一の環境変数設定が複数ファイル内に存在していた場合、最終のファイルに示されている値が有効になります。

env_file:
  - ./a.env
  - ./b.env

リスト要素はマッピングとして宣言することもできます。 そうすれば追加の属性を設定することもできます。

required

必要条件: Docker Compose 2.24.0 およびそれ以降

required 属性のデフォルトは true です。 requiredfalse に設定されていて .env ファイルが見つからない場合、Compose は何も出力せず無視するだけです。

env_file:
  - path: ./default.env
    required: true # default
  - path: ./override.env
    required: false

format

必要条件: Docker Compose 2.30.0 およびそれ以降

format 属性は env_file のファイル書式を別形式とする指定です。 これが未指定の場合 env_fileenv_file フォーマット に示されている Compose ルールに従って解釈されます。

raw フォーマットは env_file においてキーバリュー形式の項目指定ができるようになります。 ただし Compose はその値に対しての補間はいっさい行いません。 つまり値は記述されたまま取り扱われ、クォートや $ 記号もそのままです。

env_file:
  - path: ./default.env
    format: raw

env_file フォーマット

.env ファイル内の各行は VAR[=[VAL]] の形式になっていなければなりません。 そして以下のルールが適用されます。

  • # で始まる行はコメントとして扱われ無視されます。
  • 空行は無視されます。
  • クォートで囲まれていないまたはダブルクォート (") で囲まれている値は 補間 処理が適用されます。
  • 各行はキーバリューペアを表現しています。 値をクォーテーションで囲むこともできます。
    • VAR=VAL -> VAL
    • VAR="VAL" -> VAL
    • VAR='VAL' -> VAL
  • クォートで囲まれていない値に対してインラインコメントをつける場合は、コメント記号の前に空白を設ける必要があります。
    • VAR=VAL # コメント -> VAL
    • VAR=VAL# コメントにあらず -> VAL# コメントにあらず
  • クォートで囲まれた値に対してのインラインコメントは、閉じクォートの後につける必要があります。
    • VAR="VAL # コメントにあらず" -> VAL # コメントにあらず
    • VAR="VAL" # コメント -> VAL
  • シングルクォーテーションで囲んだ場合、値はそのまま評価されます。
    • VAR='$OTHER' -> $OTHER
    • VAR='${OTHER}' -> ${OTHER}
  • クォーテーション記号は \ を使ってエスケープすることができます。
    • VAR='Let\'s go!' -> Let's go!
    • VAR="{\"hello\": \"json\"}" -> {"hello": "json"}
  • \n\r\t\\ といった一般的なシェルエスケープシーケンスは、ダブルクォートで囲まれた値においてサポートされます。
    • VAR="some\tvalue" -> some value
    • VAR='some\tvalue' -> some\tvalue
    • VAR=some\tvalue -> some\tvalue

VAL は省略可です。 この場合、変数値は空文字になります。 =VAL も省略可です。 この場合、変数値が未設定になります。

# Rails/Rack 環境の設定
RACK_ENV=development
VAR="quoted"

environment

environment 属性は、コンテナー内に設定する環境変数を定義します。 environment は配列かマップ形式で指定できます。 ブーリアン値 true、false、yes、no はダブルクォートで囲む必要があります。 これは YAML パーサーによって True や False に変換されないようにするためです。

環境変数はキーだけ (等号文字による値がない) 単独で宣言することができます。 その場合 Compose はその値の設定をユーザーに委ねます。 その値が解決できなかった場合、その変数は未設定となり、サービスコンテナーの環境内からは削除されます。

マップ形式の文法

environment:
  RACK_ENV: development
  SHOW: "true"
  USER_INPUT:

配列形式の文法

environment:
  - RACK_ENV=development
  - SHOW=true
  - USER_INPUT

1 つのサービスに対して env_fileenvironment の両方が設定された場合、environment に設定された値が優先されます。

expose

expose は (入力) ポート、または Compose がコンテナーから公開するポート範囲を定義するものです。 このポートはリンクされたサービスからアクセス可能でなければならず、またホストマシンに向けては公開されていないものとします。 内部コンテナーのポートのみが指定できます。

その文法は <ポート>/[<プロトコル>] とするか、ポート範囲であれば <開始ポート-終了ポート>/[<プロトコル>] とします。 プロトコルが明示的に指定されなかった場合は tcp が用いられます。

expose:
  - "3000"
  - "8000"
  - "8080-8085/tcp"
メモ

イメージに対する Dockerfile においてポートが既に公開されている場合は、Compose ファイルでの expose が設定されていなくても、そのポートはネットワーク上の他のコンテナーが参照できます。

extends

extends lets you share common configurations among different files, or even different projects entirely. extends を使うことで、共通するサービスオプションを一箇所に定義しておいて、それをどこからでも参照することができます。 別の Compose ファイルを参照しアプリケーション内で利用したいサービスを選び出します。 必要に応じて属性を上書きする機能を利用します。

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.

extends:
  file: common.yml
  service: webapp
  • service: Defines the name of the service being referenced as a base, for example web or database.
  • file: The location of a Compose configuration file defining that service.

制約

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:

  • Not present. This indicates that another service within the same Compose file is being referenced.
  • File path, which can be either:
    • Relative path. This path is considered as relative to the location of the main Compose file.
    • Absolute path.

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

  • The service denoted by service is not found.
  • The Compose file denoted by file is not found.

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: Keys in mappings of the main service definition override keys in mappings of the referenced service definition. Keys that aren't overridden are included as is.
  • Sequences: Items are combined together into a new sequence. The order of elements is preserved with the referenced items coming first and main items after.
  • Scalars: Keys in the main service definition take precedence over keys in the referenced one.
マッピング

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 specify disable: true unless the referenced mapping also specifies disable: true. Compose returns an error in this case. For example, the following input:

services:
  common:
    image: busybox
    environment:
      TZ: utc
      PORT: 80
  cli:
    extends:
      service: common
    environment:
      PORT: 8080

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

environment:
  PORT: 8080
  TZ: utc
image: busybox

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

For example, the following input:

services:
  common:
    image: busybox
    volumes:
      - common-volume:/var/lib/backup/data:rw
  cli:
    extends:
      service: common
    volumes:
      - cli-volume:/var/lib/backup/data:ro

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.

image: busybox
volumes:
- cli-volume:/var/lib/backup/data:ro

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:

services:
  base:
    image: busybox
    user: root
  common:
    image: busybox
    extends:
      service: base
  cli:
    extends:
      service: common

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

image: busybox
user: root
シーケンス

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:

services:
  common:
    image: busybox
    security_opt:
      - label=role:ROLE
  cli:
    extends:
      service: common
    security_opt:
      - label=user:USER

Produces the following configuration for the cli service.

image: busybox
security_opt:
- label=role:ROLE
- label=user:USER

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.

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

extra_hosts

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

短い文法

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

extra_hosts:
  - "somehost=162.242.195.82"
  - "otherhost=50.31.209.229"
  - "myhostv6=::1"

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

extra_hosts:
  - "myhostv6=[::1]"

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

extra_hosts:
  - "somehost:162.242.195.82"
  - "myhostv6:::1"

長い文法

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

extra_hosts:
  somehost: "162.242.195.82"
  otherhost: "50.31.209.229"
  myhostv6: "::1"

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:

162.242.195.82  somehost
50.31.209.229   otherhost
::1             myhostv6

gpus

必要条件: Docker Compose 2.30.0 およびそれ以降

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

services:
  model:
    gpus:
      - driver: 3dfx
        count: 2

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

services:
  model:
    gpus: all

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 in group_add.

services:
  myservice:
    image: alpine
    group_add:
      - mail

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 the Dockerfile reference.

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

interval, timeout, start_period, and start_interval are specified as durations. Introduced in Docker Compose version 2.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.

# Hit the local web app
test: ["CMD", "curl", "-f", "http://localhost"]

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:

test: ["CMD-SHELL", "curl -f http://localhost || exit 1"]
test: curl -f https://localhost || exit 1

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:

healthcheck:
  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 Specification addressable image format, as [<registry>/][<project>/]<image>[:<tag>|@<digest>].

    image: redis
    image: redis:5
    image: redis@sha256:0ed5d5928d4737458944eb604cc8509e245c3e19d02ad83935398bc4b991aac7
    image: library/redis
    image: docker.io/library/redis
    image: my_private.registry:5000/redis

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.

services:
  web:
    image: alpine:latest
    init: true

The init binary that is used is platform specific.

ipc

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

  • shareable: Gives the container its own private IPC namespace, with a possibility to share it with other containers.
  • service:{name}: Makes the container join another container's (shareable) IPC namespace.
    ipc: "shareable"
    ipc: "service:[service name]"

isolation

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

labels

labels はコンテナーにメタデータを追加します。 配列またはマップ形式のデータを指定できます。

推奨されるのは逆引き DNS 記法を用いることであり、他のソフトウェアが利用するラベルとの衝突を避けることができます。

labels:
  com.example.description: "Accounting webapp"
  com.example.department: "Finance"
  com.example.label-with-empty-value: ""
labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"
  - "com.example.label-with-empty-value"

Compose creates containers with canonical labels:

  • com.docker.compose.project set on all resources created by Compose to the user project name
  • com.docker.compose.service set on service containers with service name as defined in the Compose file

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

label_file

必要条件: Docker Compose 2.32.2 およびそれ以降

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.

services:
  one:
    label_file: ./app.labels

  two:
    label_file:
      - ./app.labels
      - ./additional.labels

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.

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.

logging

logging defines the logging configuration for the service.

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

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.

  • 0: Turns off anonymous page swapping.
  • 100: Sets all anonymous pages as swappable.

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.

  • If memswap_limit is set to a positive integer, then both memory and memswap_limit must be set. memswap_limit represents the total amount of memory and swap that can be used, and memory controls the amount used by non-swap memory. So if memory="300m" and memswap_limit="1g", the container can use 300m of memory and 700m (1g - 300m) swap.
  • If memswap_limit is set to 0, the setting is ignored, and the value is treated as unset.
  • If memswap_limit is set to the same value as memory, and memory is set to a positive integer, the container does not have access to swap.
  • If memswap_limit is unset, and memory is set, the container can use as much swap as the memory setting, if the host container has swap memory configured. For instance, if memory="300m" and memswap_limit is not set, the container can use 600m in total of memory and swap.
  • If memswap_limit is explicitly set to -1, the container is allowed to use unlimited swap, up to the amount available on the host system.

models

必要条件: Docker Compose 2.38.0 およびそれ以降

models defines which AI models the service should use at runtime. Each referenced model must be defined under the models top-level element.

services:
  short_syntax:
    image: app
    models:
      - my_model
  long_syntax:
    image: app
    models:
      my_model:
        endpoint_var: MODEL_URL
        model_var: MODEL

When a service is linked to a model, Docker Compose injects environment variables to pass connection details and model identifiers to the container. This allows the application to locate and communicate with the model dynamically at runtime, without hard-coding values.

長い文法

The long syntax gives you more control over the environment variable names.

  • endpoint_var sets the name of the environment variable that holds the model runner’s URL.
  • model_var sets the name of the environment variable that holds the model identifier.

If either is omitted, Compose automatically generates the environment variable names based on the model key using the following rules:

  • Convert the model key to uppercase
  • Replace any '-' characters with '_'
  • Append _URL for the endpoint variable

network_mode

network_mode sets a service container's network mode.

  • none: Turns off all container networking.
  • host: Gives the container raw access to the host's network interface.
  • service:{name}: Gives the container access to the specified container by referring to its service name.
  • container:{name}: Gives the container access to the specified container by referring to its container ID.

For more information container networks, see the Docker Engine documentation.

    network_mode: "host"
    network_mode: "none"
    network_mode: "service:[service name]"

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 the networks 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.

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

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:

services:
  some-service:
    image: foo

This example is actually equivalent to:

services:
  some-service:
    image: foo
    networks:
      default: {}

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.

services:
  some-service:
    networks:
      some-network:
        aliases:
          - alias1
          - alias3
      other-network:
        aliases:
          - alias2

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 monitoring is able to reach same backend service at backend or mysql on the admin network.

services:
  frontend:
    image: example/webapp
    networks:
      - front-tier
      - back-tier

  monitoring:
    image: example/monitoring
    networks:
      - admin

  backend:
    image: example/backend
    networks:
      back-tier:
        aliases:
          - database
      admin:
        aliases:
          - mysql

networks:
  front-tier: {}
  back-tier: {}
  admin: {}

interface_name

必要条件: Docker Compose 2.36.0 およびそれ以降

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.

services:
  backend:
    image: alpine
    command: ip link show
    networks:
      back-tier:
        interface_name: eth0

Running the example Compose application shows:

backend-1  | 11: eth0@if64: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP

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 an ipam attribute with subnet configurations covering each static address.

services:
  frontend:
    image: example/webapp
    networks:
      front-tier:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10

networks:
  front-tier:
    ipam:
      driver: default
      config:
        - subnet: "172.16.238.0/24"
        - subnet: "2001:3984:3989::/64"

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:

services:
  app:
    image: busybox
    command: top
    networks:
      app_net:
        link_local_ips:
          - 57.123.22.11
          - 57.123.22.13
networks:
  app_net:
    driver: bridge

mac_address

必要条件: Docker Compose 2.23.2 およびそれ以降

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

driver_opts

driver_opts specifies a list of options as key-value pairs to pass to the driver. These options are driver-dependent. Consult the driver's documentation for more information.

services:
  app:
    networks:
      app_net:
        driver_opts:
          foo: "bar"
          baz: 1

gw_priority

必要条件: Docker Compose 2.33.1 およびそれ以降

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.

services:
  app:
    image: busybox
    command: top
    networks:
      app_net_1:
      app_net_2:
        gw_priority: 1
      app_net_3:
networks:
  app_net_1:
  app_net_2:
  app_net_3:

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 attribute networks.mac_address.

priority does not affect which network is selected as the default gateway. Use the gw_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.

services:
  app:
    image: busybox
    command: top
    networks:
      app_net_1:
        priority: 1000
      app_net_2:

      app_net_3:
        priority: 100
networks:
  app_net_1:
  app_net_2:
  app_net_3:

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.

pids_limit: 10

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.

platform: darwin
platform: windows/amd64
platform: linux/arm64/v8

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.

短い文法

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:

  • HOST is [IP:](port | range) (optional). If it is not set, it binds to all network interfaces (0.0.0.0).
  • CONTAINER is port | range.
  • PROTOCOL restricts ports to a specified protocol either tcp or udp(optional). Default is tcp.

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:

ports:
  - "3000"
  - "3000-3005"
  - "8000:8000"
  - "9090-9091:8080-8081"
  - "49100:22"
  - "8000-9000:80"
  - "127.0.0.1:8001:8001"
  - "127.0.0.1:5000-5010:5000-5010"
  - "::1:6000:6000"
  - "[::1]:6001:6001"
  - "6060:6060/udp"
メモ

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

長い文法

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

  • target: The container port.
  • published: The publicly exposed port. It is defined as a string and can be set as a range using syntax start-end. It means the actual port is assigned a remaining available port, within the set range.
  • host_ip: The host IP mapping. If it is not set, it binds to all network interfaces (0.0.0.0).
  • protocol: The port protocol (tcp or udp). Defaults to tcp.
  • app_protocol: The application protocol (TCP/IP level 4 / OSI level 7) this port is used for. This is optional and can be used as a hint for Compose to offer richer behavior for protocols that it understands. Introduced in Docker Compose version 2.26.0.
  • mode: Specifies how the port is published in a Swarm setup. If set to host, it publishes the port on every node in Swarm. If set to ingress, it allows load balancing across the nodes in Swarm. Defaults to ingress.
  • name: A human-readable name for the port, used to document its usage within the service.
ports:
  - name: web
    target: 80
    host_ip: 127.0.0.1
    published: "8080"
    protocol: tcp
    app_protocol: http
    mode: host

  - name: web-secured
    target: 443
    host_ip: 127.0.0.1
    published: "8083-9000"
    protocol: tcp
    app_protocol: https
    mode: host

post_start

必要条件: Docker Compose 2.30.0 およびそれ以降

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_stop

必要条件: Docker Compose 2.30.0 およびそれ以降

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_.-]+.

services:
  frontend:
    image: frontend
    profiles: ["frontend"]

  phpmyadmin:
    image: phpmyadmin
    depends_on:
      - db
    profiles:
      - debug

provider

必要条件: Docker Compose 2.36.0 およびそれ以降

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 here.

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

pull_policy

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

  • always: Compose always pulls the image from the registry.
  • never: Compose doesn't pull the image from a registry and relies on the platform cached image. If there is no cached image, a failure is reported.
  • missing: Compose pulls the image only if it's not available in the platform cache. This is the default option if you are not also using the Compose Build Specification. if_not_present is considered an alias for this value for backward compatibility. The latest tag is always pulled even when the missing pull policy is used.
  • build: Compose builds the image. Compose rebuilds the image if it's already present.
  • daily: Compose checks the registry for image updates if the last pull took place more than 24 hours ago.
  • weekly: Compose checks the registry for image updates if the last pull took place more than 7 days ago.
  • every_<duration>: Compose checks the registry for image updates if the last pull took place before <duration>. Duration can be expressed in weeks (w), days (d), hours (h), minutes (m), seconds (s) or a combination of these.
services:
  test:
    image: nginx
    pull_policy: every_12h

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.

  • 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.

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".

web:
  image: busybox:latest
  command: true
  runtime: runc

The default is runc. To use a different runtime, see Alternative 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 the secrets 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.

短い文法

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.

services:
  frontend:
    image: example/webapp
    secrets:
      - server-certificate
secrets:
  server-certificate:
    file: ./server.cert

長い文法

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

  • source: The name of the secret as it exists on the platform.
  • target: The name of the file to be mounted in /run/secrets/ in the service's task container, or absolute path of the file if an alternate location is required. Defaults to source if not specified.
  • uid and gid: The numeric uid or gid that owns the file within /run/secrets/ in the service's task containers.
  • mode: The permissions for the file to be mounted in /run/secrets/ in the service's task containers, in octal notation. The default value is world-readable permissions (mode 0444). The writable bit must be ignored if set. The executable bit may be set.

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.cert within 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.

services:
  frontend:
    image: example/webapp
    secrets:
      - source: server-certificate
        target: server.cert
        uid: "103"
        gid: "103"
        mode: 0o440
secrets:
  server-certificate:
    file: ./server.cert

security_opt

security_opt overrides the default labeling scheme for each container.

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

For further default labeling schemes you can override, see Security 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, see Keep 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 with stop_signal), before sending SIGKILL. It's specified as a duration.

    stop_grace_period: 1s
    stop_grace_period: 1m30s

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.

stop_signal: SIGUSR1

storage_opt

storage_opt defines storage driver options for a service.

storage_opt:
  size: '1G'

sysctls

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

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

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 to configure 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.

tmpfs:
 - <path>
 - <path>:<options>
  • path: The path inside the container where the tmpfs will be mounted.
  • options: Comma-separated list of options for the tmpfs mount.

Available options:

  • mode: Sets the file system permissions.
  • uid: Sets the user ID that owns the mounted tmpfs.
  • gid: Sets the group ID that owns the mounted tmpfs.
services:
  app:
    tmpfs:
      - /data:mode=755,uid=1009,gid=1009
      - /run

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, see Allocate 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.

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

use_api_socket

When use_api_socket is set, the container is able to interact with the underlying container engine through the API socket. Your credentials are mounted inside the container so the container acts as a pure delegate for your commands relating to the container engine. Typically, commands ran by container can pull and push to your registry.

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.

userns_mode: "host"

uts

必要条件: Docker Compose 2.15.1 およびそれ以降

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:

  • 'host': Results in the container using the same UTS namespace as the host.
    uts: "host"

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.

services:
  backend:
    image: example/backend
    volumes:
      - type: volume
        source: db-data
        target: /data
        volume:
          nocopy: true
          subpath: sub
      - type: bind
        source: /var/run/postgres/postgres.sock
        target: /var/run/postgres/postgres.sock

volumes:
  db-data:

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

短い文法

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).

  • VOLUME: Can be either a host path on the platform hosting containers (bind mount) or a volume name.
  • CONTAINER_PATH: The path in the container where the volume is mounted.
  • ACCESS_MODE: A comma-separated , list of options:
    • rw: Read and write access. This is the default if none is specified.
    • ro: Read-only access.
    • z: SELinux option indicating that the bind mount host content is shared among multiple containers.
    • Z: SELinux option indicating that the bind mount host content is private and unshared for other containers.
メモ

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.

長い文法

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

  • type: The mount type. Either volume, bind, tmpfs, image, npipe, or cluster
  • source: The source of the mount, a path on the host for a bind mount, a Docker image reference for an image mount, or the name of a volume defined in the top-level volumes key. Not applicable for a tmpfs mount.
  • target: The path in the container where the volume is mounted.
  • read_only: Flag to set the volume as read-only.
  • bind: Used to configure additional bind options:
    • propagation: The propagation mode used for the bind.
    • create_host_path: Creates a directory at the source path on host if there is nothing present. Defaults to true.
    • selinux: The SELinux re-labeling option z (shared) or Z (private)
  • volume: Configures additional volume options:
    • nocopy: Flag to disable copying of data from a container when a volume is created.
    • subpath: Path inside a volume to mount instead of the volume root.
  • tmpfs: Configures additional tmpfs options:
    • size: The size for the tmpfs mount in bytes (either numeric or as bytes unit).
    • mode: The file mode for the tmpfs mount as Unix permission bits as an octal number. Introduced in Docker Compose version 2.14.0.
  • image: Configures additional image options:
  • consistency: The consistency requirements of the mount. Available values are platform specific.
情報

Working with large repositories or monorepos, or with virtual file systems that are no longer scaling with your codebase? Compose now takes advantage of Synchronized 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.

volumes_from:
  - service_name
  - service_name:ro
  - container:container_name
  - container:container_name:rw

working_dir

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