You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A Dockerfile is a plain-text script containing a series of instructions that Docker executes in order to build an image. Every line in a Dockerfile creates a new layer in the image. Understanding how to write efficient Dockerfiles is one of the most important Docker skills.
# Start from an official base image
FROM node:20-alpine
# Set the working directory inside the container
WORKDIR /app
# Copy dependency manifests first (for layer caching)
COPY package.json package-lock.json ./
# Install dependencies
RUN npm ci --omit=dev
# Copy the rest of the application source
COPY . .
# Expose the port the app listens on
EXPOSE 3000
# Default command to run when the container starts
CMD ["node", "src/index.js"]
# Build an image from a Dockerfile in the current directory
# -t gives the image a name and optional tag
docker build -t my-app:1.0 .
# Build with a specific Dockerfile
docker build -f Dockerfile.prod -t my-app:prod .
# View the image you just built
docker images my-app
# Run the image to test it
docker run --rm -p 3000:3000 my-app:1.0
Docker caches each layer. When you rebuild an image, Docker reuses cached layers for every instruction that has not changed. Once a layer is invalidated — because a file it depends on changed — all subsequent layers are rebuilt.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.