9. Writing Your Own Derivations
From the builtins.derivation primitive up to stdenv.mkDerivation and the language builders
Back in the mental model we said every path under /nix/store is the
output of a derivation — a pure build recipe — and then we deliberately walked away
from the details. This is the article where we walk back. By the end you'll be able to take
a real program that isn't in nixpkgs, write the recipe that builds it, and understand
exactly why the resulting store path has the hash it does.
The word "derivation" gets used loosely, so let's pin it down with a concrete image. A derivation is a sealed work order handed to a factory. It names the finished product, lists every raw material by exact part number, specifies which machine does the assembly, and gives the assembly instructions — and then the factory is locked: no phone, no internet, no running out to the shop for a part that wasn't on the order. If the work order is identical, the product coming off the line is identical, every time, in every factory. That locked-room discipline is the whole reason Nix builds are reproducible, and almost everything in this article is a consequence of it.
Three layers, one primitive
There is really only one build primitive in Nix:
builtins.derivation. Everything you actually write —
stdenv.mkDerivation, buildGoModule,
fetchFromGitHub — is a convenience layer that lowers down
to that primitive. We'll start at the bottom so the layers above make sense, then spend
most of our time at the layer you'll use in practice.
The primitive: builtins.derivation
At the very bottom, a derivation is created by the builtin function derivation, which
takes a single attribute set. Exactly four attributes are required, and they are
gloriously low-level:
The four required attributes
derivation {
name = "hello-txt"; # the human-readable part of the store path
system = "x86_64-linux"; # which platform the build must run on
builder = "${pkgs.bash}/bin/bash"; # the executable Nix runs to do the build
args = [ "-c" "echo hello > $out" ]; # arguments passed to that builder
}
That's a complete, buildable derivation. Nix runs builder with
args, on a machine matching system, and whatever the builder
writes to the path in the $out environment variable becomes the output.
Two things are worth staring at. First, $out is not Nix syntax — it's a plain shell
environment variable that Nix sets before running the builder, holding the store path the
output is supposed to end up at. The builder's one job is to produce that path. Second,
${pkgs.bash} is Nix syntax: string interpolation splices in bash's store path, which
means bash becomes an input of this derivation. Any attribute you add beyond the four
required ones is simply exported into the builder's environment as a string, which is how
you pass configuration down to the build.
When Nix evaluates this expression, it does not run the build. Instead it writes a
.drv file into the store — a fully-resolved, JSON-ish description of the work order with
every input already pinned to its store path:
Evaluation produces a .drv, not an output
nix-repl> d = derivation { name = "hello-txt"; system = "x86_64-linux";
builder = "${pkgs.bash}/bin/bash";
args = [ "-c" "echo hi > $out" ]; }
nix-repl> d.drvPath
"/nix/store/2v9k…-hello-txt.drv"
nix-repl> d.outPath
"/nix/store/7bq3…-hello-txt"
The .drv is the build recipe as data; the outPath is where the
result will live once built. Both hashes are known before a single byte
is compiled, because they're computed from the recipe, not the result.
This split is the key to the whole system. Evaluation turns your Nix expressions into a
graph of .drv files (the "instantiation" step); a separate build step ("realisation")
actually runs those recipes to produce outputs. Because the output path is derived from the
recipe's inputs, Nix can look at a .drv, compute the output path, notice it already exists
locally or in a binary cache, and skip the build entirely. This is the input-addressed
model: the path is a fingerprint of the recipe.
You will almost never call builtins.derivation directly. It's too raw: you'd have to write
the unpack-configure-build-install dance by hand, in shell, for every package. But knowing
it's down there demystifies everything above it. stdenv.mkDerivation is a very elaborate
wrapper that, in the end, calls derivation.
stdenv.mkDerivation: the layer you'll actually use
stdenv is the standard environment: a bundle that includes a C compiler, make,
core Unix tools (coreutils, gnutar, gzip, patch, bash), and — most importantly — a
big shell library that implements a sensible default build process. stdenv.mkDerivation
takes an attribute set describing your package and fills in everything else.
Here is the shape of a real package. Note the attributes are declarative data; there's no
builder and no args, because mkDerivation supplies a generic builder that runs the
standard phases for you.
The canonical mkDerivation skeleton
{ stdenv, fetchFromGitHub }:
stdenv.mkDerivation {
pname = "myapp";
version = "1.4.2";
src = fetchFromGitHub {
owner = "someuser";
repo = "myapp";
rev = "v1.4.2";
hash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
};
# nativeBuildInputs / buildInputs go here (see below)
# phases are inferred; override only what you need
}
pname ("package name") and version combine into the store
path's readable suffix — myapp-1.4.2 — and into a name
attribute automatically. src is where the source comes from.
src and the hash dance
fetchFromGitHub is itself a derivation — a special one we'll dissect in the sandbox
section — and it needs a hash of the source it fetches. This is the part that trips up
everyone the first time, because you have to build the package once to learn the hash. The
standard workflow uses a deliberately wrong placeholder:
-
Put a fake hash in the
hashfield. The convention islib.fakeHash, which issha256-AAAA…AAA=(43 base-64As). Any obviously-wrong value works, butfakeHashis self-documenting. -
Build it. The fetch fails with a hash mismatch error that prints both
what you specified and — crucially — the real hash it computed:
error: hash mismatch in fixed-output derivation '/nix/store/…-source.drv': specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= got: sha256-Cvj0Zm2yZ0z8Ym6R0kZ1uJmR9wYb0mQ3o5pQ7xk1w2A= -
Copy the
got:value into thehashfield and rebuild. This time the fetch succeeds and its output is cached, so it never runs again.
Why the illustrative hashes here are placeholders
Every sha256-… value shown in this article is a stand-in. Real hashes are
the output of hashing real bytes — you get them from the build error above (or from
nix-prefetch-url), never by guessing. Don't copy the strings on this page
into a real package.
If you'd rather not run a failing build, nix-prefetch-url fetches a URL and prints its
hash directly (nix-prefetch-url --unpack <tarball-url> for archives), and there are
helpers like nix-prefetch-git and nix store prefetch-file for other sources. The
fake-hash-then-read-the-error trick is the most common because it needs no extra tooling and
works for every fetcher, including the language-specific ones we'll meet later.
The build phases
The generic builder runs a fixed sequence of phases. For a plain
mkDerivation, the default phase list is, in order:
The default phase order
unpackPhase → patchPhase → configurePhase → buildPhase
→ checkPhase → installPhase → fixupPhase
(There are also optional distPhase and installCheck phases, and
$prePhases/$postPhases hooks around the edges, but these seven
are the ones you'll reason about daily.)
Each phase has a sensible default, tuned for the ubiquitous autotools build (./configure && make && make install):
The elegance here is that for a well-behaved autotools project, you override nothing.
You supply src and the right build inputs, and the defaults carry it from tarball to
installed store path. You only reach for an override when a project deviates — say, it has no
./configure, or its Makefile has no install target.
Overriding a phase
To replace a phase, set the correspondingly-named attribute to a shell snippet. The one
rule you must respect: call the pre/post hooks yourself, or user-supplied
preInstall/postInstall code silently won't run.
A hand-written install phase
stdenv.mkDerivation {
pname = "tinytool";
version = "0.1";
src = ./.;
# This project's Makefile builds ./tinytool but has no install target,
# so we install by hand.
installPhase = ''
runHook preInstall
mkdir -p $out/bin
cp tinytool $out/bin/
runHook postInstall
'';
}
Everything inside ''…'' is ordinary shell that runs in the sandbox.
$out is the environment variable Nix set for you. Because there's no
configure script, the default configurePhase does nothing and needs no
override; the default buildPhase still runs make.
nativeBuildInputs vs buildInputs
This distinction confuses newcomers, but the rule is crisp once you frame it in terms of which machine needs the tool:
nativeBuildInputs — build-time
Tools that run during the build, on the machine doing the building:
compilers you invoke, code generators, pkg-config, cmake,
makeWrapper. They end up on PATH in the sandbox. They are
not needed once the package is installed.
buildInputs — runtime / target
Libraries the built program links against and needs when it runs, on
the machine that will execute it: openssl, zlib,
sqlite. Their headers and libs are made available to the compiler, and
references to them are retained so they follow the package as runtime dependencies.
The mnemonic: nativeBuildInputs = "things I run to build it," buildInputs = "things it
runs with." A build tool like cmake is nativeBuildInputs; a library it links, like
openssl, is buildInputs.
Why the split exists at all
On a normal native build, both lists just end up available and the distinction seems
academic. It becomes essential under cross-compilation, where "the
machine that builds" and "the machine that runs" are different architectures. In
nixpkgs' precise terminology nativeBuildInputs is depsBuildHost
and buildInputs is depsHostTarget — but you can carry the simple
mnemonic and be right the vast majority of the time. Getting it wrong won't fail a native
build, so it's easy to be sloppy; being correct is what lets your package cross-compile
later.
The build sandbox
Remember the locked factory. When Nix realises a derivation, it runs the builder inside a sandbox designed to make the build a pure function of its declared inputs:
- No network. The builder cannot open a socket to the internet. This is the single most
important constraint, and it's why
srcneeds a hash: fetching source is the one place a build legitimately needs the network, so fetchers are special fixed-output derivations — see below. - Only declared inputs are visible. The sandbox exposes just the store paths this
derivation depends on.
PATHcontains only thebin/directories of your build inputs plusstdenv's core tools. Your~/.cargo, the systemgcc,/usr/lib— none of it is there. - A private, empty build directory. The build runs in a fresh isolated
$TMPDIRthat's deleted afterward. Nothing leaks in from previous builds; nothing leaks out except$out. - A frozen, minimal environment. Most environment variables are cleared, the clock is
effectively fixed (many builds set
SOURCE_DATE_EPOCH), and the user/hostname are standardized, so incidental host details can't sneak into the output.
The fixed-output escape hatch
Fetchers like fetchFromGitHub and fetchurl are allowed
network access, but only because they are fixed-output derivations: you
declare the hash of their output up front. Nix relaxes the sandbox for them, then verifies
the fetched bytes hash to exactly what you promised. If a mirror serves different bytes,
the hash won't match and the build fails. This is the deal: network access in exchange for
a hash you committed to in advance — which is why the fake-hash dance from earlier exists.
The payoff is the reproducibility guarantee from the mental-model article, now with teeth:
because the sandbox forbids undeclared inputs, the set of things that can influence the
output is exactly the set captured in the .drv — and therefore in the output hash. Same
inputs, same output path, on any machine.
Worked example: packaging GNU hello end to end
Let's package something real from scratch. GNU hello is the canonical example: a tiny
program built with standard autotools. We'll fetch its release tarball with fetchurl,
build it with the default phases, and end up with a working /nix/store/…-hello-2.12.1.
-
Write the derivation with a fake hash. Because hello is a textbook
autotools project, we override no phases at all — the defaults do the whole job.
The{ stdenv, fetchurl }: stdenv.mkDerivation rec { pname = "hello"; version = "2.12.1"; src = fetchurl { url = "mirror://gnu/hello/hello-${version}.tar.gz"; hash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; # placeholder }; }recletssrcreuseversionin the URL. Themirror://gnuscheme lets Nix pick a working GNU mirror. -
Build once, read the real hash. The fetch fails with a hash mismatch;
copy the
got:value intohash. (Get the true value from your own build ornix-prefetch-url mirror://gnu/hello/hello-2.12.1.tar.gz— don't copy a placeholder from this page.) -
Rebuild. With a correct hash, the source is fetched and the phases run:
unpackPhaseuntarshello-2.12.1.tar.gzand enters it.configurePhasefinds./configureand runs it with--prefix=$out.buildPhaserunsmake, compilinghello.c.installPhaserunsmake install, placing the binary at$out/bin/helloand the man page under$out/share/man.fixupPhasestrips the binary and tidies the layout.
-
Run it. The output path now contains a real program:
$ nix-build hello.nix /nix/store/1a2b3c…-hello-2.12.1 $ ./result/bin/hello Hello, world!
Now a variant that needs a hand: a small C project on GitHub whose Makefile builds a
binary but has no install target. Two changes from the hello case — swap the fetcher for
fetchFromGitHub, and supply an installPhase:
A GitHub C project with a custom install
{ stdenv, fetchFromGitHub, zlib }:
stdenv.mkDerivation {
pname = "squish";
version = "0.3.0";
src = fetchFromGitHub {
owner = "example";
repo = "squish";
rev = "v0.3.0";
hash = "sha256-Cvj0Zm2yZ0z8Ym6R0kZ1uJmR9wYb0mQ3o5pQ7xk1w2A=";
};
buildInputs = [ zlib ]; # squish links against libz at runtime
installPhase = ''
runHook preInstall
install -Dm755 squish $out/bin/squish
runHook postInstall
'';
}
zlib goes in buildInputs because the finished binary links it;
the compiler here (cc from stdenv) is already present, so no
nativeBuildInputs is needed. The default buildPhase still runs
make; we only replace the missing install step.
For the practical, task-focused side — how to take a package like this and actually use it
in your running configuration, via an overlay or environment.systemPackages — see the next
article, packaging software that isn't in nixpkgs. This article is about the
recipe; that one is about wiring it into your system.
Language builders at a glance
Most software today is built by an ecosystem-specific tool — go build, cargo, pip,
npm — that wants to download dependencies from the network mid-build. That collides
head-on with the no-network sandbox. Nixpkgs solves it with language builders: wrappers
around mkDerivation that split the build into a network-allowed, fixed-output "fetch all
dependencies" derivation (guarded by a hash, exactly like src) and a pure "compile" step.
The tell is the extra hash each one wants:
You obtain these extra hashes the same fake-hash way: set them to lib.fakeHash, build, and
read the got: line. Choosing between them is easy — pick the builder that matches the
project's ecosystem. A Go program? buildGoModule. A Rust CLI? buildRustPackage. Each still
supports the phase overrides, nativeBuildInputs, and buildInputs you already know, because
each is mkDerivation underneath.
Fixups: making binaries behave in the store
The fixupPhase earns its own section because two of its tools solve problems unique to a
world where nothing lives in /usr.
Wrapping programs
A program often needs to find other programs or data at runtime — a helper binary on
PATH, a config directory, an environment variable. In the store there's no global PATH to
rely on, so you wrap the executable in a tiny launcher that sets things up first.
makeWrapper (add it to nativeBuildInputs) provides wrapProgram:
wrapProgram in a post-install fixup
nativeBuildInputs = [ makeWrapper ];
postFixup = ''
wrapProgram $out/bin/myapp \
--prefix PATH : ${lib.makeBinPath [ ffmpeg imagemagick ]} \
--set MYAPP_DATA $out/share/myapp
'';
This renames the real binary and drops a wrapper script in its place that prepends
ffmpeg and imagemagick to PATH and exports a data
path, then execs the original. The dependencies are now baked in by store
path — they'll always be found, and they're correctly recorded as runtime dependencies.
Patching prebuilt binaries with patchelf
Sometimes you can't build from source — you have a vendor's prebuilt Linux binary. It won't
run as-is, because a normal ELF executable hard-codes an interpreter path like
/lib64/ld-linux-x86-64.so.2 and looks for libraries in /usr/lib — neither of which
exists on NixOS. patchelf rewrites those baked-in paths to point into the store:
Relocating a prebuilt binary
nativeBuildInputs = [ autoPatchelfHook ];
buildInputs = [ stdenv.cc.cc.lib zlib ]; # libs the binary needs
# autoPatchelfHook scans the binary, finds its needed libraries among
# buildInputs, and rewrites the interpreter + RPATH automatically.
autoPatchelfHook automates the common case; under the hood it runs
patchelf --set-interpreter … and --set-rpath … with store paths.
You list the libraries the binary needs in buildInputs and the hook finds and
wires them.
Why /usr is poison
Both fixups exist to enforce one rule: a store path may only reference other store paths.
If your build wrote /usr/bin/python or /lib/x86_64-linux-gnu/libssl.so into a script or
binary, three things break at once. That path isn't in the sandbox, so the reference isn't a
declared dependency and won't be captured in the hash; it won't be copied to another machine
or a binary cache; and on a fresh NixOS box /usr is nearly empty, so it simply won't be
there. Referencing /usr is impure precisely because it's an input the derivation never
declared — the exact thing the sandbox is built to prevent. Every reference must be a store
path, so that the closure of dependencies is complete and the whole thing is relocatable.
Try it: step through a build
A derivation is easiest to grasp in motion: declared inputs feed a hash, the phases transform the source, and out the end comes a store path whose name is a fingerprint of everything that went in. Step through it below.
The recipe and its input-addressed output
Step through the phases
Key Takeaways
- One primitive underneath:
builtins.derivationtakesname,system,builder, andargs. Evaluating it writes a.drvrecipe and computes an input-addressed output path before any build runs. Everything higher lowers to this. stdenv.mkDerivationis the practical layer: give itpname,version, andsrc, and its generic builder runs the standard phases.$outis a plain shell variable holding the target store path.- Getting a source hash: use
lib.fakeHash, build, and copy the real value from thegot:line of the mismatch error (or usenix-prefetch-url). - Phase order: unpack → patch → configure → build → check → install → fixup, with autotools defaults. Override a phase by setting its attribute — and call
runHook pre/postX. nativeBuildInputsvsbuildInputs: tools you run to build it vs libraries it runs with. It only matters for real under cross-compilation, but get it right anyway.- The sandbox makes purity real: no network, only declared inputs on
PATH, isolated$TMPDIR. Fetchers get network access only as fixed-output derivations verified against a promised hash. - Language builders (buildGoModule/vendorHash, buildRustPackage/cargoHash, buildPythonApplication, buildNpmPackage) split dependency-fetching into a hashed step so the compile stays pure.
- Fixups keep the store pure:
wrapProgrambakes in runtime deps by store path,patchelf/autoPatchelfHookrelocate prebuilt binaries, and nothing may reference/usr— every reference must be a store path.
You can now read and write a derivation from the primitive on up: what a .drv is, why the
output path is a hash of the inputs, how the sandbox enforces purity, and how the phases turn
source into an installed package. Next we make it practical — taking a program that isn't in
nixpkgs and wiring your own package into a running configuration.