Code Reference

Dockerfile

Docker · Reference cheat sheet

Dockerfile

Docker · Reference cheat sheet


📋 Overview

A Dockerfile is a sequence of instructions that build an image layer by layer. Order matters for cache efficiency.

🔧 Core concepts

InstructionRole
FROMBase image
WORKDIRSet working directory
COPY / ADDAdd files (COPY preferred)
RUNExecute build commands
ENV / ARGRuntime env / build args
EXPOSEDocument port (does not publish)
USERSwitch user
CMD / ENTRYPOINTDefault process
Cache tipPractice
Copy lockfiles firstReuse npm ci / pip layers
Fewer layersCombine related RUNs when it helps
.dockerignoreExclude node_modules, .git, secrets

💡 Examples

Node app sketch:

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 9000
CMD ["node", "server.js"]

Build args:

ARG NODE_ENV=production
ENV NODE_ENV=$NODE_ENV

.dockerignore:

node_modules
.git
.env
Dockerfile*

⚠️ Pitfalls

  • ADD auto-extracts archives and can fetch URLs — surprising; prefer COPY.
  • Secrets in RUN lines leak into image history — use BuildKit secret mounts.
  • CMD vs ENTRYPOINT confusion: know exec-form JSON arrays vs shell form.

On this page