From NixOS Wiki
Jump to: navigation, search

NixOS has native support for ZFS (wikipedia:ZFS). It uses the code from the ZFS on Linux project, including kernel modules and userspace utilities. The installation isos also come with zfs.

What works

All functionality supported by ZFS on Linux, including:

  • Using ZFS as the root filesystem (using either MS-DOS or GPT partitions)
  • Encrypted ZFS pools (using either native encryption or Linux's dm-crypt)
  • All the other ZFS goodies (cheap snapshotting, checksumming, compression, RAID-Z, …)
  • Auto-snapshotting service

Known issues

Note: Setting boot.zfs.enableUnstable = true; is required if you are running an newer kernel which is not yet officially supported by zfs, otherwise the zfs module will refuse to evaluate and show up as broken. This will install a pre-release of zfs. This might be not as stable as a released version. However in the past this rarely lead to problems/stability issues
  • Using NixOS on a ZFS root file system might result in the boot error external pointer tables not supported when the number of hardlinks in the nix store gets very high. This can be avoided by adding this option to your configuration.nix file:
boot.loader.grub.copyKernels = true;
  • In contrast to many native Linux filesystems, ZFS misses support for freeze/thaw operations.This means that using ZFS together with hibernation (suspend to disk) may cause filesystem corruption.See https://github.com/openzfs/zfs/issues/260.
Note: For now, setting boot.kernelParams = [ "nohibernate" ];is necessary to avoid the issue described above.


  • (ZFS, unrelated to Nix- see https://github.com/openzfs/zfs/issues/7734) You shouldn't use a ZVol as a swap device, as it can deadlock under memory pressure.
  • You should set the mountpoint property of your ZFS filesystems to be legacy and let NixOS mount them like any other filesystem (such as ext4 or btrfs), otherwise some filesystems may fail to mount due to ordering issues.
  • By default, all ZFS pools available to the system will be forcibly imported during boot, regardless if you had imported them before or not. You should be careful not to have any other system accessing them at the same time, otherwise it will corrupt your pools. Normally (for the common desktop user) this should not be a problem, as a hard disk is usually only directly connected to one machine. This behaviour can be disabled by setting boot.zfs.forceImportAll = false.
  • If you create a zpool in the installer, make sure you run `zpool export <pool name>` after `nixos-install`, or else when you reboot into your new system, zfs will fail to import the zpool.

How to use it

Warning: Add all mounts to your configuration as legacy mounts as described in this article instead of zfs's own mount mechanism. Otherwise mounts might be not mounted in the correct order during boot!

Just add the following to your configuration.nix file:

boot.initrd.supportedFilesystems = ["zfs"]; # boot from zfs
boot.supportedFilesystems = [ "zfs" ];
services.udev.extraRules = ''
  ACTION=="add|change", KERNEL=="sd[a-z]*[0-9]*|mmcblk[0-9]*p[0-9]*|nvme[0-9]*n[0-9]*p[0-9]*", ENV{ID_FS_TYPE}=="zfs_member", ATTR{../queue/scheduler}="none"
''; # zfs already has its own scheduler. without this my(@Artturin) computer froze for a second when i nix build something.

Be sure to also set networking.hostId, see https://nixos.org/nixos/manual/options.html#opt-networking.hostId (Why- https://discourse.nixos.org/t/feedback-on-a-user-guide-i-created-on-installing-nixos-with-zfs/5986/4?u=srgom)

To activate the configuration and load the ZFS kernel module, run:

nixos-rebuild switch

All ZFS functionality should now be available.

If you want NixOS to auto-mount your ZFS filesystems during boot, you should set their mountpoint property to legacy and treat it like if it were any other filesystem, i.e.: mount the filesystem manually and regenerate your list of filesystems, as such:

zfs set mountpoint=legacy <pool>/<fs>
mount -t zfs <pool>/<fs> <mountpoint>

This will regenerate your /etc/nixos/hardware-configuration.nix file:

nixos-rebuild switch

NixOS will now make sure that your filesystem is always mounted during boot.

The nixos-generate-config command regenerates your /etc/nixos/hardware-configuration.nix file, which includes the list of filesystems for NixOS to mount during boot, e.g.:

  fileSystems."/home" =
    { device = "rpool/home";
      fsType = "zfs";

  fileSystems."/backup" =
    { device = "rpool/backup";
      fsType = "zfs";

Changing the Cache Size

ZFS has a complicated cache system. The cache you're most likely to want to fiddle with is the called Adaptive Replacement Cache, usually abbreviated ARC. This is the first-level (fastest) of ZFS's caches.

You can increase or decrease a parameter which represents approximately the maximum size of the ARC cache. You can't set its actual size (ZFS does that adaptively according to its workload), nor can you set its exact maximum size.

To change the maximum size of the ARC cache to (for example) 12 GB, add this to your NixOS configuration:

boot.kernelParams = ["zfs.zfs_arc_max=12884901888"];

In some versions of ZFS, you can change the maximum size of the ARC on the fly, but in NixOS 18.03 this is not possible. (Nor is it possible in other versions of ZFS on Linux yet, according to Stack Exchange.)

Automatic Scrubbing

Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:

services.zfs.autoScrub.enable = true;

You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).


Since zfs is a copy-on-write filesystem even for deleting files disk space is needed. Therefore it should be avoided to run out of disk space. Luckily it is possible to reserve disk space for datasets to prevent this.

To reserve space create a new unused dataset that gets a guaranteed disk space of 1GB.

zfs create -o refreservation=1G -o mountpoint=none zroot/reserved

where zroot should be replaced by a dataset in your pool. The dataset itself should not be used. In case you would run out of space you can shrink the reservation to reclaim enough disk space to cleanup the other data from the pool:

zfs set refreservation=none zroot/reserved

How to use the auto-snapshotting service

To auto-snapshot a ZFS filesystem or a ZVol, set its com.sun:auto-snapshot property to true, like this:

zfs set com.sun:auto-snapshot=true <pool>/<fs>

(Note that by default this property will be inherited by all descendent datasets, but you can set their properties to false if you prefer.)

Then, to enable the auto-snapshot service, add this to your configuration.nix:

services.zfs.autoSnapshot.enable = true;

And finally, run nixos-rebuild switch to activate the new configuration!

By default, the auto-snapshot service will keep the latest four 15-minute, 24 hourly, 7 daily, 4 weekly and 12 monthly snapshots. You can globally override this configuration by setting the desired number of snapshots in your configuration.nix, like this:

services.zfs.autoSnapshot = {
  enable = true;
  frequent = 8; # keep the latest eight 15-minute snapshots (instead of four)
  monthly = 1;  # keep only one monthly snapshot (instead of twelve)

You can also disable a given type of snapshots on a per-dataset basis by setting a ZFS property, like this:

zfs set com.sun:auto-snapshot:weekly=false <pool>/<fs>

This would disable only weekly snapshots on the given filesystem.

How to install NixOS on a ZFS root filesystem

Another guide titled "Encrypted ZFS mirror with mirrored boot on NixOS" is available at https://elis.nu/blog/2019/08/encrypted-zfs-mirror-with-mirrored-boot-on-nixos/.

OpenZFS document for NixOS Root on ZFS is also available: https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/Root%20on%20ZFS.html

Pool Layout Considerations

it is important to keep /nix and the rest of the filesystem in different sections of the dataset hierarchy, like this:

            nix         mounted to /nix
            root        mounted to /
            home        mounted to /home

the name of `local` and `safe` can change, but them being peers is important.

ZFS can take consistent and atomic snapshots recursively down a dataset's hierarchy. Since Nix is good at being Nix, most users will want their server's data backed up, and don't mind reinstalling NixOS and then restoring data. If this is sufficient, only snapshot and back up the safe hierarchy. Users who want to be able to restore a service with only ZFS snapshots will want to snapshot the entire tree, at the significant expense of snapshotting the Nix store.

Dataset Properties

The following is a list of recommended dataset properties which have no drawbacks under regular uses:

  • compression=lz4
  • xattr=sa for Journald
  • acltype=posixacl also for Journald

The following is a list of dataset properties which are often useful, but do have drawbacks:

  • atime=off disables if a file's access time is updated when the file is read. This can result in significant performance gains, but might confuse some software like mailers.


Journald requires some properties for journalctl to work for non-root users. The dataset containing /var/log/journal (probably the / dataset for simple configurations) should be created with xattr=sa and acltype=posixacl.

For example:

$ zpool create  -O xattr=sa -O acltype=posixacl rpool ...


$ zfs create -o xattr=sa -o acltype=posixacl rpool/root

If you have already created the dataset, these properties can be set later:

$ zfs set xattr=sa acltype=posixacl rpool/root


These instructions will get you started with a single-disk ZFS setup. If you're interested in setting up RAID, see below.

# Always use the by-id aliases for devices, otherwise ZFS can choke on imports.

# Partition 2 will be the boot partition, needed for legacy (BIOS) boot
sgdisk -a1 -n2:34:2047 -t2:EF02 $DISK
# If you need EFI support, make an EFI partition:
sgdisk -n3:1M:+512M -t3:EF00 $DISK
# Partition 1 will be the main ZFS partition, using up the remaining space on the drive.
sgdisk -n1:0:0 -t1:BF01 $DISK

# Create the pool. If you want to tweak this a bit and you're feeling adventurous, you
# might try adding one or more of the following additional options:
# To disable writing access times:
#   -O atime=off
# To enable filesystem compression:
#   -O compression=lz4
# To improve performance of certain extended attributes:
#   -O xattr=sa
# For systemd-journald posixacls are required
#   -O  acltype=posixacl 
# To specify that your drive uses 4K sectors instead of relying on the size reported
# by the hardware (note small 'o'):
#   -o ashift=12
# The 'mountpoint=none' option disables ZFS's automount machinery; we'll use the
# normal fstab-based mounting machinery in Linux.
# '-R /mnt' is not a persistent property of the FS, it'll just be used while we're installing.
zpool create -O mountpoint=none rpool $DISK-part1

# Create the filesystems. This layout is designed so that /home is separate from the root
# filesystem, as you'll likely want to snapshot it differently for backup purposes. It also
# makes a "nixos" filesystem underneath the root, to support installing multiple OSes if
# that's something you choose to do in future.
zfs create -o mountpoint=legacy rpool/root
zfs create -o mountpoint=legacy rpool/root/nixos
zfs create -o mountpoint=legacy rpool/home

# Mount the filesystems manually. The nixos installer will detect these mountpoints
# and save them to /mnt/nixos/hardware-configuration.nix during the install process.
mount -t zfs rpool/root/nixos /mnt
mkdir /mnt/home
mount -t zfs rpool/home /mnt/home

# If you need to boot EFI, you'll need to set up /boot as a non-ZFS partition.
mkfs.vfat $DISK-part3
mkdir /mnt/boot
mount $DISK-part3 /mnt/boot

# Generate the NixOS configuration, as per the NixOS manual.
nixos-generate-config --root /mnt

# Edit /mnt/etc/nixos/configuration.nix and add the following line:
## ---8<-------------------------8<---
  boot.supportedFilesystems = [ "zfs" ];
## ---8<-------------------------8<---

# Also, make sure you set the networking.hostId option, which ZFS requires:
## ---8<-------------------------8<---
  networking.hostId = "<random 8-digit hex string>";
## ---8<-------------------------8<---
# See https://nixos.org/nixos/manual/options.html#opt-networking.hostId for more.

# Continue with installation!


Here's an example of how to create a ZFS root pool using 4 disks in RAID-10 mode (striping+mirroring), create a ZFS root+home filesystems and install NixOS on them: (thanks to Danny Wilson for the instructions)

# Verify that the installer environment has loaded the ZFS kernel module (default since 18.09)
lsmod | grep zfs

# Create boot partition and (zfs) data partition
# For information on the ZFS partitions see https://openzfs.github.io/openzfs-docs/Getting%20Started/Ubuntu/Ubuntu%2018.04%20Root%20on%20ZFS.html#step-2-disk-formatting
# The linked guide assumes a pure ZFS setup which is not the same suitable for this guide. You will have to create the partitions for the /boot raid by yourself.
fdisk /dev/sda

# Copy the partition table to the other disks
sfdisk --dump /dev/sda | sfdisk /dev/sdb
sfdisk --dump /dev/sda | sfdisk /dev/sdc
sfdisk --dump /dev/sda | sfdisk /dev/sdd

# Create a RAID-10 ZFS pool. Use "-o ashift=12" to create your ZFS pool with 4K sectors
# enable posixacls, otherwise journalctl is broken for users
zpool create -o ashift=12 -o altroot=/mnt -O  acltype=posixacl -O xattr=sa rpool mirror /dev/sda2 /dev/sdb2 mirror /dev/sdc2 /dev/sdd2

# Create the filesystems
zfs create -o mountpoint=none rpool/root
zfs create -o mountpoint=legacy rpool/root/nixos
zfs create -o mountpoint=legacy rpool/home
zfs set compression=lz4 rpool/home    # compress the home directories automatically

# Mount the filesystems manually
mount -t zfs rpool/root/nixos /mnt

mkdir /mnt/home
mount -t zfs rpool/home /mnt/home

# Create a raid mirror of the first partitions for /boot (GRUB)
mdadm --create /dev/md127 --metadata=0.90 --level=1 --raid-devices=4 /dev/sd[a,b,c,d]1
mkfs.ext4 -m 0 -L boot -j /dev/md127

mkdir /mnt/boot
mount /dev/md127 /mnt/boot

# Generate the NixOS configuration, as per the NixOS manual
nixos-generate-config --root /mnt

# Now edit the generated hardware config:
nano /mnt/etc/nixos/hardware-configuration.nix

## ---8<-------------------------8<---
# This is what you want:

  fileSystems."/" =
    { device = "rpool/root/nixos";
      fsType = "zfs";

  fileSystems."/home" =
    { device = "rpool/home";
      fsType = "zfs";

  fileSystems."/boot" =
    { device = "/dev/md127";
      fsType = "ext4";
## ---8<-------------------------8<---

# configuration.nix needs an adjustment:
nano /mnt/etc/nixos/configuration.nix

## ---8<-------------------------8<---
# This is some more of what you want:

  boot.loader.grub.devices = [ "/dev/sda" "/dev/sdb" "/dev/sdc" "/dev/sdd" ];
  boot.supportedFilesystems = [ "zfs" ];
## ---8<-------------------------8<---

# Ready to go!

Encrypted ZFS

Assuming that a zpool named zroot has been already created as described. Encrypted datasets can be added on top as follow:

posixacl are needed for journald
zfs create -o  acltype=posixacl -o xattr=sa -o encryption=aes-256-gcm -o keyformat=passphrase -o mountpoint=none zroot/root

Instead of encrypting just a dataset (and all its child datasets) you can also directly encrypt the whole pool upon creation:

zpool create -o ashift=12 -o altroot="/mnt" -O mountpoint=none -O encryption=aes-256-gcm -O keyformat=passphrase zroot /dev/sdxy

All child datasets will inherit the encryption.

Note that using grub to boot directly from zfs with encryption enabled might not work at the moment, so a separate boot partition is required.

A full encrypted nixos installation on an UEFI system could look like this:

zfs create -o mountpoint=legacy -o sync=disabled zroot/root/tmp
zfs create -o mountpoint=legacy -o com.sun:auto-snapshot=true zroot/root/home
zfs create -o mountpoint=legacy -o com.sun:auto-snapshot=true zroot/root/nixos
mount -t zfs zroot/root/nixos /mnt
mkdir /mnt/{home,tmp,boot}
assuming that /dev/sda1 is the boot partition
mkfs.vfat /dev/sda1
mount /dev/sda1 /mnt/boot/
mount -t zfs zroot/root/home /mnt/home/
mount -t zfs zroot/root/tmp /mnt/tmp/
nixos-generate-config  --root /mnt

To unlock the zfs dataset at root also the boot.zfs.requestEncryptionCredentials option must be set to true. Note that at the moment one can only use passphrases (keylocation=prompt) for pools that are mounted as the root fs. Data pools are mounted by a background systemd service and need a key (keylocation=file://). A key file could be for example put on a root filesystem if it is encrypted.

If the key is not on the root filesystem, you will also need to set zfs-import-poolname.serviceConfig.RequiresMountsFor=/path/to/key, where poolname is the name of the data pool. This makes sure that systemd will mount the filesystem for /path/to/key first before importing the zfs pool.

Unlock encrypted zfs via ssh on boot

In case you want unlock a machine remotely (after an update), having an ssh service in initrd for the password prompt is handy:

 boot = {
   initrd.network = {
     # This will use udhcp to get an ip address.
     # Make sure you have added the kernel module for your network driver to `boot.initrd.availableKernelModules`, 
     # so your initrd can load it!
     # Static ip addresses might be configured using the ip argument in kernel command line:
     # https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt
     enable = true;
     ssh = {
        enable = true;
        # To prevent ssh clients from freaking out because a different host key is used,
        # a different port for ssh is useful (assuming the same host has also a regular sshd running)
        port = 2222; 
        # hostKeys paths must be unquoted strings, otherwise you'll run into issues with boot.initrd.secrets
        # the keys are copied to initrd from the path specified; multiple keys can be set
        # you can generate any number of host keys using 
        # `ssh-keygen -t ed25519 -N "" -f /path/to/ssh_host_ed25519_key`
        hostKeys = [ /path/to/ssh_host_rsa_key ];
        # public ssh key used for login
        authorizedKeys = [ "ssh-rsa AAAA..." ];
     # this will automatically load the zfs password prompt on login
     # and kill the other prompt so boot can continue
     postCommands = ''
       cat <<EOF > /root/.profile 
       if pgrep -x "zfs" > /dev/null 
         zfs load-key -a 
         killall zfs 
         echo "zfs not running -- maybe the pool is taking some time to load for some unforseen reason." 
  • In order to use DHCP in the initrd, network manager must not be enabled and networking.useDHCP = true; must be set.
  • If your network card isn't started, you'll need to add the according kernel module to the initrd as well, e.g. boot.initrd.kernelModules = [ "r8169" ];

Import and unlock multiple encrypted pools/dataset at boot

If you have not only one encrypted pool/dataset but multiple ones and you want to import and unlock them at boot, so that they can be automounted using the hardware-configuration.nix, you could just amend the boot.initrd.network.postCommands option.

Unfortunately having an unlock key file stored in an encrypted zfs dataset cannot be used directly, so the pool must use keyformat=passphrase and keylocation=prompt.

The following example follows the remote unlocking with OpenSSH, but imports another pool also and prompts for unlocking (either when at the machine itself or when logging in remotely:

 boot = {
   initrd.network = {
     enable = true;
     ssh = {
        enable = true;
        port = 2222; 
        hostKeys = [ /path/to/ssh_host_rsa_key ];
        authorizedKeys = [ "ssh-rsa AAAA..." ];
     postCommands = ''
       zpool import tankXXX
       echo "zfs load-key -a; killall zfs" >> /root/.profile

When you login by SSH into the box or when you have physical access to the machine itself, you will be prompted to supply the unlocking password for your zroot and tankXXX pools.

ZFS Trim Support for SSDs

ZFS 0.8 now also features trim support for SSDs.

How to use ZFS trimming

ZFS trimming works on one or more zpools and will trim each ssd inside it. There are two modes of it. One mode will manually trim the specified pool and the other will auto-trim pools. However the main difference is, that auto-trim will skip ranges that it considers too small while manually issued trim will trim all ranges.

To manually start trimming of a zpool run: zpool trim tank. Since PR-65331 this can be also done periodically (by default once a week) by setting services.zfs.trim.enable = true.

To set a pool for auto-trim run: zpool set autotrim=on tank

To check the status of the manual trim, you can just run zpool status -t

To see the effects of trimming, you can run zpool iostat -r and zpool iostat -w

To see whether auto-trimming works, just run zpool iostat -r note the results and run it later again. The trim entries should change.

For further information read the PR description.

Following are a few discourse posts on zfs, serving as pointers, form your own opinion

Mail notification for ZFS Event Daemon

ZFS Event Daemon (zed) monitors events generated by the ZFS kernel module and runs configured tasks. It can be configured to send an email when a pool scrub is finished or a disk has failed.

First, we need to configure a mail transfer agent, the program that sends email:

    programs.msmtp = {
      enable = true;
      setSendmail = true;
      defaults = {
        aliases = "/etc/aliases";
        port = 465;
        tls_trust_file = "/etc/ssl/certs/ca-certificates.crt";
        tls = "on";
        auth = "login";
        tls_starttls = "off";
      accounts = {
        default = {
          host = "mail.example.com";
          passwordeval = "cat /etc/emailpass.txt";
          user = "user@example.com";
          from = "user@example.com";

Then, configure an alias for root account. With this alias configured, all mails sent to root, such as cron job results and failed sudo login events, will be redirected to the configured email account.

tee -a /etc/aliases <<EOF
root: user@example.com

Finally, override default zed settings with a custom one:

  services.zfs.zed.settings =
   ZED_DEBUG_LOG = "/tmp/zed.debug.log";
   ZED_EMAIL_ADDR = [ "root" ];
   ZED_EMAIL_PROG = "${ pkgs.msmtp }/bin/msmtp";


  # this option does not work; will return error
  services.zfs.zed.enableMail = false;

You can now test this by performing a scrub

zpool scrub $pool

Mount datasets without legacy mountpoint

Contrary to conventional wisdom, mountpoint=legacy is not required for mounting datasets. The trick is to use mount -t zfs -o zfsutil path/to/dataset /path/to/mountpoint.

Also, legacy mountpoints are also inconvenient in that the mounts can not be natively handled by zfs mount command, hence legacy in the name.

An example configuration of mounting non-legacy dataset is the following:

  fileSystems."/tank" =
    { device = "tank_pool/data";
      fsType = "zfs"; options = [ "zfsutil" ];

NFS share

With sharenfs property, ZFS has build-in support for generating /etc/exports.d/zfs.exports file, which in turn is processed by NFS service automatically.

Warning: If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs your rule will not correctly apply, and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - openzfs/zfs#11939

To enable NFS share on a dataset, only two steps are needed:

First, enable NFS service:

  services.nfs.server.enable = true;

Only this line is needed. Configure firewall if necessary, as described in NFS article.

Then, set sharenfs property:

zfs set sharenfs="ro=,all_squash,anonuid=70,anongid=70" rpool/myData

For more options, see man 5 exports.

See also

This article on how to setup encrypted ZFS on Hetzner: <https://mazzo.li/posts/hetzner-zfs.html>.