Pregunta de Containerization #019e3a4f
What is a best practice to minimize the container image size?
Use a DockerFile.
Use multistage builds.
Build images with different tags.
Add a build.sh script.
Explicación Oficial / Explicaciones de la Comunidad
Summary
Multistage builds are a best practice to minimize container image size by allowing you to use multiple FROM statements in a single Dockerfile. Each stage can use a different base image, and you can selectively copy only the necessary artifacts from one stage to another, discarding intermediate build dependencies and tools.
How It Works
In a multistage build, you define multiple build stages. The first stage might use a full SDK or compiler image to compile your application. The final stage uses a minimal runtime image (e.g., alpine or scratch). Using the COPY --from directive, you copy only the compiled binary or necessary files from the earlier stage into the final stage. This ensures that the final image contains only what is needed to run the application, significantly reducing its size.
Why Multistage Builds Are Correct
- Reduces image size: By separating build-time dependencies from runtime dependencies, the final image is lean and secure.
- Improves security: Fewer packages mean a smaller attack surface.
- Simplifies Dockerfile: A single Dockerfile can handle both build and runtime stages without needing external scripts or multiple Dockerfiles.
Why Other Options Are Incorrect
- Using a DockerFile: This is a generic practice for building images, but it does not inherently minimize size. A poorly written Dockerfile can produce large images.
- Building images with different tags: Tags are just labels for versions; they do not affect image size.
- Adding a build.sh script: This is an external build script that does not directly reduce image size. It may even increase complexity without size benefits.
Best Practices for Minimal Images
- Use multistage builds.
- Choose minimal base images like
alpineorscratch. - Clean up package manager caches in the same layer.
- Combine
RUNcommands to reduce layers. - Avoid installing unnecessary packages.