Dockerfile Optimization
Dockerfile optimization means making an image smaller, builds faster, and deployment more stable through layer design, build order adjustment, and base image selection, while ensuring the image functions correctly. It is the most easily overlooked link between a model service that "runs on my machine" and one that "goes live reliably," and it directly determines release speed, pull time, and the size of the security surface.
Core Principles
A Docker image is formed by stacking a series of read-only layers; each instruction generates a layer, and once a layer is generated it cannot be modified, only overlaid by new layers. This mechanism has two consequences: first, deleting a file can only be done within the same layer, and cross-layer deletion merely places a whiteout marker while the underlying data still occupies space; second, during a build, as long as the content of an instruction matches the cache, subsequent layers can directly reuse the cache. Understanding "layer stacking" and "cache hits" means understanding the whole starting point of optimization.
Therefore the truly effective optimization methods almost all revolve around these two points: making the image small relies on multi-stage builds and streamlined base images; making builds fast relies on putting low-frequency-of-change instructions early and high-frequency ones late. Many teams write Dockerfiles like scripts, arranged in sequence from beginning to end, installing dependencies, copying code, installing models, and changing configuration, so that every one-line code change requires reinstalling dependencies, and the build goes from two minutes to twenty.
Key Points
First, multi-stage builds are the mainstay of reducing size. The compilation toolchain, test dependencies, and download caches all stay in the build stage, and the final stage only copies artifacts from a clean base image, using --from=build to copy precisely when necessary. This is especially obvious in Python scenarios, where many packages need gcc and pybind headers during installation but are not needed at all at runtime.
Second, layer cache order must be designed deliberately. First COPY the dependency manifest (requirements.txt, pyproject.toml, package.json), then run the installation, and only then COPY the source code. In this way, when business code is changed the dependency layer hits the cache and the build takes only seconds. Where multiple RUN commands can be merged with &&, merge them, and clean apt caches and pip caches within the same layer.
Third, slim-type base images are preferable to full versions. python:3.11-slim, or a slim tag with a pinned version number, is usually only a fraction of the full version's size, which is enough as long as the business does not depend on the compilation toolchain and complete system tools. When greater controllability is needed, distroless can be used, at the cost of fewer debugging means; the container does not even have a shell, and troubleshooting can only rely on external logs and probes.
Fourth, do not COPY model files into the image. Once weights of several GB enter a layer, the image becomes permanently bloated, and every release must push gigabytes, nodes pull slowly, storage costs are high, and coupling weights with code makes rollback difficult. The correct approach is to place weights in object storage, a shared volume, or a model repository, mounted or downloaded at container startup, with the image retaining only the loading logic and verification logic.
Fifth, make good use of .dockerignore to exclude .git, virtual environments, local logs, and test data from the build context; the larger the build context, the higher the transfer overhead of each build. At the same time, pin base image tags instead of latest to guarantee reproducible builds.
Common Misconceptions
Misconception one: copying code before installing dependencies. It seems only a matter of order, but in fact it invalidates the cache on every change and multiplies CI time. Misconception two: thinking RUN rm can reduce size. Deletion is only effective within the same layer, and cross-layer deletion merely masks. Misconception three: using the latest tag to save trouble, until one day an upstream update suddenly breaks the build and there is no way to roll back to yesterday's environment.
Application Scenarios
Slimming images for model inference services, speeding up CI builds, consistent deployment across environments, image distribution in offline environments, image trimming for edge devices, and convergence of base images for security compliance.