Writing a Dockerfile
Building your own image: FROM, WORKDIR, COPY, RUN, EXPOSE and CMD, layer caching and .dockerignore.
A Dockerfile is a recipe for building an image. Each instruction adds a layer:
FROM— the base image (for examplenode:20-alpine).WORKDIR— the folder inside the image where the next commands run.COPY— copy files from your project into the image.RUN— run a command while building, such as installing dependencies.EXPOSE— document the port the app listens on.CMD— the command that runs when a container starts.
Docker caches layers. Copy the dependency file and install before copying the rest of the code, so code changes don't reinstall everything. Add a .dockerignore (with node_modules, .git, .env) to keep images small and secrets out.
Example in the terminal
Run these on your own computer$ cat Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]
$ cat .dockerignore
node_modules
.git
.env
$ docker build -t job-api:1.0 .
[+] Building 18.4s (10/10) FINISHED
=> [3/5] COPY package*.json ./
=> [4/5] RUN npm ci --omit=dev
=> naming to docker.io/library/job-api:1.0
$ docker run -d -p 3000:3000 --name api job-api:1.0
$ curl localhost:3000/health
{"status":"ok"}
$ docker images job-api
REPOSITORY TAG SIZE
job-api 1.0 142MB
Lines starting with $ are commands you type; the rest is what the terminal prints. Use Linux, macOS, WSL on Windows or a free cloud shell. Names and paths are examples.
Key points
- A Dockerfile builds an image step by step.
- Install dependencies before copying code to reuse cached layers.
- Use .dockerignore to exclude node_modules, .git and .env.
- Run as a non-root user (USER) and use small base images.
Quick check
Why copy package.json and run npm ci before COPY . . ?
Docker reuses unchanged layers. If package.json didn't change, the npm ci layer comes from cache and builds are much faster.
Practice task
Write a Dockerfile for a small Python or Node app, build it with a version tag, run it and check the image size with docker images.
Interview corner
What is the difference between CMD and ENTRYPOINT?
Both define what runs when the container starts. CMD provides defaults that are easily overridden by arguments to docker run; ENTRYPOINT fixes the executable, and CMD then supplies its default arguments.
How do you reduce Docker image size?
Use slim or alpine base images, multi-stage builds so build tools aren't in the final image, a .dockerignore file, combined RUN steps that clean caches, and only production dependencies.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.