The RUN instruction

The RUN instruction is the real workhorse during the build, and it can run any command. The general recommendation is to execute the multiple commands using one RUN instruction. This reduces the layers in the resulting Docker image because the Docker system inherently creates a layer for each time an instruction is called in Dockerfile.

The RUN instruction has two types of syntax:

  • The first is the shell type, as shown here:
      RUN <command> 

Here, <command> is the shell command that has to be executed during the build time. If this type of syntax is to be used, then the command is always executed using /bin/sh -c.

  • The second syntax type is either exec or the JSON array, as shown here:
      RUN ["<exec>", "<arg-1>", ..., "<arg-n>"] 

Here, the code terms mean the following:

  • <exec>: This is the executable to run during the build time
  • <arg-1>, ..., <arg-n>: These are the variable numbers (zero or more) of arguments for the executable

Unlike the first type of syntax, this type does not invoke /bin/sh -c. Hence, the types of shell processing, such as the variable substitution ($USER) and the wildcard substitution (*, ?) do not happen in this type. If shell processing is critical for you, then you are encouraged to use the shell type. However, if you still prefer the exec (JSON array type) type, then use your preferred shell as the executable and supply the command as an argument.

Consider the example, RUN ["bash", "-c", "rm", "-rf", "/tmp/abc"].

Now, let's look at a few examples of the RUN instruction. In the first example, we will use the RUN instruction for adding a greeting line to the .bashrc file in the target image filesystem, as shown here:

RUN echo "echo Welcome to Docker!" >> /root/.bashrc 

The second example is a Dockerfile, which has the instructions for crafting an Apache2 application image on top of the Ubuntu 14.04 base image. The following steps will explain the Dockerfile instructions line by line:

  1. We are going to build an image using ubuntu:14.04 as the base image, using the FROM instruction, as shown here:
      ########################################### 
# Dockerfile to build an Apache2 image
###########################################
# Base image is Ubuntu
FROM ubuntu:14.04
  1. Set the author's details using the MAINTAINER instruction, as shown here:
      # Author: Dr. Peter 
MAINTAINER Dr. Peter <[email protected]>
  1. Using one RUN instruction, we will synchronize the apt repository source list, install the apache2 package, and then clean the retrieved files, as shown here:
      # Install apache2 package 
RUN apt-get update &&
apt-get install -y apache2 &&
apt-get clean
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset