~7m10:53
Velum Theory

Docker Image BEST Practices - From 1.1GB to 8MB

Dec 1, 2026

Read: ~8m · You save: 3 min

Docker Image BEST Practices: from 1.1 GB to 8 MB

How to shrink a Go server's Docker image from 1.1 GB to 8 MB, speed up builds, and remove secrets, root access and extra packages. Step-by-step breakdown.

A small web server written in Go responds to one web address and returns a line of text. After compilation, the program takes up about 8 MB. When it was packaged into a Docker image, the image size reached 1.1 GB, more than 100 times the size of the program itself. Size is not the only problem. The image also contains a file with passwords for local testing. Every rebuild takes significantly longer than it should, and the program inside the container runs with full control over the container. Docker issues no warnings about this, since none of these problems are treated as errors.

The goal is to get an image smaller than 8 MB that builds faster and is more secure. Changes are made one at a time, and the size is checked after each step.

Basic Concepts

Image — a packaged copy of everything a program needs to run: the program itself, plus the files and tools it depends on. A running copy of an image is called a container.

Dockerfile — a text file with instructions for building an image. Each line represents one instruction, such as copying files or running a command.

Docker builds an image layer by layer. Each instruction that changes files saves those changes as a new layer. An image is a stack of all its layers.

Two rules determine most build problems and build speed:

  1. Layers are only added. If one line copies a file and the next line deletes it, the deletion only hides the file. The file remains in the previous layer, takes up space, and is accessible to anyone who unpacks the image.
  2. The cache rebuilds everything below a change. Docker stores every built layer in the cache and reuses it on the next build, as long as the line and its associated files have not changed. As soon as one line changes, Docker rebuilds its layer and all subsequent ones.

Each of the fixes described below relies on one of these rules.

Step 1. Excluding Unnecessary Files from the Build Context

When you run docker build, Docker sends the entire project folder that the command points to, to the builder. This folder is called the build context. A Dockerfile copies it into the image in full with one line that copies everything.

A real project folder contains much more than code:

  • a Git folder that stores the complete change history and can be larger than the project itself;
  • log files, test results, and editor settings;
  • an environment file with passwords and keys that is used for testing on the local machine.

According to the first rule, each of these files ends up in an image layer.

The solution is a .dockerignore file, placed next to the Dockerfile, that lists the files and folders Docker should exclude. Its syntax matches that of .gitignore. If you add the Git folder, the logs, and the environment file to this list, they are not sent to the builder and cannot end up in the image.

In a small project the savings amount to a few megabytes. In a project with a long history, they can reach hundreds of megabytes. The file with passwords no longer ends up in the image.

Step 2. Copy Order and Dependency Caching

The original Dockerfile first copied the entire source code and only then downloaded the libraries that the code depends on.

The copy instruction changes whenever any source file is edited. Docker rebuilds that layer and every subsequent one, including the library download. As a result, fixing a single line means downloading all the libraries from the internet again.

The solution is to split the copy into two parts. In Go, a project's list of libraries is stored in the go.mod and go.sum files. First, only these two files are copied, then the libraries are downloaded, and only after that is the rest of the code copied.

The list of libraries changes rarely, so Docker reuses the download layer during almost every build. Only the fast copy at the end gets rebuilt. This principle works in any language: slow steps that rarely change go at the beginning of the Dockerfile, and parts that change every day go at the end.

Step 3. Installing Only the Necessary Packages

During debugging, a line was added to the Dockerfile that installs a text editor, a process viewer, and a database client. The server does not use these tools.

The line was written in a way that is standard for many projects: the apt-get update command downloads the list of available packages, and a separate apt-get install line installs the packages. This approach creates three problems:

  1. The tools take up space, even though the server does not need them.
  2. The package list downloaded by update is saved in its own layer.
  3. The update line never changes, so Docker takes it from the cache. A few months later, when a new package is added to the install line, it is installed from the outdated list.

Rule: install only the packages the program needs at runtime, and run the update, installation, and cleanup in a single line. In this case they are cached and rebuilt together, and the package list is deleted before the layer is saved, so it does not end up in the image. Deleting it in the next line would have no effect.

Removing the tools and the old package list reduced the image by about 70 MB. However, the password file still remained in the image, because it had been deleted in one of the previous lines.

Step 4. Choosing the Base Image and Multi-Stage Build

Most of the remaining size comes from the base image specified in the first line of the Dockerfile (FROM). The original project used the official go image.

This image is a full Linux system with the Go compiler, other build tools, and many common programs. On its own it weighs more than 900 MB, which accounts for almost the entire size of the image.

Official images are often released in lightweight versions:

  • Slim — the same Linux system without unnecessary components;
  • Alpine — an image based on Alpine Linux, a system only a few megabytes in size;
  • Distroless — an image that contains only what the program needs to run, with no command line inside.

The server requires the Go compiler to build, but after the build it does not need the compiler. That is why a multi-stage build is used. A Dockerfile can contain several FROM lines, and each one starts a new stage with its own base image.

  • The first stage takes the full go image, downloads the libraries, copies the code, and compiles the server into a single executable file.
  • The second stage starts from the scratch image, which is completely empty: no system and no files.

