Nono.MA

Pass arguments to a Dockerfile

FEBRUARY 1, 2023

Here's how to pass arguments to a Dockerfile when building a custom image with Docker.

First, you need to define a Dockerfile which uses an argument.

# Dockerfile
FROM python

ARG code_dir # Our argument

WORKDIR /code/
ENTRYPOINT ["python", "/code/script.py"]

COPY ./$code_dir /code/
RUN pip install -r requirements.txt

What the above Dockerfile does is parametrize the location of the directory of script.py, our Docker image's entry point. For this example's sake, let's assume our directory structure looks like the following.

project/
  Dockerfile
  code_a/script.py
  code_b/script.py
# code_a/script.py
print('This is code_a!')
# code_b/script.py
print('This is code_b!')

Then you'll pass the code_dir variable as an argument to docker build to decide whether the Dockerfile is going to COPY folder code_a or code_b into our image.

Let's pass code_a as our code_dir first.

docker build -t my_image_a --build-arg code_dir=code_a .
docker run -it my_image_a
# Prints 'This is code_a!'

Then code_b.

docker build -t my_image_b --build-arg code_dir=code_b .
docker run -it my_image_b
# Prints 'This is code_b!'

The objective of this example was to avoid having two different Dockerfiles that look exactly the same but simply specify different source code paths. We could have done the same with the following two Dockerfiles and specifying which Docker file to use in each case with the -f flag.

# Dockerfile.code_a
FROM python

WORKDIR /code/
ENTRYPOINT ["python", "/code/script.py"]

COPY ./code_a /code/
RUN pip install -r requirements.txt
# Dockerfile.code_b
FROM python

WORKDIR /code/
ENTRYPOINT ["python", "/code/script.py"]

COPY ./code_b /code/
RUN pip install -r requirements.txt
docker build -t my_image_a -f Dockerfile.code_a .
docker run -it my_image_a
# Prints 'This is code_a!'
docker build -t my_image_b --f Dockerfile.code_b .
docker run -it my_image_b
# Prints 'This is code_b!'

If you found this useful, let me know!

BlogCodeDockerTil