Writing data to a 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 Docker file, I add this script and run it, then try to add the generated file.txt :

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

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

lstat file.txt: no such file or directory

Why can't I find the file that my shell script generates? Where can I find him?

+5
source share
2 answers

When you run RUN chmod 755 script.sh && ./script.sh , actually execute this script inside the docker container ( RUN chmod 755 script.sh && ./script.sh .: at the docker level).

When you ADD file.txt . trying to add a file to the local file system inside the docker container (i.e.: in a new docker layer).

You cannot do this because the .txt file does not exist on your computer.

In fact, you already have this file inside the docker, try docker run --rm -ti mydockerimage cat file.txt and you will see its contents displayed

+4
source

This is because Docker loads the entire directory context (where your Docker file is located) to the Docker daemon at the beginning. From Docker Docs

The build is done by the Docker daemon, not the CLI. The first thing the build process does is send the entire context (recursively) to the daemon. In most cases, it is best to start with an empty directory as context and store the Docker file in this directory. Add only the files needed to create the Docker file.

Since your text file was not available at the beginning, you will receive this error message. If you still want the text file to be added to the Docker image, you can invoke the 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 Docker file just to add the generated text file.

 ADD file.txt .. <rest of the Dockerfile instructions> 
+1
source

All Articles