Only two items are copied from the first stage into the empty image: the compiled server and the security certificate file that the server needs for secure web requests. The compiler, the source code, and the downloaded libraries stay in the first stage and do not end up in any layer of the final image.

For the program to run in scratch, it must start without system files, which are absent from this image. Go builds such a program when the cgo feature, which links the program to system libraries, is disabled. Most simple Go servers do not need it.

The final image weighs less than 8 MB, which is almost the same as the size of the program itself. If the application is written in Node.js or Python, the final stage requires a runtime environment, so the image will not take up just a few megabytes. Multi-stage builds still remove the build tools, and the effect is usually significant.

Step 5. Working with Secrets

The .dockerignore file prevented the accidental inclusion of a file with local passwords in the image. However, the build sometimes requires a secret, such as a key for downloading a private library.

  • Copying the key as a file leaves it in a layer.
  • Passing the key as a build argument does not help, because such parameters are saved in the image and can be read from its history.

For this task, Docker provides the secret mount mechanism. The key is passed to the docker build command with the --secret option. In the Dockerfile, only the instruction that needs the secret mounts it. The key is available only while that command runs and disappears immediately after it finishes, so it is not written to any layer.

If the key has already ended up in an image, fixing the Dockerfile is not enough. Anyone who has downloaded that image has retained access to the key. The key must be replaced with a new one.

The final image contains no secrets.

Step 6. Running as a Non-Privileged User

By default, the program in the container runs as root, a user with full privileges. Containers are isolated from the computer they run on, but this isolation has already had vulnerabilities.

If an attacker breaks into the server through a bug in the program, root privileges give them maximum capability to cause damage. The USER instruction solves this problem. It tells Docker to run the program as a regular user with a fixed numeric ID, one that cannot modify the files the program is run from.

The scratch image has no user accounts, so only a number is specified. Many guides use 65532 for this purpose. In other base images, you can create a user or use a user that is already included in the official image.

Step 7. Graceful Process Shutdown

When a container stops, Docker sends the main program a SIGTERM signal, which requests that it finish its work. If the program does not exit within a short time, Docker sends SIGKILL, which immediately stops it, even while it is handling a request.

The original Dockerfile started the server with a plain text string. In this form, Docker runs the command through a shell, so the main process is the shell rather than the server. The shell receives the SIGTERM signal but does not pass it on, and the server learns about the shutdown only after it is forcibly killed.

The solution is to write the startup command as a bracketed list, with the path to the program in quotes. Docker then starts the server directly, so the server receives the signal and can finish the requests it has already started.

Test results:

Dockerfile versionStop time
Original (started via shell)11 seconds: Docker waited, then forcibly killed the process
Fixed (started directly)About 1 second

The image has no shell, so the only way to start it is this one.

Step 8. Keeping the Image Up to Date

The FROM instruction specifies a version tag, for example go:1.23. A tag is just a label that image publishers move to a new build with each update. Therefore, the same Dockerfile may build on a different base image a month later without any changes to the project.

To pin the base image, you can fix it by its digest, a long code that points to one specific image and never changes. This makes every build reproducible, but it means security fixes no longer arrive automatically. Pinning by digest only works together with tools such as Dependabot or Renovate, which open a request to update the pinned value when a new version is released.

It is also recommended to:

  • rebuild the image regularly, even if the code has not changed;
  • run an image scanner, such as Docker Scout or Trivy, with every build, since new vulnerabilities are constantly discovered in older software.

Summary

The image size was reduced from 1.1 GB to less than 8 MB. The server builds faster, contains no files with passwords or secrets, runs without root privileges, and correctly completes requests. The next time the server changes, the image scanner will indicate whether any components inside the image need to be fixed.

Problem: a large and insecure image

The original image weighs 1.1 GB, although the program takes up about 8 MB. The image contains a password file, the build is slow, and the process runs as root.

  • The Go program compiles into a binary of about 8 MB
  • The Docker image weighs 1.1 GB, which is more than 100 times larger than the program
  • The image contains a password file for local testing
  • Each rebuild takes too much time
  • The program runs with full control over the container
  • Docker issues no warnings, since these are not errors

Basics: Images, Layers, and Cache

An image is a packaged copy of everything needed to run a program. A running copy is called a container. An image is built from layers, and layers can only be added. The cache reuses layers as long as the instruction line and its files have not changed.

  • An image is a packaged copy of a program and its dependencies
  • A running image is called a container
  • The build recipe is a text file called Dockerfile, where each line is an instruction
  • An image consists of layers; each instruction that changes files creates a new layer
  • Rule 1: a layer can only add; deleting in a later layer merely hides the file
  • Rule 2: Docker caches layers; when a line changes, it and all subsequent layers are rebuilt

Fix 1: Build Context and .dockerignore

