Build nix cache/nar inside derivation


I can build a local cache with the nars of a derivation from the command line like this:

nix --experimental-features nix-command copy --offline --to file:///tmp/mycache /nix/store/2g3jazymqbjw9c390c3b7vw8xq3r8iny-hello-2.12.1

I tried to do that from a derivation like this:

    hello-cache = nixpkgs.legacyPackages.x86_64-linux.stdenv.mkDerivation {
      name = "hello-cache";
      unpackPhase = "true";
      buildInputs = [nixpkgs.legacyPackages.x86_64-linux.nix];
      installPhase = ''
        mkdir -p $out
        export NIX_STATE_DIR=$(pwd)
        export NIX_LOG_DIR=$(pwd)
        export NIX_DATA_DIR=$(pwd)
        nix --experimental-features nix-command --no-sandbox --offline --no-substitute copy --to file://$out ${nixpkgs.legacyPackages.x86_64-linux.hello}

but it fails with this error (I tried with nix 2.15 and 2.16 in the derivation):

       > error: path '/nix/store/2g3jazymqbjw9c390c3b7vw8xq3r8iny-hello-2.12.1' is required, but there is no substituter that can build it

Is there a way to achieve this?

My use case would be to create a self-extracting container where /nix is a volume, the image does not contain /nix, and the container can re-build its /nix dependencies from the cache in the image.

There’s a nixpkgs function for this:

    hello-cache = nixpkgs.legacyPackages.x86_64-linux.mkBinaryCache {
      rootPaths = [ nixpkgs.legacyPackages.x86_64-linux.hello ];

Ah perfect thank you! I only looked into the built-ins and didn’t see anything related to the caching system there.