How do I write a Dockerfile?

Updated October 2026 · How we answer

Short answerA Dockerfile is a text file with instructions to build a Docker image. Start with a base image (FROM), copy your code (COPY), install dependencies (RUN), and set the startup command (CMD).

Basic Structure

A Dockerfile is a plain text file named exactly 'Dockerfile' (no extension) placed in your project root. Each instruction creates a layer in the image. The order matters: put things that change less often (like installing system packages) near the top to take advantage of Docker's layer caching.

The most common instructions are FROM (base image), WORKDIR (set working directory), COPY (copy files from host to image), RUN (execute commands during build), and CMD (default command when container starts). You can also use ENV for environment variables and EXPOSE to document ports.

  • FROM node:18-alpine — start from a small Node.js image
  • WORKDIR /app — set the working directory inside the container
  • COPY package*.json ./ — copy dependency files first for caching
  • RUN npm ci --only=production — install dependencies
  • COPY . . — copy the rest of your code
  • CMD ["node", "server.js"] — run your app

Building and Running

Once you have a Dockerfile, build the image with 'docker build -t my-app .' from the same directory. The '-t' gives it a name (tag). Then run it with 'docker run -p 3000:3000 my-app' to map port 3000 on your host to port 3000 in the container.

If you need to debug, use 'docker build --progress=plain .' to see full output, or 'docker run -it my-app sh' to get a shell inside the container. Remember that each RUN instruction runs in a separate layer, so combine related commands with && to reduce layers and image size.

Common mistakes

  • Putting COPY . . before installing dependencies, which invalidates the cache every time any file changes.
  • Using CMD in exec form incorrectly (e.g., CMD node server.js instead of CMD ["node", "server.js"]) can cause signal handling issues.
  • Forgetting to create a .dockerignore file, which can accidentally copy node_modules or .git into the image.
From our shopsTitan Case: Premium MagSafe iPhone cases with a precision fit.