Sub topic 1
What a Dockerfile Does: Images, Containers, and Layers
Prerequisites
Assume you can use a command line, have Docker installed, and understand that a container runs an application in an isolated environment.
Images, Containers, and Layers
A Dockerfile is a text file that describes how to build a Docker image. An image is a packaged application filesystem plus metadata, such as its startup command. An image is a reusable template.
A container is a running instance of an image. You can start several containers from one image. Each container gets its own writable layer on top of the image's read-only layers.
Each Dockerfile instruction usually creates an image layer. Layers can be reused between builds and images. This makes builds faster and reduces repeated storage.
Anatomy of a Dockerfile
Instructions usually appear in dependency order. FROM selects the starting image. WORKDIR sets the working directory. COPY adds files from the build context. RUN executes a command while building. ENV sets an environment variable. EXPOSE documents the intended port. USER selects the runtime user. CMD supplies the default startup command.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]The JSON array in CMD is the exec form. It starts the process directly, so the application receives signals correctly. Shell form, such as CMD node server.js, starts through a shell and can behave differently.
The Build Context
The build context is the directory, and its contents, sent to Docker for a build. In docker build -t myapp:1.0 ., the final . is the context. COPY can read only files inside this context.
Keep the context small with .dockerignore:
node_modules
.git
*.log
.envThis prevents unnecessary files and secrets from being sent to the builder.
Choosing a Base Image with `FROM`
FROM determines the initial filesystem and available tools. A slim image usually reduces size, while a full distribution can simplify debugging. Pin a deliberate version, and choose an image maintained for your language runtime. Avoid adding build tools to the final image when they are unnecessary.
Exercise
What is the difference between an image and a container?
Show answer
An image is a reusable package; a container is a running instance of that image with a writable layer.