10. Packaging Software That Isn't in Nixpkgs
Write a local package and wire it into your NixOS configuration
Nixpkgs is one of the largest software collections in existence — well over a
hundred thousand packages, more than any other Linux distribution ships. So the
first time you go looking for a tool and it simply isn't there, it's a little
disorienting. You nix search, you check search.nixos.org,
and you get nothing — or worse, you find it pinned to a version that's two years
stale. A niche CLI someone published last month, an in-house tool your team wrote,
a fast-moving project whose latest release fixes the exact bug that's biting you:
these gaps are normal, and they're not a dead end.
On a traditional distro your options here are grim: curl | sh an install script,
drop a binary into /usr/local/bin, and quietly reintroduce all the drift NixOS
exists to eliminate. On NixOS you do the reproducible thing instead — you write a
small package for the tool and add it to your configuration exactly like any package
that did ship in nixpkgs. This article is the practical, hands-on sequel to
Packaging & Derivations: that article explained how
derivations work from first principles; here we take a real program that isn't
packaged and get it onto your running system, flakes-first.
When the package just isn't there
Before you write anything, it's worth knowing that "package it yourself" is the third rung on a ladder, and the first two are often enough. From least to most effort:
1. Run it in a dev shell
If you only need the tool for one project, don't touch the system at all. A
nix develop shell (or an FHS environment for stubborn binaries)
gives you the program on PATH just inside that project. This is
the subject of the next article, and it's the right
answer for anything project-scoped.
2. Override an existing package
If the tool is in nixpkgs but the version, patch set, or build flags
are wrong, you rarely need a rewrite. .override and
.overrideAttrs let you tweak an existing derivation — a newer
src, an extra patch, a different feature flag. See
Overlays & Overrides.
The third rung — writing a derivation from scratch — is for when nixpkgs has nothing to start from: a brand-new project, an internal tool, an upstream that never made it into the repo. That's what the rest of this article does. It's less work than it sounds, because nixpkgs hands you most of the machinery; you're mostly filling in a form.
The goal
Turn an unpackaged program into a first-class citizen of your config: something
you can put in environment.systemPackages, build with
nix build, and reach as pkgs.mytool — pinned by your
flake.lock like everything else, so it rebuilds identically on
every machine.
Anatomy of a minimal derivation
Here's the shortest useful reminder of what a derivation looks like; for the full
tour of build phases and stdenv, go back to
Packaging & Derivations. The skeleton for almost any
package is a call to stdenv.mkDerivation (or one of its language-specific
cousins, coming up next) with three things it can't do without: a name, a version,
and a source.
The irreducible core
{ stdenv, fetchFromGitHub }:
stdenv.mkDerivation {
pname = "mytool";
version = "1.4.0";
src = fetchFromGitHub {
owner = "someuser";
repo = "mytool";
rev = "v1.4.0";
hash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
};
}
pname and version combine into the store path's
human-readable name (mytool-1.4.0). src is where the
code comes from — fetchFromGitHub here, or fetchurl
for a release tarball, or fetchgit for an arbitrary repo.
The one field that trips everyone up is hash. Nix insists that anything fetched
from the network be content-addressed: you declare, up front, the hash of what
you expect to download, and Nix refuses the result if it doesn't match. This is
what lets fetching happen despite the build sandbox having no network access — a
fixed-output derivation is trusted precisely because its output is pinned to a
known hash. But how do you know the hash before you've downloaded anything?
You don't, and you don't have to guess. The idiom is to write a fake hash, attempt the build, and let Nix tell you the real one:
The fakeHash trick
src = fetchFromGitHub {
owner = "someuser";
repo = "mytool";
rev = "v1.4.0";
hash = lib.fakeHash; # a deliberately wrong placeholder
};
Build it, and Nix fetches the source, computes the real hash, sees it doesn't match your placeholder, and aborts with an error that includes the line you actually want:
error: hash mismatch in fixed-output derivation '/nix/store/...-source.drv':
specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
got: sha256-Q0f4l7iP2m1n3o5p7r9t1v3x5z7B9D1F3H5J7L9N1P3=
Copy the got: value into hash and rebuild. (The old
lib.fakeSha256 works too; lib.fakeHash is the modern,
algorithm-agnostic spelling. You may also see people use
nix-prefetch-url or nurl to fetch a hash ahead of
time, but the fakeHash loop needs no extra tools and works everywhere.)
Picking the right builder
stdenv.mkDerivation is the general-purpose base: you hand it a source and it runs
the classic ./configure && make && make install dance, which is perfect for C/C++
projects using autotools or plain Makefiles. But if your program is written in a
language with its own dependency manager, reaching for mkDerivation directly means
re-implementing that whole ecosystem's fetch-and-build logic by hand. Don't.
Nixpkgs ships language-specific builders that do it for you:
Match the builder to the language
stdenv.mkDerivation— C/C++, autotools, plain Makefiles, or anything bespoke.buildGoModule— Go modules. Vendors dependencies; needs avendorHash.rustPlatform.buildRustPackage— Rust/Cargo. Fetches crates; needs acargoHash.buildNpmPackage— Node. Fetches the npm dependency tree; needs annpmDepsHash.buildPythonApplication— Python end-user apps (as opposed to importable libraries, which usebuildPythonPackage).
Notice the recurring theme: each of these builders needs a second hash beyond the
source hash — vendorHash, cargoHash, npmDepsHash. That's because fetching the
project's dependency tree is itself a networked, fixed-output step, and it gets its
own content-addressed hash, obtained with the exact same fakeHash loop.
A worked example: a small Go CLI
Let's package a real-shaped example end to end. Say there's a little command-line
tool called portping on GitHub — it checks whether a TCP port is open — written in
Go, and it isn't in nixpkgs. Here is the complete derivation:
pkgs/portping/default.nix
{ lib, buildGoModule, fetchFromGitHub }:
buildGoModule rec {
pname = "portping";
version = "0.3.1";
src = fetchFromGitHub {
owner = "acme";
repo = "portping";
rev = "v${version}";
hash = "sha256-Q0f4l7iP2m1n3o5p7r9t1v3x5z7B9D1F3H5J7L9N1P3=";
};
vendorHash = "sha256-8oIWlZeErOcj0h9zM2kFpVnBtLdXqYs4uUgAw6cRe1E=";
meta = {
description = "Tiny TCP port reachability checker";
homepage = "https://github.com/acme/portping";
license = lib.licenses.mit;
mainProgram = "portping";
};
}
Walk it top to bottom:
-
The function head
{ lib, buildGoModule, fetchFromGitHub }:— the file is a function whose arguments are the pieces of nixpkgs it needs. It doesn't fetch them itself; something will inject them (that'scallPackage, next section). -
buildGoModule rec { ... }— the Go builder. Therecletsrevreuseversionviav${version}, so bumping the version updates the tag in one place. -
src+hash— obtained with the fakeHash loop from the last section. -
vendorHash— the hash of the fetched Go module dependencies. Get it the same way: set it tolib.fakeHash, build, and copy thegot:value. (If a project vendors its dependencies into the repo already, you'd setvendorHash = nullinstead.) -
meta— optional but good manners.license,homepage,description, and especiallymainProgram(which tellsnix runwhich binary to launch when the package name and binary name differ).
That's it — no buildPhase, no installPhase. buildGoModule knows how to
go build the module and install the resulting binaries into $out/bin. A Rust
equivalent is almost identical in shape, swapping buildGoModule/vendorHash for
rustPlatform.buildRustPackage/cargoHash:
The Rust shape, for comparison
{ lib, rustPlatform, fetchFromGitHub }:
rustPlatform.buildRustPackage rec {
pname = "portping";
version = "0.3.1";
src = fetchFromGitHub {
owner = "acme";
repo = "portping";
rev = "v${version}";
hash = "sha256-Q0f4l7iP2m1n3o5p7r9t1v3x5z7B9D1F3H5J7L9N1P3=";
};
cargoHash = "sha256-r8Kx2vBnMq4Ld6Ns8Pt0Rw2Yz4Ac6Eg8Ik0Mo2Qs4U=";
}
Keeping the package in your repo
A .nix file that's a function isn't yet a package — nobody has supplied its
arguments. The clean way to supply them is callPackage, and understanding it is
the key idea of this article.
Put the derivation in your config repo at a predictable path — one directory per package is the nixpkgs convention:
~/nixos-config/
├── flake.nix
├── flake.lock
├── configuration.nix
└── pkgs/
└── portping/
└── default.nix
Now call it:
pkgs.callPackage ./pkgs/portping { }
What callPackage actually does
callPackage f args looks at the names of the arguments
the function f declares — lib,
buildGoModule, fetchFromGitHub — and for each one that
exists in the package set, it passes that package in automatically. Anything you
put in args (the { }) overrides the auto-supplied
value. So pkgs.callPackage ./pkgs/portping { } means: "read
portping's argument list, fill every argument from
pkgs, and I have nothing to override."
Concretely, callPackage is essentially this line from nixpkgs, using function
introspection to intersect the function's parameters with the package set:
callPackage, demystified
callPackage = f: args:
f ((builtins.intersectAttrs (builtins.functionArgs f) pkgs) // args);
functionArgs f reads the argument names off the function;
intersectAttrs keeps only the entries of pkgs whose
names match; // args layers your explicit overrides on top. The
payoff is that a package's dependencies are declared once, by name, in the
function head — you never repeat the wiring at the call site. Because
pkgs is your pinned package set, every dependency is the
exact version your flake.lock selected.
This is also why you sometimes need to override: if portping needed a specific
older library, you'd write pkgs.callPackage ./pkgs/portping { somelib = pkgs.somelib_1; },
and only that one argument changes.
Using it in your configuration
Now the practical question: how does callPackage ./pkgs/portping { } become a
program on your PATH? Flakes-first, there are three routes, and the diagram shows
how the single local file flows into all of them.
(a) Expose it as a flake output
Adding the package to your flake's packages output makes it buildable on its own
with nix build .#portping and shareable with anyone who references your flake.
Inside outputs, alongside your nixosConfigurations:
flake.nix (excerpt)
outputs = { self, nixpkgs, ... }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
in {
packages.${system}.portping = pkgs.callPackage ./pkgs/portping { };
nixosConfigurations.bluewhale = nixpkgs.lib.nixosSystem {
# ...as before...
};
};
Build and test it in isolation, without rebuilding your whole system:
nix build .#portping
./result/bin/portping --help
result is a symlink to the package's store path — a quick way to confirm the
derivation is correct before you commit to a system rebuild.
(b) Add it directly to systemPackages
The most direct route to "installed on this machine." In configuration.nix,
callPackage the file right where you list packages:
configuration.nix (excerpt)
environment.systemPackages = with pkgs; [
git
vim
(callPackage ../pkgs/portping { })
];
The parentheses matter: without them the list would try to include
callPackage, ../pkgs/portping, and { } as
three separate elements. Adjust the relative path to point at the file from
wherever configuration.nix lives.
(c) Add it via an overlay so it's pkgs.portping everywhere
If you want the tool to behave like any nixpkgs package — reachable as
pkgs.portping from every module and every callPackage in your config — add it
with an overlay. An overlay extends the package set itself. This is the most
composable option and the one to reach for once a package is used in more than one
place; the mechanics of overlays get their own treatment in
Overlays & Overrides, but the shape is:
An overlay that adds portping to pkgs
nixpkgs.overlays = [
(final: prev: {
portping = final.callPackage ./pkgs/portping { };
})
];
After this, pkgs.portping exists throughout your configuration, so
environment.systemPackages = with pkgs; [ portping ]; just works —
no callPackage at the use site. Using final.callPackage
means the package is built against the fully-overlaid package set, so it sees any
other overrides you've applied.
Rebuild and confirm
Whichever consumption route you chose (b or c rebuilds the system; a is
independent), remember the flake git gotcha — Nix only sees git-tracked files,
so a brand-new pkgs/portping/default.nix is invisible until you stage it:
git add pkgs/portping/default.nix
sudo nixos-rebuild switch --flake .#bluewhale
which portping
portping --help
If which portping prints a path under /nix/store/...-portping-0.3.1/bin/portping,
you're done — the tool is on PATH and pinned by your lock file like everything else.
Overriding vs. packaging from scratch
Everything above assumes nixpkgs had nothing for you. Often it has almost what you want, and then writing a fresh derivation is wasted effort. The rule of thumb:
Override when a base exists
The package is in nixpkgs but you need a newer src, an extra
patch, or a different build flag. Use .overrideAttrs (to change
the derivation's own attributes — version, src,
patches, phases) or .override (to change the
arguments a package was called with — toggling optional features).
You inherit all the upstream packaging work.
Package from scratch when there's no base
Nothing in nixpkgs builds this program — a new project, an internal tool, an upstream that was never packaged. There's no derivation to override, so you write one, exactly as in this article.
The dividing line is simply whether an existing derivation is close enough to bend
into shape. When it is, override; the full mechanics of .override,
.overrideAttrs, and overlays live in
Overlays & Overrides.
Gotchas & troubleshooting
Packaging goes wrong in a handful of predictable ways. When it does, the Troubleshooting article goes deeper; here are the ones specific to writing a package:
Two different hashes to mind
The source hash (hash in fetchFromGitHub)
and the dependency hash (vendorHash /
cargoHash / npmDepsHash) are separate fixed-output
hashes. A mismatch error names which derivation failed — a
-source.drv means the src hash; a
-vendor or -cargo-deps derivation means the dependency
hash. Fix the one it's complaining about with the fakeHash loop. And remember:
when you bump version, both hashes usually change, because
both the source and the resolved dependency tree moved.
buildInputs vs. nativeBuildInputs
A near-universal beginner bug. nativeBuildInputs
are tools needed at build time, on the build machine — compilers,
pkg-config, code generators, makeWrapper.
buildInputs are libraries the built program links
against and needs at runtime, on the target. Get them backwards and it
usually still works on your desktop (build and host are the same machine) but
breaks the moment you cross-compile. Rule: if it runs during the build, it's
native; if the program depends on it afterward, it's a
buildInput.
The build sandbox has no network
"Why can't my build just go get / cargo fetch /
npm install?" Because ordinary builds run in a sandbox with
no network access — that's what makes them reproducible. The only way
to fetch is a fixed-output derivation, whose declared hash lets
Nix trust the download. That's exactly why src needs a
hash and why the dependency step needs a vendorHash:
each is a fixed-output fetch. If a build tries to reach the network from a normal
phase, it'll fail with a connection error, and the fix is to route that fetch
through a proper fetcher instead.
Runtime dependencies not found
Your package builds, but at runtime it can't find a helper binary or shells out
to something not on its PATH. Wrap it: add makeWrapper
to nativeBuildInputs and, in a postFixup, use
wrapProgram $out/bin/portping --prefix PATH : ${lib.makeBinPath [ pkgs.iproute2 ]}
to bake the needed tools into the wrapper's PATH. For a
prebuilt binary (a release you didn't compile from source), the
dynamic loader path is wrong for NixOS — reach for autoPatchelfHook
(in nativeBuildInputs), which rewrites the ELF interpreter and
RPATH to point at store paths. These patchelf/wrapper
steps are the usual bridge between "upstream assumed FHS" and "NixOS has no
/usr/lib."
Purity is the recurring lesson
Almost every packaging failure is the derivation reaching for something outside
its declared inputs — the network mid-build, a library at
/usr/lib, a tool that happens to be on your login shell's
PATH but not the build's. The fix is always the same: declare the
input explicitly (a fetcher, a buildInput, a wrapper) so the build
is self-contained. If it builds in the sandbox, it builds on every machine.
Where to go next
You can now take any unpackaged program and make it a proper part of your system. Three natural directions from here:
- Contribute it upstream. If the tool is generally useful, a local derivation is
most of the work of a real nixpkgs package. Add a
metablock, follow the contributing guide, and open a PR — then everyone gets it, and you get to delete your local copy. - Scope it to a project instead of the system. Not everything belongs in
systemPackages. For per-project tooling, put the package in a dev shell so it's available only inside that project'snix developenvironment — the very next article. - Share it across your machines. Because the package is a flake output, any other
flake can pull it in as an input and use
yourflake.packages.${system}.portping. Your config repo becomes a little package registry for the tools you care about.
Key Takeaways
- Packaging is the third rung: try a dev shell or an override first; write a derivation from scratch only when nixpkgs has nothing to start from.
- A minimal derivation is pname + version + src, and you get the source
hashwith the fakeHash loop: setlib.fakeHash, build, copy thegot:value. - Match the builder to the language:
stdenv.mkDerivationfor C/Make,buildGoModule(vendorHash),rustPlatform.buildRustPackage(cargoHash),buildNpmPackage,buildPythonApplication. Each dependency hash uses the same fakeHash loop. - Keep it in your repo at
pkgs/mytool/default.nixand instantiate it withpkgs.callPackage ./pkgs/mytool { }, which auto-fills the function's arguments by name from the package set. - Three ways to consume it, flakes-first: a flake
packages.<system>output (buildable + shareable), directly inenvironment.systemPackages, or via an overlay so it'spkgs.mytooleverywhere. - Gotchas: two separate hashes (source vs. dependencies),
nativeBuildInputs(build-time) vs.buildInputs(runtime), no network outside fixed-output fetches, andwrapProgram/autoPatchelfHookfor runtime deps and prebuilt binaries.
Packaging a single program teaches the whole shape of Nix: declare your inputs, build in a sandbox, get a pinned store path. But you don't always want a tool installed system-wide — often you want it only inside one project, alongside a specific toolchain, for anyone who clones the repo. That's what dev shells are for, and they're next.