The command `docker build` sends the entire project folder to the builder. Without exclusions, the image includes the Git folder, logs, tests, and environment files with passwords. The solution is a `.dockerignore` file.

  • The folder passed to docker build is called the build context
  • The Dockerfile copies the whole folder with a single COPY everything line
  • Projects often include the Git folder, logs, test results, editor settings, and an environment file with passwords and keys
  • Because of the layer rule, all these files end up in the image
  • The .dockerignore file sits next to the Dockerfile and uses the same syntax as .gitignore
  • In a small project the savings are a few MB, while in a project with a long history they are hundreds of MB

Fix 2: Layer Order and Dependency Cache

The original Dockerfile copies all the code before downloading libraries, so every code change re-downloads all libraries. The fix is to copy only the dependency files first, then download them, and only then copy the code.

  • Originally the code is copied before libraries are downloaded
  • Any change to a source file invalidates the cache of the copy step and all subsequent layers, including the download
  • In Go, the list of libraries is stored in go.mod and go.sum
  • First only go.mod and go.sum are copied, then libraries are downloaded, then the rest of the code is copied
  • Slow, rarely changing steps are placed at the top of the Dockerfile, frequently changing ones at the bottom
  • The principle works with any programming language

Fix 3: unnecessary packages and apt-get

The Dockerfile installs unnecessary tools: a text editor, a process viewer, and a database client. Running apt-get update and apt-get install on separate lines causes cache problems and extra layers.

  • Installs a text editor, a process viewer, and a database client
  • apt-get update and apt-get install are written on separate lines
  • The package list downloaded by update is saved in a separate layer
  • The update line is cached, so adding a package may install an outdated list
  • Rule: install only what the program needs at runtime
  • Update, install, and cleanup should be done in one line, and the package list should be deleted before the layer is saved
  • Deleting in the next line does not reduce the image size
  • The fix removes about 70 MB

Fix 4: Base Image and Multi-Stage Build

The base image in the FROM instruction is the main source of image size. The official go image weighs more than 900 MB. For a multi-stage build, the compiler is needed only in the first stage, while the final image is built on an empty scratch image.

  • The FROM instruction sets the base image; the project started with the official go image
  • The official go image weighs more than 900 MB and accounts for almost the entire image size
  • There are slim variants (without extras), alpine (based on Alpine Linux, a few MB), and distroless (only what is needed to run)
  • Multi-stage build: the first stage, based on the go image, downloads libraries and compiles the program
  • The second stage starts from an empty scratch image
  • The final image receives the compiled server and the security certificate file copied into it
  • To work without system files, Go is built with cgo disabled
  • The final image is under 8 MB, almost equal to the size of the program
  • For programs on node or Python, the final stage still requires its own runtime, so the size will be more than a few MB

Fix 5: Secrets

Secrets, such as a key for downloading a private library, must not be copied into an image as a file or passed as a build argument, because they would be saved in image layers or history. Use a secret mount instead. If the key has already ended up in an image, it must be replaced.

  • Copying the key as a file leaves it in an image layer
  • Passing it via a build argument keeps the value in the image history
  • A secret mount passes the key through the secret option of the docker build command
  • In the Dockerfile, only the required command mounts the secret
  • The secret exists only while the command runs and is not written to a layer
  • If the key got into the image, fixing the Dockerfile is not enough: the key must be replaced, since it could have been downloaded

Fix 6: Do Not Run as Root

By default, the program in the container runs as root, which is dangerous if it is compromised. The USER instruction allows running the program as a regular user with a numeric ID. For scratch, a number is specified, for example 65532.

  • By default, the process in the container runs as root
  • Containers are isolated from the host, but this isolation has gaps
  • If compromised, root gives maximum capabilities for causing damage
  • The USER instruction sets a regular user with a fixed numeric ID
  • The program cannot modify the files it was launched from
  • Scratch has no user accounts, so only a number is specified, often 65532
  • In other base images, you can create a user or use an existing one

Fix 7: Graceful Shutdown (CMD in exec Form)

When stopping a container, Docker sends SIGTERM, then SIGKILL. Launching through a command-line shell makes the shell the main process, so the signal never reaches the server. The bracketed list form starts the server directly.

  • Docker sends SIGTERM as a request to shut down, then SIGKILL after a short grace period
  • SIGKILL terminates the process immediately, even while it is handling a request
  • Launching with a plain string runs through a shell, and the shell becomes the main process
  • The shell does not pass the signal to the server, so the server only learns of it at SIGKILL
  • Fix: write the launch command as a bracketed list with the path in quotes
  • The old version took 11 seconds to stop, while the fixed one takes about 1 second
  • In an image without a shell, this form of launch is the only possible option

Keeping Up to Date

Tags like go 1.23 are labels that can change over time. For reproducibility, an image can be pinned by its digest. Pinning requires update tools (Dependabot, Renovate). Regular rebuilds and image scanning are also important.

  • A tag is just a label, and the publisher can move it to a new build
  • Pinning a base image by digest makes the build repeatable
  • Pinning also stops receiving security fixes, so Dependabot or Renovate are needed
  • It is recommended to rebuild the image regularly even without code changes
  • It is recommended to scan the image with Docker Scout or Trivy on every build
  • New vulnerabilities are constantly found in old software