Sub topic 2
Setting Up a Dockerfile
Assume you can use the command line, Docker is installed, and you understand what a container is. A Dockerfile describes how to build an image. A container runs that image.
WORKDIR, COPY, and RUN
WORKDIR sets the current directory inside the image. It creates the directory if needed. Later instructions use this directory.
COPY moves files from the build context into the image. The build context is usually the directory given to docker build. RUN executes a command while the image is being built. Each RUN instruction creates an image layer.
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"]Copying the dependency manifests before the rest of the source lets Docker reuse the dependency layer when only application code changes.
Configuration with ENV and ARG
ENV sets a value that remains in the image and is available when the container runs. ARG provides a value only during the build. Do not put passwords in either instruction because image history can reveal them.
ARG APP_VERSION=1.0
ENV NODE_ENV=production
RUN echo "Building version ${APP_VERSION}"Starting the App
CMD supplies a default command or default arguments. ENTRYPOINT defines the main executable. With both, docker run image 9000 keeps the executable and replaces the default argument.
Use exec form, which is a JSON array, for predictable signal handling and process shutdown.
FROM python:3.12-slim
ENTRYPOINT ["python", "-m", "http.server"]
CMD ["8000"]Building, Tagging, and Running
Run these commands from the directory containing the Dockerfile:
docker build -t myapp:1.0 .
docker run --rm -p 3000:3000 myapp:1.0The final . sends the current directory as the build context. -t assigns a name and tag. -p maps host port 3000 to container port 3000. --rm removes the stopped container.
Exercise
Why should package.json be copied before the rest of the source?
Show answer
Docker can reuse the npm install layer when application source files change but dependency manifests do not.