Dockerfile basics (build an image)
Topic: Containers core
Summary
Write a Dockerfile with FROM, RUN, COPY, and CMD to build a container image. Use multi-stage builds to keep the final image small. Use this when creating a custom image for your application or when optimizing build time and image size.
Intent: How-to
Quick answer
- FROM base image (e.g. alpine, debian); RUN for commands (apt install, pip install); COPY to add files; CMD or ENTRYPOINT for the default command. Each instruction is a layer; order for cache (least-changing first).
- Multi-stage: FROM builder AS build; RUN build steps; FROM runtime; COPY --from=build /app /app. Final image has only runtime and built artifact, not build tools. Use .dockerignore to exclude files from context.
- Build: docker build -t myimage:tag . Run the container and test; push to a registry with docker push. Prefer specific base tags (alpine:3.18) not latest; pin dependency versions in RUN.
Prerequisites
Steps
-
Minimal Dockerfile
FROM alpine:3.18 RUN apk add --no-cache nginx COPY nginx.conf /etc/nginx/ CMD ["nginx", "-g", "daemon off;"] Build: docker build -t mynginx .
-
Layer order and cache
Put COPY of dependency files (package.json, requirements.txt) before COPY of source; then RUN install. So install layer is cached until deps change. Put COPY of source last.
-
Multi-stage (optional)
First stage: FROM golang AS build; COPY . .; RUN go build. Second stage: FROM alpine; COPY --from=build /app/binary .; CMD ["./binary"]. Final image has no Go toolchain.
-
Build and test
docker build -t myapp:1.0 .; docker run --rm myapp:1.0. Add .dockerignore (git, docs, test) to speed build. Push: docker tag myapp:1.0 registry/myapp:1.0; docker push registry/myapp:1.0.
Summary
Write a Dockerfile with FROM, RUN, COPY, CMD; use multi-stage to reduce size; build with docker build and test. Use this to create and maintain application images.
Prerequisites
Steps
Step 1: Minimal Dockerfile
Create a Dockerfile with FROM, RUN, COPY, and CMD; build with docker build -t name .
Step 2: Layer order and cache
Order instructions so dependency install is cached; copy source last.
Step 3: Multi-stage (optional)
Use multi-stage to build in one stage and copy artifacts into a smaller runtime image.
Step 4: Build and test
Build, run, and test; use .dockerignore; tag and push to a registry.
Verification
- Image builds; container runs and behaves as expected; image size is acceptable.
Troubleshooting
Build fails — Check RUN commands (paths, packages); ensure context has required files. Image too large — Use multi-stage; use smaller base (alpine); remove cache in same layer (apt clean, rm -rf /var/cache).