Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 101 of 8022. Docker Image LifecycleFree lesson

Executing Commands with RUN and Shell Form

Learners will execute package installations and system configurations using the RUN instruction while understanding the impact of shell versus exec forms.

In this lesson, you will learn how to use the RUN instruction to install software and configure your system during the Docker image build process, focusing on the differences between Shell and Exec forms.

What is the RUN Instruction?

When you build an image, you often need to install packages (like curl or git) or set up configuration files. The RUN instruction is your primary tool for this; it executes commands during the image build process and commits the results as a new layer.

Shell Form vs. Exec Form

There are two ways to write RUN commands. Choosing the right one changes how your command is processed.

1. Shell Form In the shell form, you simply provide the command as a string:

RUN apt-get update && apt-get install -y python3

This runs inside a shell (/bin/sh -c). Because it uses a shell, you can use shell features like environment variables, pipes (|), and redirects (>). This is the most common and readable way to execute simple tasks.

2. Exec Form The exec form uses a JSON-array syntax:

RUN ["apt-get", "update"]

This form executes the command directly without invoking a shell. Because there is no shell involved, you cannot use shell features like environment variables or pipes. The benefit? It avoids potential issues with shell string parsing and is cleaner for specific low-level system calls, but it is generally less flexible for day-to-day configuration.

Why It Matters

When you use the shell form, Docker spawns a shell process to interpret your command. This is why you can chain commands together with &&. If you use the exec form, you would need to manually call the shell if you wanted to perform a complex command: RUN ["/bin/bash", "-c", "apt-get update && apt-get install -y python3"].

Most beginners find the shell form much easier to manage for package installations, while the exec form is reserved for scenarios where you want to avoid side effects from the shell environment.

Key Takeaway: Use the Shell form for readability and command chaining, and use the Exec form when you need precise control over how the command is executed without shell interference.