Reading input files with docker

2019-07-28 07:56发布

问题:

I'm writting a C++ program that is run as follows:

./program data_file config_file

And I want to use docker with it. I've written the following Dockerfile:

FROM gcc:7.2.0
ENV MYP /repo
WORKDIR ${MYP}
COPY . ${MYP}

RUN /bin/sh -c 'make'
ENTRYPOINT ["./program"]
CMD ["file1", "file2"]

So I docker build -t test . it and use docker run test and see that everything goes fine with the defaults.

However, if I modify file1 for instance in my working directory (after build), I note that when I run docker run test file1 file2, the file1 called is the one inside the container, and the one entered as argument is being ignored.

Similarly, If I use renamed data and config files, and run docker run test file3 file4, I get an error saying that these files does not exist (because they are not in the container).

So, how can I do to make docker recognize these input files passed as arguments, avoiding to use the files that are contained in the image?

Docker version is 18.04.0-ce, build 3d479c0af6.

EDIT

Another option is to use a launch.sh script like:

#!/bin/sh
./program "${DATA_FILE}" "${CONFIG_FILE}"

So ENTRYPOINT and CMD instructions are replaced by the following line in the Dockerfile:

CMD ["./launch.sh"]

But now if I run:

docker run test -e DATA_FILE=file1 -e CONFIG_FILE=file2

I get a permission error...

docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"-e\": executable file not found in $PATH": unknown. ERRO[0000] error waiting for container: context canceled

回答1:

You can use volume mechanism for mount a host directory to the container.

Create file1.txt and file2.txt files in some directory in the host machine. For example we are creating files in the /var/dir1/ directory.
Your working dir in the docker container is /program.

So when you are running docker you should mount this host directory to container using -v flag

docker run -v /var/dir1/:/program test file1.txt file2.txt

Oh, I know why we have problem.

When I am mounting the host directory to working dir I am actually deleting all created files inside container from it working dir including the ./program binary file. So the docker run command is failed.
therefore we not must mount working directory. We can mount subdirectory of working directory for example.

 docker run -v /var/dir1/:/program/dir test dir/file1.txt dir/file2.txt 

It works for me!



标签: c++ docker