Dockerのイメージビルド時に環境変数が未定義の場合にエラーを出したい

まとめ

Dockerfile側ではエラーを出すようなENVの定義方法がなさそうで、docker image buildを叩いている場合は厳しそうに見える。

ワークアラウンドではあるものの、イメージビルドにdocker-composeを利用している場合、envプロパティを変数展開する際にエラーにできる。

docker-compose.yml の定義方法

services:
    some-service:
        image: xxxxx
        environment:
          - FOO=${FOO:?}    

とする。

variable substitutionの箇所に記載がある。 Compose file version 3 reference | Docker Documentation

Similarly, the following syntax allows you to specify mandatory variables:

${VARIABLE:?err} exits with an error message containing err if VARIABLE is unset or empty in the environment. ${VARIABLE?err} exits with an error message containing err if VARIABLE is unset in the environment.

Dockerfileではできないの

以下はFOOが未定義でもビルドが通ってしまう。

FROM xxxxx

ENV FOO=${FOO:?}

参考

kdnakt.hatenablog.com