I’m looking to create a Docker image using nix which is based on a light image such as alpine and contains a static binary built using another nix expression. I’m using haskell.nix to create my static binary, and this results in a derivation which contains a /bin/server-prod (approx 5MB) and a /nix/store/... of >1GB.
Using the following nix expression, I’ve managed to create a docker image which contains the binary at bin/server-prod but it also contains the large nix store path, meaning the resultant image is very large.
the binary appears in the right place in the resultant docker image but all the dependency nix store paths are also present (the ones used to build the static binary).
I’ve tried fiddling with the paths in runCommand, but you have to put something in $out so each of these ends up more or less the same. The path being passed to contents must be a nix store path (or list of them), and it must be a directory.
You are copying the full derivation, so everything it depends on will also be copied. Copy selectively just the files you need.
Edit
Though, if that path does indeed only hold the binary and nothing else, do you perhaps compile with debugging enabled and/or aren’t stripping those out?
That might as well lead to references to other packages that then get pulled.
Have you tried building without docker and using nix why-depends (dunno if there is a non-flake equivalent)
If I use the code as above, I get the following output derivation:
$ ls result -a
Permissions Size User Date Modified Name
dr-xr-xr-x - root 1 Jan 1970 bin
$ ls result/bin -a
Permissions Size User Date Modified Name
.r-xr-xr-x 15M root 1 Jan 1970 server-prod
By using /bin within the cp command’s first argument, this becomes:
$ ls result -a
Permissions Size User Date Modified Name
.r-xr-xr-x 15M root 1 Jan 1970 server-prod
However, if I use nix-tree on the buildStaticExecutable derivation, I find that the dependencies are listed there:
Sorry, that wasn’t very helpful of me. I’ve produced a copy of my repo and just stripped out the business code, leaving all the nix files which produce the static executable and docker image from it. Running the commands in the README results in a ~1.15GB docker image containing the binary and the superfluous nix store paths.
Here’s a link to the repo. I really do appreciate you taking the time to help me with this.