0
0
Dockerdevops~5 mins

Scratch base image for minimal containers in Docker - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want your container to be as small as possible with only your app inside. The scratch base image is an empty starting point that helps you build tiny containers without extra files or software.
When you want to create a container with only your compiled app and no extra system files.
When you need the smallest possible container size to save storage and speed up downloads.
When your app does not need any operating system tools or libraries to run.
When you want to improve security by reducing the attack surface inside the container.
When you are packaging a static binary or a simple script that runs alone.
Config File - Dockerfile
Dockerfile
FROM scratch
COPY hello /hello
CMD ["/hello"]

FROM scratch starts the build from an empty image with no files.

COPY hello /hello adds your compiled app named 'hello' into the container.

CMD ["/hello"] tells the container to run the app when it starts.

Commands
Builds the Docker image named 'hello-minimal' using the Dockerfile in the current folder.
Terminal
docker build -t hello-minimal .
Expected OutputExpected
Sending build context to Docker daemon 2.048kB Step 1/3 : FROM scratch ---> Step 2/3 : COPY hello /hello ---> Using cache ---> 3b1f4f5a6c7d Step 3/3 : CMD ["/hello"] ---> Using cache ---> 7a8b9c0d1e2f Successfully built 7a8b9c0d1e2f Successfully tagged hello-minimal:latest
Runs the 'hello-minimal' container and removes it after it stops to keep your system clean.
Terminal
docker run --rm hello-minimal
Expected OutputExpected
Hello, world!
--rm - Automatically remove the container when it exits
Shows the size and details of the 'hello-minimal' image to confirm it is very small.
Terminal
docker images hello-minimal
Expected OutputExpected
REPOSITORY TAG IMAGE ID CREATED SIZE hello-minimal latest 7a8b9c0d1e2f 10 seconds ago 1.2MB
Key Concept

If you remember nothing else from this pattern, remember: the scratch image is a completely empty container base that lets you build the smallest possible containers by adding only what you need.

Common Mistakes
Trying to run a non-static binary or app that needs system libraries inside a scratch container.
Scratch has no operating system files or libraries, so apps that depend on them will fail to run.
Compile your app as a static binary or use a base image with needed libraries if your app requires them.
Not copying the app file into the container or using the wrong path.
The container will not find the app to run and will exit with an error.
Use COPY with the correct source and destination paths matching your app location and CMD.
Summary
Use FROM scratch in your Dockerfile to start with an empty container image.
Copy only your static binary or app into the container to keep it minimal.
Run the container with docker run and verify the small image size with docker images.