← Learning Hub
Advanced

Writing a Dockerfile

A Dockerfile describes how to build your app's image, step by step. Here's one for a Node.js API (see the Node.js course):

A Dockerfile is the recipe for your app's image: base image, files, install steps, start command. Writing it well keeps images small, builds fast thanks to caching, and avoids security mistakes like shipping secrets.

Example
# Dockerfile
FROM node:22-alpine              # start from an official small Node.js image
WORKDIR /app                     # folder inside the image

COPY package*.json ./            # copy only the package files first...
RUN npm ci --omit=dev            # ...so this slow step is cached when only code changes

COPY . .                         # then copy the rest of the code
ENV NODE_ENV=production
EXPOSE 3000                      # the port the app listens on
USER node                        # don't run as root
CMD ["node", "server.js"]        # the command that starts the app
Example
# .dockerignore - keep these out of the image
node_modules
.env
.git
*.log

Build and run

Example
docker build -t shop-api:1.0 .              # -t gives it a name:tag; . = use this folder
docker run -d -p 3000:3000 --env-file .env --name api shop-api:1.0
docker images                               # list images on your computer

Multi-stage builds

Build tools aren't needed to run the app. A multi-stage build compiles in one stage and copies only the result into a small final image. Example for a Spring Boot app (see the Spring Boot course):

Example
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -q dependency:go-offline
COPY src ./src
RUN mvn -q package -DskipTests

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /src/target/*.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]
Never put secrets (passwords, API keys) in a Dockerfile or image - anyone with the image can read them. Pass them at run time with -e or --env-file.
Key points
  • FROM, WORKDIR, COPY, RUN, CMD are the core instructions.
  • Copy dependency files first for faster builds.
  • Never bake secrets into images.

📝 Test yourself

1. Why copy package.json before the rest of the code?
2. Where should secrets go?
3. Fill in the instruction that sets the start command:
["node", "server.js"]