Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing file as argument to Docker container

Tags:

python

docker

A very simple python program, suppose current directory is /PYTHON, I want to pass file.txt as argument to python script boot.py, here is my Dockerfile

FROM python COPY boot.py ./ COPY file.txt ./ RUN pip install numpy CMD ["python", "boot.py", "file.txt"] 

then I build the Docker container with :

docker build -t boot/latest .

then run the container

docker run -t boot:latest python boot.py file.txt

I got the correct results.

But If I copy another file file1.txt to the current directory (from a different directory (not /PYTHON)), then I run the container again:

docker run -t boot:latest python boot.py file1.txt

I got the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'

so the error is due to fact that file1.txt is not in the container, but if I share this container with a friend and the friend wants to pass a very different file as argument, how do I write the Dockerfile so anybody with my container can pass very different files as argument without errors ? Thanks in advance. (I am new to Docker)

like image 722
mpp Avatar asked Dec 12 '16 00:12

mpp


People also ask

How do I pass args to Dockerfile build?

If you want to pass multiple build arguments with docker build command you have to pass each argument with separate — build-arg. docker build -t <image-name>:<tag> --build-arg <key1>=<value1> --build-arg <key2>=<value2> .

Can Dockerfile take argument?

You can use the ARG command inside a Dockerfile to define the name of a parameter and its default value. This default value can also be overridden using a simple option with the Docker build command.


1 Answers

It won't work that way. Like you said, file1.txt is not in the container.

The work around is to use Docker volumes to inject files from your host machine to the container when running it.

Something like this :

docker run -v /local/path/to/file1.txt:/container/path/to/file1.txt -t boot:latest python boot.py /container/path/to/file1.txt 

Then /local/path/to/file1.txt would be the path on your host machine which will override /container/path/to/file1.txt on the container.

like image 122
HakRo Avatar answered Sep 27 '22 00:09

HakRo