Common DockerFile directives:
Estimated reading: 5 minutes 30 views

🐳 DockerFile RUN Instruction – Complete Guide with Best Practices & Examples

🧲 Introduction – Why Learn the RUN Instruction in Docker?

The RUN command is one of the most fundamental and powerful tools in any Dockerfile. It allows you to execute shell commands during the build process of your Docker image. From installing dependencies to setting permissions or compiling source codeβ€”RUN is how you customize and configure your image before it runs.

🎯 In this guide, you’ll learn:

  • What the RUN command does and how it works
  • The syntax differences (Shell vs Exec)
  • Optimization strategies to reduce image size
  • Common mistakes and real-world usage examples

🧠 What is the RUN Command in a DockerFile?

The RUN instruction executes commands at build time, creating a new layer on top of the current image. This layer is then committed and added to the final image. It’s ideal for installing software, downloading files, modifying system configuration, and more.

πŸ”Ή Syntax:

RUN <command>

🐚 Shell Form

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

βœ… Uses /bin/sh -c by default. Supports:

  • Shell features (&&, ||, >, variable expansion)

βš™οΈ Exec Form (JSON Array Format)

RUN ["apt-get", "install", "-y", "nginx"]

βœ… Does not use a shell. Executes commands directly. Useful for:

  • Precise command execution
  • Avoiding shell parsing issues

πŸ” How RUN Works in a DockerFile

  • βœ… Creates a new image layer after each execution
  • ⚠️ Executed only during the image build phase, not when the container starts
  • πŸ“¦ Impacts final image sizeβ€”unoptimized usage can result in bloat

πŸ“Œ Pro Tip: Use && to combine related commands in a single RUN to minimize the number of layers.


πŸ“¦ Real-World Example – Installing Dependencies

FROM ubuntu:20.04

RUN apt-get update && \
    apt-get install -y curl git vim && \
    rm -rf /var/lib/apt/lists/*

βœ… This example:

  • Installs multiple packages
  • Combines commands using && to reduce layers
  • Cleans up cache to reduce image size

🧰 DockerFile RUN Command – Function Table

πŸ› οΈ FunctionπŸ“ DescriptionπŸ“Œ Example
Install packagesUse OS package managersRUN apt-get install -y curl
Clean up filesReduce image bloatRUN apt-get clean && rm -rf /var/lib/apt/lists/*
Create/modify filesAdd or edit files/directoriesRUN mkdir /data && touch /data/info.txt
Edit configsCustomize settingsRUN echo "alias ll='ls -la'" >> ~/.bashrc
Execute scriptsRun custom shell scriptsRUN ./install.sh
Change permissionsAdjust file access rightsRUN chmod +x /app/start.sh
Download filesPull from internetRUN curl -O https://example.com/file.tar.gz
Extract archivesUnpack zipped contentRUN tar -xzf file.tar.gz -C /opt
Compile codeBuild from sourceRUN gcc -o app main.c
Chain commandsReduce layersRUN apt update && apt install -y vim
Use ENV variablesInject environment configsRUN echo "ENV=$APP_ENV"
Add security certsEnhance trustRUN update-ca-certificates
Run tests/buildsVerify during buildRUN npm install && npm test
Install runtimesAdd interpretersRUN apt install -y nodejs
Create users/groupsAdd OS usersRUN useradd -ms /bin/bash devuser

βœ… Best Practices for RUN in Dockerfile

πŸ”§ Combine Commands Wisely

RUN apt-get update && apt-get install -y \
    python3 python3-pip && \
    rm -rf /var/lib/apt/lists/*

πŸ”„ Chaining commands reduces image layers and speeds up builds.

🧹 Always Clean Up
Remove temporary files or cached data to reduce image size:

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

πŸ›‘οΈ Use Exec Form for Precision

RUN ["bash", "-c", "echo Hello && echo World"]

Exec form avoids shell-related parsing issues.


❌ Common Mistakes to Avoid

❗ Mistake🧹 Better Approach
Multiple RUN commandsCombine with && to reduce layers
Forgetting cleanupAlways clean apt/yum cache to reduce size
Relying only on Shell formUse Exec form when precision is needed

πŸ“˜ Real-World Dockerfile Snippet

FROM node:18

WORKDIR /app

COPY . .

RUN npm install && npm run build

CMD ["node", "server.js"]

πŸ” RUN npm install && npm run build installs dependencies and builds the app during the build stage, ensuring your app is ready when the container starts.


πŸ“ Summary – Recap & Takeaways

The RUN instruction is your tool for customizing Docker images during the build process. From installing software to configuring settings, it’s essential to use it wisely to keep your image optimized.

πŸ” Key Takeaways:

  • Executes at build time, not runtime
  • Creates new layers, which can bloat the image if misused
  • Supports both Shell and Exec syntax forms
  • Combine commands and clean up to keep your image lean
  • Use ENV, scripts, and chaining for full control

βš™οΈ Real-World Impact:
Efficient use of RUN reduces Docker image sizes, speeds up deployments, and ensures consistency across environments.


❓FAQs – DockerFile RUN Command

❓ Q1. Does RUN execute when the container starts?
❌ No. RUN executes only during image build. Use CMD or ENTRYPOINT for runtime actions.


❓ Q2. Can I use environment variables in RUN?
βœ… Yes, declare with ENV:

ENV PORT=3000
RUN echo "Server runs on port $PORT"

❓ Q3. Can I execute a shell script using RUN?
βœ… Absolutely. Just COPY the script first:

COPY setup.sh .
RUN chmod +x setup.sh && ./setup.sh

❓ Q4. What’s the difference between RUN and CMD?

InstructionWhen It RunsPurpose
RUNDuring image buildSetup image
CMDAt container startupDefault container behavior

❓ Q5. How do I reduce layers created by RUN?
βœ… Combine commands:

RUN apt-get update && apt-get install -y nginx && rm -rf /var/lib/apt/lists/*

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

DockerFile RUN

Or Copy Link

CONTENTS
Scroll to Top