3. Your First Flake-Based Configuration
Build a real, minimal NixOS system from two small files
You've got the mental model — a system is a description, that description builds immutable store paths, and generations let you move between whole systems at will. You've got just enough of the Nix language to read an attribute set without flinching. Now it's time to make something real. By the end of this article you'll have written two small files, run one command, and watched them turn into a running Linux system you can roll back at will.
We're going to build the smallest configuration that's still a complete NixOS system: it boots, it has a hostname, it has a user you can log in as, and it ships a couple of packages. Nothing more. Everything else in this series — services, modules, overlays, your own packages — hangs off this same skeleton, so it's worth getting the shape exactly right.
Where we're headed
A flake-based NixOS config is just a directory in git with two files:
flake.nix (which declares where your inputs come from and
what systems this repo can build) and configuration.nix (which
describes the actual machine). A third file, flake.lock, is written for
you and pins every input to an exact revision. You build the whole thing with
sudo nixos-rebuild switch --flake .#hostname.
Step 0: turn flakes on
Flakes are still, officially, an experimental feature of Nix — they've been the de-facto standard for years, but they remain gated behind a flag. There are two ways to switch them on, and you'll usually end up using both.
The permanent, declarative way is a single line in your NixOS configuration. This is the right home for it once you're up and running, because it means "flakes are enabled" is itself part of your reproducible system description:
The declarative switch (goes in configuration.nix)
nix.settings.experimental-features = [ "nix-command" "flakes" ];
Two features, not one. flakes enables the flake machinery itself;
nix-command enables the newer unified nix CLI (the
nix build, nix flake show, nix develop family
of subcommands) that flakes are meant to be driven with. You want both.
But there's a bootstrapping problem: to build the configuration that enables flakes, you may need flakes enabled already. The transitional escape hatch is to pass the feature on the command line for a single invocation:
nixos-rebuild switch --experimental-features "nix-command flakes" --flake .#hostname
Or, if you'd rather not type that every time before the setting takes effect, enable it
for your user by creating ~/.config/nix/nix.conf (or system-wide at /etc/nix/nix.conf)
with one line:
experimental-features = nix-command flakes
Once your first flake-based generation is live and the declarative
nix.settings.experimental-features line is baked in, you can delete the transitional
nix.conf entry — the system now enables flakes for itself.
The two files, and how they relate
A flake config lives in a directory. Let's call ours ~/nixos-config. Inside it, two
files do all the work, and one more gets generated. Here's the whole relationship before
we write a line of it:
The mental split is worth internalizing now, because it never changes: flake.nix is
about provenance and packaging — where code comes from, and what buildable things this
repo exposes. configuration.nix is about the machine — what the system actually
looks like. Beginners often try to cram machine settings into flake.nix; resist that.
The flake's job is to hand your configuration.nix to the NixOS module system with the
right nixpkgs attached.
Anatomy of flake.nix
Every flake is a single attribute set with a few well-known keys. Here's a complete, minimal one — read it top to bottom, then we'll take it apart:
flake.nix
{
description = "My first NixOS flake";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
};
outputs = { self, nixpkgs, ... }: {
nixosConfigurations.bluewhale = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [ ./configuration.nix ];
};
};
}
That's the entire file. Three keys carry all the meaning.
description is exactly what it sounds like — a one-line human string. It shows up in
nix flake show and nix flake metadata. It has no functional effect; it's documentation.
inputs declares your dependencies. Each input is a named reference to another
flake or repository. Here we have exactly one: nixpkgs, the enormous package collection
and module set that a NixOS system is built from. The value is a flake reference URL:
Reading a flake reference
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
└─┬──┘ └────┬────┘ └───┬────┘
fetcher owner/repo branch or ref
github:NixOS/nixpkgs/nixos-24.05 means "the nixos-24.05
branch of the NixOS/nixpkgs repository on GitHub." The
nixos-24.05 branch is the stable release channel — NixOS 24.05, codenamed
Uakari, released 31 May 2024. You could instead track
nixos-unstable for the rolling bleeding edge, or pin a raw commit hash for
maximum control. Pinning to a stable release branch is the sane default for a first
system.
Note what this reference does not say: it doesn't name a specific commit. It says "the
tip of the nixos-24.05 branch, whatever that is right now." That vagueness is fine,
because — as we'll see — Nix immediately resolves it to an exact commit and writes that
commit down in flake.lock. The URL says which stream to follow; the lock file records
exactly where in that stream you currently are.
outputs is the interesting one, and the place newcomers most often get confused.
Look at its shape again:
outputs = { self, nixpkgs, ... }: { nixosConfigurations. ... };
outputs is a function. Its argument is an attribute set, and — this is the key part
— its argument set is your inputs, already fetched and evaluated, plus one extra
member called self (a reference to this very flake). So the nixpkgs you destructure in
{ self, nixpkgs, ... } is not the URL string from above; it's the actual, downloaded
nixpkgs flake, with all of its library functions and packages ready to use. The ...
means "and any other inputs I didn't bother to name here." The function returns another
attribute set — the flake's actual outputs.
The one sentence to remember about outputs
outputs is a function from your resolved inputs to an
attribute set of things this flake produces. NixOS looks for one particular
output — nixosConfigurations — when you run nixos-rebuild.
nixosConfigurations: naming a buildable system
The single output we produce is nixosConfigurations.bluewhale. This is a well-known
output name that the tooling looks for: nixos-rebuild --flake .#bluewhale means "go
into this flake's nixosConfigurations and build the one called bluewhale." The name
after # is just an attribute key — conventionally your machine's hostname, but it's only
a label. A single flake can hold configurations for many machines side by side:
nixosConfigurations = {
bluewhale = nixpkgs.lib.nixosSystem { ... }; # your laptop
narwhal = nixpkgs.lib.nixosSystem { ... }; # a server
};
Each value is built by nixpkgs.lib.nixosSystem, a function nixpkgs provides specifically
for assembling a NixOS system. It takes an attribute set with two keys that matter to us
now:
system— the platform to build for, as a Nix double."x86_64-linux"for a 64-bit Intel/AMD PC;"aarch64-linux"for a 64-bit ARM machine like a Raspberry Pi 4.modules— a list of NixOS modules to combine into the final system. We give it one:./configuration.nix. As your config grows you add more paths to this list, and the module system merges them all together (that's the subject of the next article).
That relative path, ./configuration.nix, is where the flake hands off to the file that
actually describes your machine.
A minimal configuration.nix
This is a NixOS module: an attribute set of options that describe the system. If you
already have a working NixOS install, you have one of these at /etc/nixos/configuration.nix
that the installer generated. Here is a deliberately small one, written from scratch:
configuration.nix
{ config, pkgs, ... }:
{
imports = [ ./hardware-configuration.nix ];
# Enable flakes on the built system itself.
nix.settings.experimental-features = [ "nix-command" "flakes" ];
# Bootloader — systemd-boot on a UEFI machine.
boot.loader.systemd-boot.enable = true;
boot.loader.efi.canTouchEfiVariables = true;
# Identity + networking.
networking.hostName = "bluewhale";
networking.networkmanager.enable = true;
# A login user. Put yourself in "wheel" so you can use sudo.
users.users.jo = {
isNormalUser = true;
description = "Jo";
extraGroups = [ "wheel" "networkmanager" ];
initialPassword = "changeme";
};
# A couple of system-wide packages.
environment.systemPackages = with pkgs; [
git
vim
htop
];
# Do NOT casually change this. See below.
system.stateVersion = "24.05";
}
Let's walk the pieces, because every one of them earns its place.
-
The function head
{ config, pkgs, ... }:— a NixOS module is itself a function. The module system calls it withconfig(the fully merged configuration of the whole system) andpkgs(the package set from your pinned nixpkgs). You rarely needconfigin a first config, but it's conventional to accept it.pkgsis how you reach packages likepkgs.git. -
imports = [ ./hardware-configuration.nix ];— pulls in the machine-specific file the installer generated (disk layout, filesystems, detected kernel modules). On a real install this file already exists next to your config; you almost never edit it by hand. If you're following along on an existing NixOS machine, keep this line; on a fresh install, generate it withnixos-generate-config. -
The bootloader block —
systemd-bootis the simple choice for modern UEFI hardware. On older BIOS systems you'd configure GRUB instead. This is what puts the "pick a generation" menu in front of you at boot. -
Hostname and networking —
networking.hostNamenames the machine;networking.networkmanager.enable = true;gives you the usual NetworkManager stack for Wi-Fi and wired connections. -
The user —
isNormalUser = true;creates an ordinary login account with a home directory. Adding"wheel"toextraGroupsgrantssudo.initialPasswordsets a password for the first boot only; change it immediately withpasswd, and for a real machine preferhashedPasswordor SSH keys instead of a plaintext password in your config. -
environment.systemPackages— packages installed for the whole system, on everyone'sPATH. Thewith pkgs;prefix lets you writegitinstead ofpkgs.gitfor each entry. -
system.stateVersion = "24.05";— the single most misunderstood line in NixOS. It is not "which NixOS version I'm running." It records the release your machine was first installed with, so that stateful things (default database formats, data directories) keep behaving the way they did on day one, even as you upgrade nixpkgs underneath. Set it once, to the version you started on, and then leave it alone forever. Bumping it to chase your current nixpkgs can silently migrate stateful services and cause data loss.
stateVersion in one line
"What release did this machine first exist on?" — not "what am I running now." Pick it at install time and never touch it again. Upgrading your system is done by bumping the nixpkgs input, not this string.
flake.lock: the reproducibility payoff
Here's the file you never write by hand and should always commit. The first time you build
(or the first time you run nix flake lock), Nix takes each vague input reference —
"nixpkgs at the tip of nixos-24.05" — resolves it to the exact commit that's there
right now, and records it. A flake.lock entry for nixpkgs looks roughly like this:
flake.lock (excerpt — auto-generated)
"nixpkgs": {
"locked": {
"type": "github",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "63dacb46bf939521bdc93981b4cbb7ecb58427a0",
"narHash": "sha256-8oIWlZ...=",
"lastModified": 1717179513
},
"original": {
"type": "github",
"owner": "NixOS",
"repo": "nixpkgs",
"ref": "nixos-24.05"
}
}
Notice the two halves. original is the loose reference you wrote in
flake.nix (the branch). locked is what it resolved to: an
exact commit (rev) and a content hash (narHash) of the
fetched source. From now on, builds use the locked commit, not the moving
branch tip.
This is the whole reproducibility story, made concrete. Recall from the mental-model
article that a build is a pure function of its inputs — same inputs, same output store
path. The lock file is what freezes those inputs. Commit flake.nix and flake.lock
together, and anyone who checks out your repo — a colleague, a fresh server, future you
after a disk dies — resolves nixpkgs to the identical commit and rebuilds the
byte-for-byte same system. No "which channel were you on?" No hidden global state.
Channels (the old way)
A machine-global, mutable pointer updated with nix-channel --update.
Two machines with the "same" config could build differently depending on when each
last updated its channel. Nothing in your repo records the actual version used.
flake.lock (the flake way)
The exact nixpkgs commit lives in a file inside the repo. Check out the repo at any point in history and you get precisely the inputs that were in effect then. The version is data, versioned alongside your config.
Updating is now an explicit, visible act rather than ambient drift:
nix flake updatere-resolves all inputs to their latest matching revisions and rewritesflake.lock. This is how you deliberately pull in a newer nixpkgs. Because it only changes the lock file, the diff is reviewable, and if the new revision breaks something yougit checkoutthe oldflake.lockand rebuild — instant downgrade.nix flake update nixpkgsupdates just that one input, leaving others pinned.nix flake lockcreates or repairs the lock file without upgrading anything already pinned — it only fills in inputs that are missing an entry. Handy right after you add a new input.
Upgrading a flake system, in full
nix flake update (rewrites flake.lock with newer inputs) →
sudo nixos-rebuild switch --flake .#bluewhale (builds them) →
git commit the new lock file. That commit is a perfect record of the
upgrade, and reverting it reverts the upgrade.
Building and switching
With flake.nix, configuration.nix, and (on a real machine)
hardware-configuration.nix in ~/nixos-config, you build the system with one command
run from inside that directory:
sudo nixos-rebuild switch --flake .#bluewhale
Read the --flake .#bluewhale argument as two parts around the #. The . is the flake
to use — here, the current directory. bluewhale is which nixosConfigurations entry to
build. If you omit the name (--flake .), nixos-rebuild defaults to the configuration
matching the machine's current hostname, so many people just write --flake ..
The final subcommand — switch — is one of a small family, and knowing the difference
saves you from a bad night:
switch
Build the new generation, activate it right now, and make it the default at the next boot. The everyday command. Services restart, the new symlink flips, you're on the new system immediately.
boot
Build the new generation and make it the boot default, but don't activate it in the running system. You get the change on your next reboot. Good for kernel changes you'd rather apply cleanly on restart.
...and test
sudo nixos-rebuild test --flake .#bluewhale builds and activates the new
generation in the running system but does not add it to the boot menu. If it
misbehaves, just reboot and you're back on your previous default — the risky change was
never made permanent. It's the natural way to try something dicey. (There's also
build, which only builds, activating nothing, and build-vm,
which builds a throwaway virtual machine of your config so you can boot it in a window
without touching the host.)
Whichever you pick, remember the guarantee from the mental-model article: activation is
atomic. Nix builds everything off to the side first and only swaps the system
symlink at the very end. A build that fails halfway leaves your running machine completely
untouched, and every successful build is a new numbered generation sitting in the boot
menu, ready to roll back to.
The git gotcha that bites everyone once
Here is the single most common first-flake mistake, and it produces a baffling error message, so commit it to memory now:
Flakes only see files tracked by git
When your flake lives in a git repository, Nix copies only the files git knows
about into the store before evaluating. A file you've created but not yet
git added is invisible to the flake — as far as the build is
concerned, it does not exist.
Picture the classic sequence. You git init your config directory, you write
flake.nix, and you run the rebuild — and Nix complains that it can't find
configuration.nix, or that the path ./configuration.nix "does not exist," even though
you're staring right at it in your editor. The file is there on disk; it just isn't
tracked, so Nix's copy of the flake doesn't include it. The fix is simply:
git add flake.nix configuration.nix hardware-configuration.nix
sudo nixos-rebuild switch --flake .#bluewhale
Why it works this way (it's a feature)
This behavior is intentional: it makes flakes reproducible by construction. The flake
is defined entirely by its committed contents, so a stray scratch file or an
editor backup can't sneak into a build and make it non-reproducible. The price is that
git add becomes part of your workflow — any new file must be tracked
before it can affect the build. You don't have to commit, just
add (stage) it; but committing is the good habit, since that's what lets
you roll the config back too, not just the system.
Two commands to sanity-check your flake
Before or after you rebuild, two nix subcommands are worth knowing.
nix flake show prints the tree of outputs your flake exposes — a quick way to
confirm that nixosConfigurations.bluewhale is actually there and spelled the way you
think:
$ nix flake show
git+file:///home/jo/nixos-config
└───nixosConfigurations
└───bluewhale: NixOS configuration
nix flake check evaluates your flake and runs whatever checks it defines, verifying
that the outputs at least build their evaluation without errors. It's a good pre-commit
habit: if nix flake check is clean, your flake is structurally sound even before you
commit to a full nixos-rebuild. (On a minimal config it mostly confirms the flake
evaluates and the NixOS configuration is well-formed; as you add tests and packages it
does more.)
Both, like every flake command, only see git-tracked files — so if nix flake show
insists your configuration is empty right after you created it, that's the git gotcha
waving hello again.
Explore a flake config
Rather than build a real machine to see how these files fit together, try the pieces
below. Flip a few switches — change the hostname, add or remove a user, toggle a
package or an option — and watch flake.nix and
configuration.nix update in lockstep, with a summary of the system
generation they'd produce.
Resulting system
Key Takeaways
- Two files do the work:
flake.nixdeclares inputs and buildable outputs;configuration.nixdescribes the machine. The flake hands your config module tonixpkgs.lib.nixosSystem. - Enable flakes explicitly:
nix.settings.experimental-features = [ "nix-command" "flakes" ];in the config, plus a transitional--experimental-featuresflag or~/.config/nix/nix.confline to bootstrap. outputsis a function from your resolved inputs ({ self, nixpkgs, ... }) to an attribute set. NixOS reads thenixosConfigurations.<hostname>output when you rebuild.flake.lockis the reproducibility win: it pins each loose input reference to an exact commit + hash. Commit it alongsideflake.nix; upgrade deliberately withnix flake update.- Build with
sudo nixos-rebuild switch --flake .#hostname.switch= now + default;boot= next boot;test= now but not the boot default. Activation is atomic. - Flakes only see git-tracked files:
git addnew files (includingconfiguration.nix) before rebuilding, or Nix will insist they don't exist. stateVersionrecords the release you first installed on — set it once and never change it.
You now have a real, reproducible NixOS system defined by two small files. But
configuration.nix was a flat list of settings, and we waved at the fact that modules
is a list for a reason. Next, we'll unpack the NixOS module system —
how options are declared, merged, and split across many files — which is what lets a
configuration grow from this skeleton into a full machine without becoming a mess.