The RUN instruction

The RUN instruction is the real workhorse of the Dockerfile. It is the tool by which you affect the most change in the resulting docker image. Basically, it allows you to execute any command in the image. There are two forms of the RUN instruction. Here is the syntax:

# RUN instruction syntax
# Shell form to run the command in a shell
# For Linux the default is "/bin/sh -c"
# For Windows the default is "cmd /S /C"
RUN <command>

# Exec form
RUN ["executable", "param1", "param2"]

Every RUN instruction creates a new layer in the image, and the layers for each instruction that follow will be built on the results of the RUN instruction's layer. The shell form of the instruction will use the default shell unless it is overridden using a SHELL instruction, which we will discuss in The SHELL instruction section. If you are building a container that does not include a shell, you will need to use the exec form of the RUN instruction. You can also use the exec form of the instruction to use a different shell. For example, to run a command using the bash shell, you could add a RUN instruction, like so:

# Exec form of RUN instruction using bash
RUN ["/bin/bash", "-c", "echo hello world > /myvol/greeting"]

The uses for the RUN command are limited only by the imagination, so providing an exhaustive list of RUN instruction samples would be impossible, but here are a few using both forms of the instruction, just to give you some ideas:

# RUN instruction Dockerfile for Docker Quick Start
FROM ubuntu
RUN useradd --create-home -m -s /bin/bash dev
RUN mkdir /myvol
RUN echo "hello DQS Guide" > /myvol/greeting
RUN ["chmod", "664", "/myvol/greeting"]
RUN ["chown", "dev:dev", "/myvol/greeting"]
VOLUME /myvol
USER dev
CMD ["/bin/bash"]
There is a fun and useful RUN instruction you can add when you know your image will include bash. This idea was shared with me by my colleague Marcello de Sales after he learned of it at Dockercon 16.
You can use the following code to create a custom prompt displayed when you shell into your containers. If you don't like the whale graphic, you can switch it up and use anything you like better. I've included some of my favorite options. Here's the code:
# RUN instruction Dockerfile for Docker Quick Start
FROM ubuntu
RUN useradd --create-home -m -s /bin/bash dev
# Add a fun prompt for dev user of my-app
# whale: "xF0x9Fx90xB3"
# alien:"xF0x9Fx91xBD"
# fish:"xF0x9Fx90xA0"
# elephant:"xF0x9Fx91xBD"
# moneybag:"xF0x9Fx92xB0"
RUN echo 'PS1="[$(tput bold)$(tput setaf 4)]my-app $(echo -e "xF0x9Fx90xB3") [$(tput sgr0)] [\u@\h]:\W \$ "' >> /home/dev/.bashrc &&
echo 'alias ls="ls --color=auto"' >> /home/dev/.bashrc
USER dev
CMD ["/bin/bash"]

The resulting prompt looks like this:

..................Content has been hidden....................

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