9

I've seen many dockerfiles include all build steps in a RUN statement, like:

RUN echo "Hello" &&
    cd /tmp &&
    mv a.txt b.txt &&
    ...
    and so on...

My question is: what's the benefits/drawbacks on replace these instructions by a single bash script that gives me highlight syntax, loop capabilities, etc? Something like:

COPY ./script.sh /tmp
RUN  bash /tmp/script.sh

and then

#!/bin/bash

echo "hello" ;
cd /tmp ;
mv a.txt b.txt ;
...    

Thanks!

2 Answers 2

6

The primary difference is that when you COPY the bash script into the image it will be available for inspection in the running container, whereas the RUN command is a little more opaque. Putting your commands in a file like that is arguably more manageable for other reasons: changes in your VCS history will be a little more clear, and for longer or more complex scripts you will probably find it easier to format things cleanly with the script in a separate file rather than embedded in your Dockerfile in a RUN command.

Otherwise the result is the same (in both cases, you are executing the same set of commands), although the COPY and RUN will result in an extra image layer (vs. just the RUN by itself).

Sign up to request clarification or add additional context in comments.

3 Comments

Removing the script file after its execution may be a good practice, then... isn't it?
I don't have a strong opinion on that question. I would typically leave the script in place, but arguably it's already available in your sources, so...you know, whatever feels right :)
One last difference, docker history will not show the commands run inside of a shell script, only that you ran the script.
0

I guess running it off as a shell script gives you more control.

For instance, you can do if-else statements to check whether a command has failed or not and provide a code path to handle it. Whereas RUN is more straight forward and when the return code is not 0 it fails the build immediately.

Obviously the case you have there is a relatively simple one and it would not have had a huge difference. The only impact I can see here is the code readability aspect. Someone would have to read the shell script to know what is happening, comparing to having everything on a single file.

I guess it all comes down to using the right tool for the right job. If it is a simple command and you don't need complex logic handling then do RUN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.