I believe it’s everyone’s fascination to create their very own Operating System and it’s been exactly that fascination paired with a “healthy” dose of “How hard can it be?” that got me into it.

There are a handful of very good resources out there already. I wont repeat what Linux From Scratch or OS Dev Wiki do but rather go a different approach.

This approach is by no means unique and is actually being used by Flatcar Linux , ChromeOS and many more.

Gentoo being notoriously known for making their users compile every little bit from scratch (and hands down my go-to distro for over a decade now) has an amazing package manager that deals with everything required to reproducibly compile and track source code.

But Portage can do so much more than just compile and install your programs.

Let’s start with something easy to get used to it.

Something Easy

So let’s start with creating a bare minimum docker container for your favourite application that isn’t statically compiled - otherwise it would’ve been too easy ;)

Python is a decent enough example because it requires so damn many things but also because statically compiling python is even more tedious.

FROM gentoo/portage:latest as portage
FROM gentoo/stage3:nomultilib as builder

# Copy portage tree (AKA the repository)
COPY --from=portage /var/db/repos/gentoo /var/db/repos/gentoo

# Remove portage features we cant use due to missing privileges
ENV FEATURES="-ipc-sandbox -network-sandbox -pid-sandbox" 

RUN mkdir /out \
 && emerge -1v --usepkgonly --quickpkg-direct=y --ignore-soname-deps=y --with-bdeps=n --root=/out --root-deps=rdeps --jobs=$(nproc) python

FROM scratch
COPY --from=builder /out /
ENTRYPOINT [ "/usr/bin/python3" ]

This will take a while to complete since it actually compiles stuff. It will also add some other things into the final build because after all we’re asking Portage to compile python as if it were for the Gentoo OS, so it’s not absolute bare-minimum but very close to it.

The resulting image ships with /usr/bin/python3 and barely anything else, it weights about 296MB which is quite hefty I must admit. This is because it’s really not slimmed down, it’s a full python installation.

But slimming down wasn’t really the point of this exercise, it was to get an application with it’s dependencies into a standalone container. And we got exactly that. Without much hassle even.

Okay. What now?

Now let’s go a bit deeper and build a partial operating system (we’ll leave out the kernel for simplicity in this pt1) - but that will have to wait until Pt2. Sorry folks.