How can a docker container image be constructed “FROM scratch” that only has a python program and the basic python interpreter?
Solution 1:
Actually it is possible (at least for GoLang static binaries) to have only the application binary and from security perspective it's quite reasonable. If you wish to do the same with python , you will need to compile the python code into a binary, but keep in mind that the glibc has only backward compatibility. Thus , if you decide to compile your python code with cpython or pyinstaller - you need to know the container host OS version and compile on it (compiling on latest Fedora, won't work on RHEL 6 ;) ).
Once you have the python code into binary, you can use a Dockerfile to copy your binary and start it inside the container. Then building the container is as usual.
Here is an example how to build your minimal container via buildah.
Solution 2:
The closest you'll get with Python is Google's distroless project that builds docker images with the minimum necessary to run a specific interpreter. That said, I'd question the goal a bit because yes, attackers may not have a shell or package installer, but they'll still have a full interpreter (python in this case) to use for their exploit.
Realize that without a shell, you won't be able to use the string syntax for RUN
, and that python won't be able to shell out to the host, so some things may also break with this approach.
If you switch to a compiled language that can package the result in a single static binary (C, C++, and Go, among others), you'll have a much more secure environment since the only tool inside the container for the attackers to use is the application itself. Even better if you can run that binary with the root filesystem in the container set to read only, and any volumes mounted set to noexec, eliminating the ability of attackers to push their own binaries to run inside the container.