14

I have a Nix package I'd like to bundle up into a docker container.

Specifically, I want to use Nix as a more expressive alternative to a Dockerfile to have faster (non-linear) image builds.

I've found documentation on dockerTools.buildImage but I'd like to have a minimal working example, and I'd also like to know what ends up being in the docker container.

nh2
  • 24,526
  • 11
  • 79
  • 128

1 Answers1

20

The following example packages (using contents =) the pkgs.nginx nixpkgs package into a docker container:

docker load --input $(nix-build -E 'with import <nixpkgs> {}; pkgs.dockerTools.buildImage { name = "nix-htop"; contents = pkgs.htop; config = { Cmd = [ "/bin/htop" ]; }; }')

You can then run it with

docker run -it nix-htop

The contents of the container are pretty minimal, a single Docker layer:

docker save nix-htop | tar x --to-stdout --wildcards '*/layer.tar' | tar t --exclude="*/*/*/*"
./
./bin/
./bin/htop
./share/
./share/applications/
./share/man/
./share/pixmaps/
nix/
nix/store/
nix/store/gi5vvbjawzw1bakiksazbd50bvfmpmmc-ncurses-6.0/
nix/store/pa5nkrpd5hg5qp1dc4gmbd2vdhn1y3x2-htop-2.0.2/
nix/store/vn6fkjnfps37wa82ri4mwszwvnnan6sk-glibc-2.25/

Only htop and its dependencies (glibc, ncurses), 26 MB on my case.

nh2
  • 24,526
  • 11
  • 79
  • 128
  • 1
    On macOS, this builds a docker image container macOs software, i.e. it is not runnable as a docker container. – jmg Aug 01 '18 at 21:58
  • 1
    @jmg: I only tried it on Linux and am not too surprised it doesn't work on OSX, but I'm not sure what "this builds a docker image container macOs software" means precisely. – nh2 Aug 06 '18 at 11:48
  • 1
    I meant, it contains software built for macOS, not for linux. – jmg Aug 07 '18 at 05:49
  • @jmg [Here's](https://unix.stackexchange.com/a/652402/79812) an answer on how to do it on macOS. The gist is that you give a `system` argument to nixpkgs: `import { system = "x86_64-linux"; }`. You also need a remote builder that runs linux, for example [linuxkit-nix](https://github.com/nix-community/linuxkit-nix) – Hjulle Jun 03 '21 at 04:27
  • `docker run -it nix-htop` doesn't work (presumably because it's not tagged "latest"), but `docker run -it nix-htop:HASH` does. – l0b0 Sep 16 '21 at 03:27
  • 3
    No need for a remote runner. Use the macOS pkgs for dockertools and the linux pkgs for image contents. I.e. : `nix-build -E '(import {}).dockerTools.buildImage { name = "nix-docker-test"; tag = "latest"; contents = [ (import { system = "x86_64-linux"; }).hello ]; }'` – Philippe Apr 13 '22 at 14:24