Building Nix derivations

Now that we’ve written our Hello, Nix!, we can build it with nix build, which produces a symlink to the result of the derivation at ./result.

Builder execution

First, we create a working directory under TMPDIR and cd to it. Then the setup script clears the environment as described in Nix builder script.

The following additional environment variables are also set:

  • NIX_BUILD_TOP, TMPDIR, TEMPDIR, TMP, and TEMP are all set to the working directory
  • PATH and HOME are set to nonsense values to prevent impurities
  • NIX_STORE is set to the Nix store path (usually /nix/store)
  • Environment variables for each element in outputs containing the store path for each output.

Existing matching output paths are removed and locked to prevent build conflicts. Combined stdout and stderr logs are written to /nix/var/log/nix.

Now the builder is run with args, and its return code determines the success of the build.

On a successful build, Nix cleans up the working directory, registers dependencies for the outputs, and alters permissions on the outputs to render them immutable.