Archive · Docker

Writing Your First Dockerfile

Build an image for a small Node.js app and keep the layers cache-friendly.

1 min read

  • Docker Engine 19.03.9
  • Node.js 12 LTS
  • node:12-alpine

A Dockerfile lists the steps to build an image. Order matters, because Docker caches each layer and reuses it until a step changes.

FROM node:12-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
USER node
CMD ["node", "server.js"]

Copying package*.json and installing dependencies before copying the source means a code change does not reinstall every package. Add a .dockerignore containing node_modules and .git so the build context stays small.

docker build -t myapp:1.0 .
docker run -d -p 3000:3000 myapp:1.0

USER node avoids running as root inside the container. Prefer CMD ["node", "server.js"] (exec form) over a shell string, so signals reach your process and docker stop works cleanly.