0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

docker build --build-arg時の引数は、Dockerfile内でそのまま使用できない

Last updated at Posted at 2025-04-07

概要

Dockerfileを修正している際に、なぜかdocker build --build-argで指定した引数が、Dockerfileで使用できませんでした。
自分が陥ったdocker build --build-argの罠の解決策を共有しようと思います。

結論

docker build --build-arg hoge=fuga

でビルドしたときに、hoge(引数)をDockerfile内で使用するときは、Dockerfileで

ARG hoge=piyo

と宣言しないと、hoge(引数)は使用できません。

解説

結論でお伝えした通り、docker buildで設定した引数は、Dockerfile内でARGを宣言しないといけません。

ARGについて少し解説を加えます。

ARG 変数名=初期値

上記のように宣言するARGですが、引数に変数の値が存在しない場合は、初期値の値が使用されます。

またDockerfile内で、最初にFROMを用いて、新たに作成するDockerイメージのベースとなるイメージを指定すると思います。
この際に同一のDockerfile内で、FROMが複数ある場合は、それぞれのFROMのスコープにおいて、ARGを定義する必要があることに注意が必要です。以下が例になります。

FROM image1
ARG hoge=fuga

FROM image2
ARG hoge=piyo

# ARGの初期値は、同じ値でも問題ないです。

最後に

いちいちARGで宣言するのは忘れてしまいそうですが、引数を使用してエラーが起こった際は、まずはARGが宣言されているか確認するのが良いでしょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?