RUN instruction - Dockerfile

The RUN instruction will execute the Linux command on a new layer. It is used to alter the image like adding new packages using apt-get or changing file permissions etc.

RUN has 2 forms:

  • RUN (the command is run in a shell, which by default is /bin/sh -c on Linux or cmd /S /C on Windows)
  • RUN ["executable", "param1", "param2"] (exec form)
RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME'

In the shell form, you can use a \ (backslash) to continue a single RUN instruction onto the next line. For example, consider these two lines:

RUN /bin/bash -c 'source $HOME/.bashrc; \
echo $HOME'

To use a different shell, other than ‘/bin/sh’, use the exec form passing in the desired shell. For example:

RUN ["/bin/bash", "-c", "echo hello"]

Concept of Caching

Docker layer caching (DLC) is a great feature to use if building Docker images. It is a regular part of your CI/CD process. DLC will save image layers created within your jobs, rather than impact the actual container used to run your job. Docker uses a layer cache to optimize and speed up the process of building Docker images.

The cache for an instruction like RUN apt-get dist-upgrade -y will be reused during the next build. The cache for RUN instructions can be invalidated by using the--no-cache flag, for example docker build --no-cache.

Did you find this article valuable?

Support Things for DevOps by becoming a sponsor. Any amount is appreciated!