How do I set up a swap file?

I’ve tried adding this to my configuration.nix:

swapDevices = [ { device = "/swapfile"; size = 2048; } ];

But it gives me the error:

A dependency job for failed. See 'journalctl -xe' for details.
warning: the following units failed: swapfile.swap

● swapfile.swap - /swapfile
   Loaded: loaded (/etc/fstab; generated)
   Active: failed (Result: exit-code) since Sun 2020-07-26 11:05:53 EDT; 24ms ago
     What: /swapfile
     Docs: man:fstab(5)
       IP: 0B in, 0B out
      CPU: 2ms

Jul 26 11:05:53 corpus-db-nixos swapon[18433]: swapon: /swapfile: swapon failed: Invalid argument
Jul 26 11:05:53 corpus-db-nixos systemd[1]: Activating swap /swapfile...
Jul 26 11:05:53 corpus-db-nixos systemd[1]: swapfile.swap: Swap process exited, code=exited, status=255/EXCEPTION
Jul 26 11:05:53 corpus-db-nixos systemd[1]: swapfile.swap: Failed with result 'exit-code'.
Jul 26 11:05:53 corpus-db-nixos systemd[1]: Failed to activate swap /swapfile.
warning: error(s) occurred while switching to the new configuration

And indeed when I try to run sudo swapon /swapfile I get: swapon: /swapfile: swapon failed: Invalid argument.

How should I be setting up a swap file? If it makes a difference, I’m trying to do this on a VPS.

I set up partitions before nixos-install and then it gets generated for me inside hardware-configuration.nix:

  swapDevices =
    [ { device = "/dev/disk/by-uuid/some-redacted-uuid"; }

(Maybe there are some other ways, too.)

There is a bug in the NixOS module, see

1 Like

I can’t seem to get that workaround working for me, either. I tried removing the old swap file, creating a new one using dd, fixing the permissions, and restarting the service, but I’m still getting swapon failed: Invalid argument, no matter what. Furthermore, in journalctl -xe I see kernel: swapon: swapfile has holes.

Forgot to mention, the size you use for the dd command needs to exactly match the size set in the module, otherwise the module will call fallocate again:

Oh, I didn’t realize it wasn’t a normal swap partition in the OP.