1# pkgs.mkBinaryCache {#sec-pkgs-binary-cache}
2
3`pkgs.mkBinaryCache` is a function for creating Nix flat-file binary caches.
4Such a cache exists as a directory on disk, and can be used as a Nix substituter by passing `--substituter file:///path/to/cache` to Nix commands.
5
6Nix packages are most commonly shared between machines using [HTTP, SSH, or S3](https://nixos.org/manual/nix/stable/package-management/sharing-packages.html), but a flat-file binary cache can still be useful in some situations.
7For example, you can copy it directly to another machine, or make it available on a network file system.
8It can also be a convenient way to make some Nix packages available inside a container via bind-mounting.
9
10`mkBinaryCache` expects an argument with the `rootPaths` attribute.
11`rootPaths` must be a list of derivations.
12The transitive closure of these derivations' outputs will be copied into the cache.
13
14## Optional arguments {#sec-pkgs-binary-cache-arguments}
15
16`compression` (`"none"` or `"xz"` or `"zstd"`; _optional_)
17
18: The compression algorithm to use.
19
20 _Default value:_ `zstd`.
21
22::: {.note}
23This function is meant for advanced use cases.
24The more idiomatic way to work with flat-file binary caches is via the [nix-copy-closure](https://nixos.org/manual/nix/stable/command-ref/nix-copy-closure.html) command.
25You may also want to consider [dockerTools](#sec-pkgs-dockerTools) for your containerization needs.
26:::
27
28[]{#sec-pkgs-binary-cache-example}
29:::{.example #ex-mkbinarycache-copying-package-closure}
30
31# Copying a package and its closure to another machine with `mkBinaryCache`
32
33The following derivation will construct a flat-file binary cache containing the closure of `hello`.
34
35```nix
36{ mkBinaryCache, hello }:
37mkBinaryCache {
38 rootPaths = [ hello ];
39}
40```
41
42Build the cache on a machine.
43Note that the command still builds the exact nix package above, but adds some boilerplate to build it directly from an expression.
44
45```shellSession
46$ nix-build -E 'let pkgs = import <nixpkgs> {}; in pkgs.callPackage ({ mkBinaryCache, hello }: mkBinaryCache { rootPaths = [hello]; }) {}'
47/nix/store/azf7xay5xxdnia4h9fyjiv59wsjdxl0g-binary-cache
48```
49
50Copy the resulting directory to another machine, which we'll call `host2`:
51
52```shellSession
53$ scp result host2:/tmp/hello-cache
54```
55
56At this point, the cache can be used as a substituter when building derivations on `host2`:
57
58```shellSession
59$ nix-build -A hello '<nixpkgs>' \
60 --option require-sigs false \
61 --option trusted-substituters file:///tmp/hello-cache \
62 --option substituters file:///tmp/hello-cache
63/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1
64```
65
66:::