Search code examples
dockerdockerfile

Docker printing out empty string instead of a value set during build


This is my dockerfile:

FROM python:3.11-slim-bullseye

COPY requirements.txt .
RUN python -m pip install --upgrade pip
RUN python -m pip install -r requirements.txt

ARG my_build_arg

CMD echo $my_build_arg

I want to set an argument at the time of building the image. So, I run this command:

docker build --build-arg my_build_arg='my_fantastic_value' -t 'my_image' .

When I run docker run my_image into the console, I am expecting that docker will print out 'my_fantastic_value'. Instead, docker prints a newline with no text. What is wrong here?


Solution

  • ARG instructions do not persist in the image. You can use an ENV instruction instead, which does persist in the image:

    ...
    ARG my_build_arg
    ENV my_build_env=$my_build_arg
    CMD echo $my_build_env
    

    See more here: https://docs.docker.com/engine/reference/builder/#using-arg-variables