What are core Dockerfile instructions (FROM, WORKDIR, COPY, RUN, CMD, ENTRYPOINT)?
❓ Interview Prompt: Explain the purpose and order of FROM, WORKDIR, COPY, RUN, EXPOSE, ENV, CMD, and ENTRYPOINT Dockerfile instructions.
Each Dockerfile instruction creates a new image layer and serves a specific purpose:
1. FROM <image>
Sets the base image. Must be the first instruction. Every layer inherits from this foundation.
2. WORKDIR /app
Sets the current working directory inside the image for all subsequent RUN, COPY, and CMD instructions. Creates the directory if it doesn't exist.
3. COPY <src> <dest>
Copies files from the build context (your local machine) into the image. Prefer COPY over ADD unless you need automatic tarball extraction.
4. RUN <command>
Executes a shell command during the build phase and commits the result as a new layer. Used for installing packages, compiling code.
5. ENV KEY=value
Sets persistent environment variables visible at both build time and runtime.
6. EXPOSE <port>
Documents which port the container listens on (informational only — does NOT publish ports).
7. CMD ["executable", "arg"]
Sets the default command to run when the container starts. Can be overridden via docker run <image> <override>.
8. ENTRYPOINT ["executable"]
Sets the fixed executable that always runs. CMD arguments are appended to ENTRYPOINT.
Code Implementation Example
# Base image — always first
FROM node:20-alpine
# Set working directory (creates /app if missing)
WORKDIR /app
# Set build-time + runtime environment variable
ENV NODE_ENV=production
# Copy dependency manifests first (cache optimization)
COPY package*.json ./
# Install dependencies — creates a layer
RUN npm ci --only=production
# Copy application source code
COPY src/ ./src/
# Document the container's listening port
EXPOSE 3000
# Default startup command (JSON array = exec form, no shell)
CMD ["node", "src/index.js"]Each Dockerfile instruction creates a cached layer — order matters for build caching. Use exec form (JSON arrays) for CMD/ENTRYPOINT to avoid shell signal issues.