如何使用nix构建docker容器?

nh2*_*nh2 10 docker nix

我有一个Nix包,我想捆绑到一个docker容器中.

具体来说,我想使用Nix作为更具表现力的替代方案,Dockerfile以获得更快(非线性)的图像构建.

我已经找到了文档,dockerTools.buildImage但我想有一个最小的工作示例,我也想知道最终存在于docker容器中的内容.

nh2*_*nh2 16

以下示例contents =pkgs.nginxnixpkgs包打包(使用)到docker容器中:

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

然后你可以运行它

docker run -it nix-htop
Run Code Online (Sandbox Code Playgroud)

容器的内容非常小,只有一个Docker层:

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/
Run Code Online (Sandbox Code Playgroud)

只有htop及其依赖项(glibc,ncurses),在我的情况下为26 MB.

  • 不需要远程跑步者。使用 macOS pkgs 作为 dockertools,使用 linux pkgs 作为镜像内容。即: `nix-build -E '(import &lt;nixpkgs&gt; {}).dockerTools.buildImage { name = "nix-docker-test"; 标签=“最新”;内容 = [ (import &lt;nixpkgs&gt; { system = "x86_64-linux"; }).hello ]; }'` (3认同)