Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to file in Dockerfile

I have a shell script, script.sh, that writes some lines to a file:

#!/usr/bin/env bash
printf "blah 
blah 
blah 
blah\n" | sudo tee file.txt

Now in my Dockerfile, I add this script and run it, then attempt to add the generated file.txt:

ADD script.sh .
RUN chmod 755 script.sh && ./script.sh 
ADD file.txt . 

When I do the above, I just get an error referring to the ADD file.txt . command:

lstat file.txt: no such file or directory

Why can't docker locate the file that my shell script generates? Where would I be able to find it?

like image 326
pcsram Avatar asked Jun 22 '16 18:06

pcsram


People also ask

Is a Dockerfile just a text file?

Docker can build images automatically by reading the instructions from a Dockerfile . A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

Does Dockerfile need Workdir?

According to the documentation: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn't exist, it will be created even if it's not used in any subsequent Dockerfile instruction.


2 Answers

When you RUN chmod 755 script.sh && ./script.sh it actually execute this script inside the docker container (ie: in the docker layer).

When you ADD file.txt . you are trying to add a file from your local filesystem inside the docker container (ie: in a new docker layer).

You can't do that because the file.txt doesn't exist on your computer.

In fact, you already have this file inside docker, try docker run --rm -ti mydockerimage cat file.txt and you should see it's content displayed

like image 187
michael_bitard Avatar answered Sep 19 '22 20:09

michael_bitard


It's because Docker load the entire context of the directory (where your Dockerfile is located) to Docker daemon at the beginning. From Docker docs,

The build is run by the Docker daemon, not by the CLI. The first thing a build process does is send the entire context (recursively) to the daemon. In most cases, it’s best to start with an empty directory as context and keep your Dockerfile in that directory. Add only the files needed for building the Dockerfile.

Since your text file was not available at the beginning, you get that error message. If you still want that text file want to be added to Docker image, you can call `docker build' command from the same script file. Modify script.sh,

#!/usr/bin/env bash
printf "blah 
blah 
blah 
blah\n" | sudo tee <docker-file-directory>/file.txt
docker build --tag yourtag <docker-file-directory>

And modify your Dockerfile just to add the generated text file.

ADD file.txt
.. <rest of the Dockerfile instructions>
like image 36
techtabu Avatar answered Sep 19 '22 20:09

techtabu