383 points · by kiyanwang · 5y ago · 159 comments
Also, https://busybox.net is a 1.0MB static binary that provides all of the standard posix-compliant tools (sh, grep, tail, etc) and actually comes with an httpd implementation. So if you wanted a more useful container at about 1MB, you could use it.
Edit: here's a previous thread on UPX that has 80 comments talking about the tradeoffs it makes. You should definitely consider these if you intend to use UPX: https://news.ycombinator.com/item?id=15456980
[1] https://docs.docker.com/storage/storagedriver/overlayfs-driv...
So in fact, it’s not might use more resources, it’s guaranteed to use more resources.
The only benefit of UPX is saving disk space, which is unlikely to be super useful to most people these days.
Similar to how saving disk is less useful to most people these days, RAM on servers in big docker/kubernetes clusters is also likely not much of a concern for binaries that are well under 100MB if you're not running a ton of copies on each server. In particular, it seems like this tradeoff is most useful for static go binaries, which don't benefit from shared system libraries and aren't likely to have many copies per server, but of course that definitely depends on the use case and I definitely do not recommend blindly using UPX without considering the tradeoffs.
It would be an amazing integration though if it were possible to integrate UPX with docker's layer compression such that the binary is extracted to the FS before running. But given how it all works, that's pretty challenging to implement and the network is only getting faster...
It added 18.5 kB on top of busybox, so, not as good as the 6kB ASM server code. With busybox included, the whole image is 1.18 MiB, or 751 kB compressed.
If anyone cares to take a look: https://hub.docker.com/r/swalog/tiny-hello/
I figured there were a bunch of ways to shrink that one, and I had a C based image that was in between my GO and ASM images, but decided to cut them for the sake of brevity!
gives you a multiprocess http server in 612K uncompressed if you compile -Drelease-small
$ ls -shL `nix-build -E '(import <nixpkgs> {}).pkgsCross.musl64.busybox.override { enableStatic = true; enableMinimal = true; }'`/bin/sh
128K /nix/store/qkq9cj81mcvnfr5y04jmf6nqvnrfg2z1-busybox-1.31.1-x86_64-unknown-linux-musl/bin/sh
But yeah, the tradeoff of that 1MB is that you get a very functional shell environment vs just an http server. It's impressive just how small ut is, given everything that it is capable of
They do distribute statically linked individual binaries [0]. For just HTTPD and nothing else is about 85kb. But it is a lot more than just a static file server - it comes with CGI support.
Maybe.. I suspect a well-designed Forth image could pack similar capability in less than 100kB. So it might seem low, but not a miracle.
In a world of xTB thumbdrives, why are we so worried about containers being <1MB? Security is one thing, minimalism is another, but I do sometimes wonder about this.
Anyway, if you want to build minimal containers and want to do it with a bit more backing than this one (pretty well written) blog post, probably also check out distroless:
https://github.com/GoogleContainerTools/distroless
I personally find most of the time alpine-based containers are more than small enough and good enough with nice ergonomics (sometimes you just want to shell in to the container), but maybe it makes sense to build containers with and without debugging/inspection tools (a `project:vx.x.x` and a `project:vx.x.x-debug`) and switch them out when problems arise.
You not only store these images once in the registry, but on all container hosts that they might run on. And you need to transmit them, if they aren't cached there, yet. And you may want to redeploy new images several times a day, as they get updated, new ones added, etc.
To be fair, the above is not the use case containers were originally intended for. And if your 10 GiB container image only runs on 3 or 5 nodes and only gets updated once a week, you obviously don't have to worry about the overhead too much.
But at scale (beyond 10 nodes) and/or on very fast development cycles (=more then one deployment per day), size IMHO starts to matter.
If you separate the heavy stuff into a base-image you still have to load it on the beginning of CI, which without beefy machines with local SSD caching can take a loooong time.
I can certainly see that it can be a painful problem (10-40GiB is huge), but I expect most smaller shops that aren't running on their own servers/colo as such these image sizes were never even an option (I can't imagine trying to upload 40GB across the public internet to launch one instance!).
It's also not usually total-person-clock-time.
It's number-of-distinct-manual-steps.
(5 minutes manual) + (15 minutes automation) + (5 minutes manual) + (30 minutes automation) = everyone hates doing it
(10 minutes manual) + (45 minutes automation) = everyone's happy and can use their time productively
A general observation on trade-offs: With containers layering and COW you get fast development, but have to pay the performance bill when you happen to download and apply an image for the first time. Similarly, taking a snapshot of a LV under LVM or on a ESXi VM is fast, but applying the snapshot is slow.
We had therefore at one point considered using Ceph RDB and their COW clone snapshots[0]. It would let us do "cheap" restores of snapshots. Our initial tests showed that the network bandwidth requirements[1] would have needed some serious infrastructure re-engineering in order to keep up with our I/O expectations. And again, the containers slot in nicely with commonly available local resources and allow working offline, to a degree.
[0] https://docs.ceph.com/en/latest/rbd/rbd-snapshot/ [1] the environment in question uses 10 - 40 Gb/s network links, 40 on the gitlab git and container registry side, 10 on the blade side.
That said, dependencies do take up a lot of space, but machines these days also come with a lot of space. People also run prune and develop caching strategies (ex. NPM) as a result. It's not like every container will be a GB in size, as it's not reasonable to have every container have that much content, but how many people are out there using 950MB dependency-filled base containers with 50MB of actual relevant application code? Most people learned the run-it-on-alpine lesson like 5+ years ago at this point.
When software was still delivered in physical boxes, I noticed the same thing and I even found products in the past where the .exe had megabytes of random data attached to it to make it look bigger.
With Docker images it's all a lot easier to bloat things up and 'hide things'; I used to pack up our main product in a chroot tgz (this is early 2000s) with an installer, so I did not have to actually think about different linux distro's or installers; I know for a fact that some people bought our product over competitors because the installer was so large in size so it looks like better value. People told me when I asked them afterwards why they did not go for the competition. And this was not intentional; it just had a full Debian install in a chroot.
Good question! Security should be a priority instead.
A lot of containers on docker hub have serious vulnerabilities, as proven by various research papers. Removing bloat is good for security.
However, using a well-tested distro and receiving security updates from its security team is more important than having a tiny footprint.
This is a good reason to use Debian stable in containers and avoid alpine.
I've written guides on how to boot Alpine (even with GUI) over PXE [1] and how to set up a perfect file server that runs from a RAMdisk USB Thumb drive with full disk encryption [2]
[1] https://blog.haschek.at/2019/build-your-own-datacenter-with-... [2] https://blog.haschek.at/2020/the-perfect-file-server.html
Base Ubuntu/Fedora used to be absolutely huge, and no one was smart/patient enough to pick out all the dynamic libs that you needed with your JAR or script to go into production so you usually just shipped the whole fat image.
https://blog.haschek.at/2020/the-perfect-file-server.html is made obsolete by SmartOS, which does the exact same thing, in addition to offering Triton (enterprise web GUI for virtual systems), OpenZFS (end-to-end data protection, ease of administration), zones (full-blown, running-at-the-speed-of-metal virtual UNIX servers), DTrace (for production-safe, real-time, deep machine state instrumentation and inspection), Bardiche (for building firewalls), FireEngine / Crossbow (high-performance TCP/IP stack for building virtual switches and routers) and imgadm(1M) / vmadm(1M) (for virtual server provisioning and software management), and last but not least, a reference implementation of the NFS V4 protocol.
or by proxmox or by any other OS. That's not what it's about. If it comes with a web gui, it's already bloated for me. This project was about the minimal perfect setup for my needs and I only need SSH access
Thank you for those links, I am about to gobble up those blog posts -- I recently went on a benchmarking kick[1] and diskless alpine instantly struck me as the perfect server setup. ECC memory + running from ram would give me full use (to put in RAID/whatever else) of the NVMe drives, it's something I'm going to try out as soon as I get a chance to.
I am so interested in the infrastructure space, I know exactly two hosting providers that will give me PXE level access (so I could use something like tinkerbell[2]):
- OVH [3][4]
- Vultr[5]
- LeaseWeb[6]
Unfortunately my personal favorite hosting provider, Hetzner[7] (I fell in love the moment I came across the robot marketplace) does not offer it yet, though I've automated going through their rescue system at this point so it's OK.
[0]: https://www.tfir.io/meet-the-creator-of-alpine-linux-natanae...
[1]: https://vadosware.io/post/k8s-storage-provider-benchmarks-ro...
[2]: https://docs.tinkerbell.org/
[3]: https://github.com/gmasse/ovh-ipxe-customer-script
[4]: https://geekgonecrazy.com/2020/09/07/tinkerbell-or-ipxe-boot...
[5]: https://www.vultr.com/docs/ipxe-boot-feature
[6]: https://kb.leaseweb.com/products/dedicated-server/installing...
In one place in Africa driving to another site 3 hours away gets network speed 10x better, so we do this from time to time.
Saving 10% in size may actually translate to a non-trivial cost saving - both obvious and cost-as-in-paid-waiting-time.
This is exactly what we do. Once the first build of our application is installed on our customer's servers, it rebuilds itself from source each time. This is also really good at firewalling CI/CD compromises away from your customers, as long as you don't merge cryptolockers/miners into your private github repos.
I found that most people focus on size and forget about reuse.
Sure, each layer adds size to your final image, but you can reuse them, so that you don't need to transfer the complete image but just the layers on top of the one that changed.
Flatten everything and you need to ship the whole stuff.
This container ends up being 436 bytes https://github.com/sigmonsays/smallest-docker-httpd
paulfurtado in this comment section mentioned UPX[0] as a way to get binaries even smaller. Funnily enough UPX even managed to decrease the size of the asmttpd web server for me:
### build stage ###
FROM ubuntu:18.04 as builder
RUN apt update
RUN apt install -y make yasm as31 nasm binutils git
RUN git clone https://github.com/nemasu/asmttpd.git asmttpd
RUN mv asmttpd/* .
RUN rm -rd asmttpd
RUN make release
# i have the upx binary on my machine in this case
COPY ./upx-3.96-amd64_linux/upx upx
RUN ./upx --brute asmttpd
### run stage ###
FROM scratch
COPY --from=builder /asmttpd /asmttpd
COPY ./index.html /web_root/index.html
CMD ["/asmttpd", "/web_root", "8080"]
With a 4 byte index.html my total image size is now 5.3kB!Thanks for the kind words. I didn't know about UPX.
I should add an update to the end with this trick!
Here is an image with a statically linked chown binary from the busybox tools cowering this use case: https://hub.docker.com/r/privatebin/chown (I am the author of that image)
Benefits of using a small image are less attack surface and faster operation (less data to download, lower startup time, less memory, etc.).
My (somewhat silly) use case for the tiny container was trying to cram 10,000 pods onto a k8s cluster without breaking the bank: https://www.youtube.com/watch?v=1y2nRNexRVk
Containers do provide benefits.
Containers are not a security measure. They're acceptable for some resource constraint considerations, but you should not ever use them because of security concerns. If that's something to worry about, use VMs at the very least.
If you can easily break out of any containerized enviornment, I'd suggest you could register for bug bounty programmes and make quite a lot of money also you can get a reward from Jessie Frazelle by escaping from https://contained.af/
Obviously containers have a larger attack surface than say a VM hypervisor, but security is not an absolute and both containers and VMs have suffered from breakout issues in the past. No security measure in isolation provides perfect protection.
This is repeatedly really commonly, but is bordering on wrong more and more every year. At the lowest level it's not even completely correct. Containers are resource + namespace isolation -- cgroups and namespaces -- isolation and kernel-assisted resource hiding/access control is absolutely a facet of good defence-in-depth. Enhanced security is not a core feature of containerization as a whole but it can absolutely help with your security posture.
For what % that satement is wrong, it's even more so because it fails to consider the container runtime. Container runtimes these days (containerd is the best one IMO) include ways to run containers at different levels of isolation (VMs and as micro kernels), so a move to containers can absolutely help security posture, because now you don't have to pull out packer/ansible/etc to build your VM, you can just take the same container you were running and change the runtime. Time to ship/launch improved security features is important, and containers can reduce that burden for teams.
Containers are a process isolation and resource control tool -- they can absolutely aid in security posture. Would you say the same about BSD Jails?
Just so there's some more value here, here are some projects that are somewhat close to cutting edge (though it's been a while) in this space that I like:
- nabla-containers.github.io/
- https://github.com/firecracker-microvm/firecracker-container...
- https://github.com/kata-containers/runtime (see https://github.com/kata-containers/documentation/blob/master...)
- https://rootlesscontaine.rs/
- https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2...
- https://starkandwayne.com/blog/the-capable-kernel-an-introdu...
The container ecosystem surfaces a lot of really cool resource limiting and isolation techniques and puts them in very close reach.
Yes, you'd need to learn how to make a systemd unit file but honestly, that shouldn't be a problem at all. I've had much worse headaches fighting Docker's networks and firewall-overruling network configuration in the past. Every time I forget to specify a restart option, I have to dig through my shell history again to see how I launched the image so I can kill and recreate it, or I have to look up that oneliner that shows you the docker run command for a running container.
I run stuff in Docker for one simple reason: I have it installed and I'm too lazy to think about software sometimes. If you're packaging software, that laziness isn't a reason to pick a distribution tool.
Static binaries have other problems, perhaps most importantly package management. How do you distribute your app? Traditional deb/rpm packages? curl-to-bash installers? Snap? Flatpak? Binaries that people flog into /usr/bin? What about automated updates, do you set up a repository, do you include a self-updater in your code? The list goes on. Docker solves that by having one general source of packages with the option of adding a repo of your own (take note, Canonical, your shitty Snap Store is practically useless without that last bit).
For services I run on servers, I much prefer traditional packages with dynamically linked executables, for a simple reason: automatically fixing security issues and bugs across applications with a single update command, instead of having to wait for every maintainer of their statically-linked tool to update their dependencies.
It's one of the big problems I have with Rust; many dependencies and applications embed their own versions of dependencies with sometimes very specific versions, and when there will eventually be a massive security problem in one of the TLS packages I'm dependent on recompiles and code modifications from random open source maintainers.
Restated, my point here is that while containers can be more complex and have pitfalls (a lot of which have been worked out somewhat at this point), there is no complexity free lunch -- `[docker|podman|crictl] run --rm --cpus 2 --memory 500mb ...` is pretty darn easy, and more so than writing properly portable and well-considered systemd unit files (and putting them in the right place, with the right permissions, under the right slice, etc). It's easier than most of the options out there (including the old methods of per-user resource segregation).
I let you research when that was, and wonder what container technologies might have used since then.
I know when they make sense and when they happen to be fashion.
Half the "static" binaries that used to float around weren't even fully static because of glibc, until building with musl (and getting bit by getaddrinfo) became widespread -- the situation is not as simple as you made it seem.
It contains everything you need, can provide sandboxing, integrates well in the OS, can do deploy and rollback, manages configuration changes.
https://github.com/opencontainers/image-spec/blob/master/ima...
Scratch has no tooling or libraries or anything. It's empty. You typically add a binary into it and then just run that binary, but due to the lack of libraries, it just be statically compiled. So in answer to your question, you can run statically compiled C. You can't run Java due to the lack of JVM which I believe has its on set of filesystem dependencies, but I'm not a Java dev, so I'm not entirely sure.
Why aren't everyone just using scratch?
If you need some basic OS files, Google's distroless is another option.
I submitted a patch to darkhttpd so folks can build the image themselves, but you can also download the images here. https://hub.docker.com/r/mileselam/darkhttpd/tags
https://zwischenzugs.com/2018/05/22/a-docker-image-in-less-t...
TL;DR can you get an image to run for test purposes that can fit in a screenful of base64?
Would anyone use this in production? I doubt so. You want a reliable battle-tested solution. Nginx can be compiled to 500kb without OpenSSL; if you need https then it's just a few megabytes, I find it acceptable for non-embedded solutions like containers.