How to build the smallest docker image?

Let’s write simple C-code to be used as our application which just simply print “Hello World!” message on the screen.


const char msg[] = "Hello World!\n";

void _start(){
  syscall(SYS_write, 1, msg, sizeof(msg) - 1);
  syscall(SYS_exit, 0);

Now compile it using gcc compiler and size optimization.

# gcc -static -Os -nostartfiles -fno-asynchronous-unwind-tables hello-world.c -o hello-world

Our next step will be building docker images with below Dockerfile.

FROM scratch
ADD hello-world /
CMD ["/hello-world"]

So let’s build it!

docker build -t hello-world .

And that’s all! Now we have our smallest Hello World image created. It has just 1.84kB!

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              770ca6b8f31c        5 minutes ago       1.84kB

Let’s try to run it.

$ docker run --rm hello-world 
Hello World!