Lesson 9: Essential Dockerfile Instructions: FROM, RUN, CMD, ENTRYPOINT
Mastering these core instructions is key to building effective Docker images.
1. FROM (Base Image)
This must be the first instruction. It specifies the base image your image will be built upon.
dockerfile FROM node:20-slim
Rule: Always choose the smallest, most secure base image necessary for your application (e.g., alpine or slim variants).
2. RUN (Executing Commands)
RUN executes any commands in a new layer on top of the current image, and commits the result.
Usage: Installing packages, downloading files, compiling code.
dockerfile
Example of installing dependencies
RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/*
Best Practice: Chain multiple commands in a single RUN instruction using && and clean up (like removing cache) to minimize the number of layers and reduce image size.
3. CMD (Default Command)
CMD provides defaults for executing an application inside the container.
- There can only be one
CMDinstruction in a Dockerfile. - If the user specifies a command when running the container (
docker run <image> <command>), theCMDinstruction is ignored.
dockerfile
Executable form (recommended)
CMD ["npm", "start"]
4. ENTRYPOINT (Defining the Executable)
ENTRYPOINT configures a container to run as an executable. The arguments passed in the CMD instruction (or on the command line) are appended to the ENTRYPOINT.
Example:
dockerfile ENTRYPOINT ["/usr/bin/curl"] CMD ["--help"]
If the user runs docker run my-image www.google.com:
- The executed command is:
/usr/bin/curl www.google.com(overriding the defaultCMD ["--help"]).
Summary: Use ENTRYPOINT for the primary executable (e.g., java, node, nginx) and CMD for the default parameters to that executable.