Table of Contents
This manual describes how to install, use and extend NixOS, a Linux distribution based on the purely functional package management system Nix, that is composed using modules and packages defined in the Nixpkgs project.
Additional information regarding the Nix package manager and the Nixpkgs project can be found in respectively the Nix manual and the Nixpkgs manual.
If you encounter problems, please report them on the
Discourse
or
on the
#nixos
channel on Freenode. Bugs should be
reported in
NixOS’
GitHub issue tracker.
#
have to be run as root, either
requiring to login as root user or temporarily switching to it using
sudo
for example.
This section describes how to obtain, install, and configure NixOS for first-time use.
NixOS ISO images can be downloaded from the NixOS download page. There are a number of installation options. If you happen to have an optical drive and a spare CD, burning the image to CD and booting from that is probably the easiest option. Most people will need to prepare a USB stick to boot from. Section 2.5.1, “Booting from a USB Drive” describes the preferred method to prepare a USB stick. A number of alternative methods are presented in the NixOS Wiki.
As an alternative to installing NixOS yourself, you can get a running NixOS system through several other means:
Using virtual appliances in Open Virtualization Format (OVF) that can be imported into VirtualBox. These are available from the NixOS download page.
Using AMIs for Amazon’s EC2. To find one for your region and instance type, please refer to the list of most recent AMIs.
Using NixOps, the NixOS-based cloud deployment tool, which allows you to provision VirtualBox and EC2 NixOS instances from declarative specifications. Check out the NixOps homepage for details.
Table of Contents
NixOS can be installed on BIOS or UEFI systems. The procedure for a UEFI installation is by and large the same as a BIOS installation. The differences are mentioned in the steps that follow.
The installation media can be burned to a CD, or now more commonly, "burned" to a USB drive (see Section 2.5.1, “Booting from a USB Drive”).
The installation media contains a basic NixOS installation. When it’s finished booting, it should have detected most of your hardware.
The NixOS manual is available on virtual console 8 (press Alt+F8 to access) or by running nixos-help.
You are logged-in automatically as nixos
.
The nixos
user account has an empty password so you
can use sudo without a password.
If you downloaded the graphical ISO image, you can run systemctl start display-manager to start the desktop environment. If you want to continue on the terminal, you can use loadkeys to switch to your preferred keyboard layout. (We even provide neo2 via loadkeys de neo!)
The boot process should have brought up networking (check ip a). Networking is necessary for the installer, since it will download lots of stuff (such as source tarballs or Nixpkgs channel binaries). It’s best if you have a DHCP server on your network. Otherwise configure networking manually using ifconfig.
To manually configure the network on the graphical installer, first disable network-manager with systemctl stop NetworkManager.
To manually configure the wifi on the minimal installer, run wpa_supplicant -B -i interface -c <(wpa_passphrase 'SSID' 'key').
If you would like to continue the installation from a different machine you
need to activate the SSH daemon via systemctl start
sshd. You then must set a password for either root
or
nixos
with passwd to be able to login.
The NixOS installer doesn’t do any partitioning or formatting, so you need to do that yourself.
The NixOS installer ships with multiple partitioning tools. The examples below use parted, but also provides fdisk, gdisk, cfdisk, and cgdisk.
The recommended partition scheme differs depending if the computer uses Legacy Boot or UEFI.
Here's an example partition scheme for UEFI, using
/dev/sda
as the device.
Create a GPT partition table.
#
parted /dev/sda -- mklabel gpt
Add the root partition. This will fill the disk except for the end part, where the swap will live, and the space left in front (512MiB) which will be used by the boot partition.
#
parted /dev/sda -- mkpart primary 512MiB -8GiB
Next, add a swap partition. The size required will vary according to needs, here a 8GiB one is created.
#
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
Finally, the boot partition. NixOS by default uses the ESP (EFI system partition) as its /boot partition. It uses the initially reserved 512MiB at the start of the disk.
#
parted /dev/sda -- mkpart ESP fat32 1MiB 512MiB#
parted /dev/sda -- set 3 boot on
Once complete, you can follow with Section 2.2.3, “Formatting”.
Here's an example partition scheme for Legacy Boot, using
/dev/sda
as the device.
Create a MBR partition table.
#
parted /dev/sda -- mklabel msdos
Add the root partition. This will fill the the disk except for the end part, where the swap will live.
#
parted /dev/sda -- mkpart primary 1MiB -8GiB
Finally, add a swap partition. The size required will vary according to needs, here a 8GiB one is created.
#
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
Once complete, you can follow with Section 2.2.3, “Formatting”.
Use the following commands:
For initialising Ext4 partitions: mkfs.ext4. It is
recommended that you assign a unique symbolic label to the file system
using the option -L
,
since this makes the file system configuration independent from device
changes. For example:
label
#
mkfs.ext4 -L nixos /dev/sda1
For creating swap partitions: mkswap. Again it’s
recommended to assign a label to the swap partition: -L
. For example:
label
#
mkswap -L swap /dev/sda2
For creating boot partitions: mkfs.fat. Again
it’s recommended to assign a label to the boot partition:
-n
. For example:
label
#
mkfs.fat -F 32 -n boot /dev/sda3
For creating LVM volumes, the LVM commands, e.g., pvcreate, vgcreate, and lvcreate.
For creating software RAID devices, use mdadm.
Mount the target file system on which NixOS should be installed on
/mnt
, e.g.
#
mount /dev/disk/by-label/nixos /mnt
Mount the boot file system on /mnt/boot
, e.g.
#
mkdir -p /mnt/boot#
mount /dev/disk/by-label/boot /mnt/boot
If your machine has a limited amount of memory, you may want to activate
swap devices now (swapon
device
). The installer (or rather,
the build actions that it may spawn) may need quite a bit of RAM,
depending on your configuration.
#
swapon /dev/sda2
You now need to create a file
/mnt/etc/nixos/configuration.nix
that specifies the
intended configuration of the system. This is because NixOS has a
declarative configuration model: you create or edit a
description of the desired configuration of your system, and then NixOS
takes care of making it happen. The syntax of the NixOS configuration file
is described in Chapter 5, Configuration Syntax, while a list
of available configuration options appears in
Appendix A, Configuration Options. A minimal example is shown in
Example 2.4, “NixOS Configuration”.
The command nixos-generate-config can generate an initial configuration file for you:
#
nixos-generate-config --root /mnt
You should then edit /mnt/etc/nixos/configuration.nix
to suit your needs:
#
nano /mnt/etc/nixos/configuration.nix
If you’re using the graphical ISO image, other editors may be available
(such as vim). If you have network access, you can also
install other editors — for instance, you can install Emacs by running
nix-env -f '<nixpkgs>' -iA emacs
.
You must set the option
boot.loader.grub.device
to specify on which disk
the GRUB boot loader is to be installed. Without it, NixOS cannot boot.
You must set the option
boot.loader.systemd-boot.enable
to
true
. nixos-generate-config
should do this automatically for new configurations when booted in UEFI
mode.
You may want to look at the options starting with
boot.loader.efi
and
boot.loader.systemd
as well.
If there are other operating systems running on the machine before
installing NixOS, the boot.loader.grub.useOSProber
option can be set to true
to automatically add them to
the grub menu.
If you need to configure networking for your machine the configuration options are described in Chapter 11, Networking. In particular, while wifi is supported on the installation image, it is not enabled by default in the configuration generated by nixos-generate-config.
Another critical option is fileSystems
, specifying the
file systems that need to be mounted by NixOS. However, you typically
don’t need to set it yourself, because
nixos-generate-config sets it automatically in
/mnt/etc/nixos/hardware-configuration.nix
from your
currently mounted file systems. (The configuration file
hardware-configuration.nix
is included from
configuration.nix
and will be overwritten by future
invocations of nixos-generate-config; thus, you
generally should not modify it.) Additionally, you may want to look at
Hardware
configuration for known-hardware at this point or after
installation.
boot.initrd.kernelModules
to
include the kernel modules that are necessary for mounting the root file
system, otherwise the installed system will not be able to boot. (If this
happens, boot from the installation media again, mount the target file
system on /mnt
, fix
/mnt/etc/nixos/configuration.nix
and rerun
nixos-install
.) In most cases,
nixos-generate-config will figure out the required
modules.
Do the installation:
#
nixos-install
This will install your system based on the configuration you provided.
If anything fails due to a configuration problem or any other issue
(such as a network outage while downloading binaries from the NixOS
binary cache), you can re-run nixos-install after
fixing your configuration.nix
.
As the last step, nixos-install will ask you to set the
password for the root
user, e.g.
setting root password... Enter new UNIX password: *** Retype new UNIX password: ***
If everything went well:
#
reboot
You should now be able to boot into the installed NixOS. The GRUB boot menu shows a list of available configurations (initially just one). Every time you change the NixOS configuration (see Changing Configuration ), a new item is added to the menu. This allows you to easily roll back to a previous configuration if something goes wrong.
You should log in and change the root
password with
passwd.
You’ll probably want to create some user accounts as well, which can be done with useradd:
$
useradd -c 'Eelco Dolstra' -m eelco$
passwd eelco
You may also want to install some software. For instance,
$
nix-env -qaP \*
shows what packages are available, and
$
nix-env -f '<nixpkgs>' -iA w3m
installs the w3m
browser.
To summarise, Example 2.3, “Commands for Installing NixOS on /dev/sda
” shows a typical
sequence of commands for installing NixOS on an empty hard drive (here
/dev/sda
). Example 2.4, “NixOS Configuration” shows a
corresponding configuration Nix expression.
Example 2.1. Example partition schemes for NixOS on /dev/sda
(MBR)
#
parted /dev/sda -- mklabel msdos#
parted /dev/sda -- mkpart primary 1MiB -8GiB#
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
Example 2.2. Example partition schemes for NixOS on /dev/sda
(UEFI)
#
parted /dev/sda -- mklabel gpt#
parted /dev/sda -- mkpart primary 512MiB -8GiB#
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%#
parted /dev/sda -- mkpart ESP fat32 1MiB 512MiB#
parted /dev/sda -- set 3 boot on
Example 2.3. Commands for Installing NixOS on /dev/sda
With a partitioned disk.
#
mkfs.ext4 -L nixos /dev/sda1#
mkswap -L swap /dev/sda2#
swapon /dev/sda2#
mkfs.fat -F 32 -n boot /dev/sda3 # (for UEFI systems only)#
mount /dev/disk/by-label/nixos /mnt#
mkdir -p /mnt/boot # (for UEFI systems only)#
mount /dev/disk/by-label/boot /mnt/boot # (for UEFI systems only)#
nixos-generate-config --root /mnt#
nano /mnt/etc/nixos/configuration.nix#
nixos-install#
reboot
Example 2.4. NixOS Configuration
{ config, pkgs, ... }: { imports = [ # Include the results of the hardware scan. ./hardware-configuration.nix ];boot.loader.grub.device
= "/dev/sda"; # (for BIOS systems only)boot.loader.systemd-boot.enable
= true; # (for UEFI systems only) # Note: setting fileSystems is generally not # necessary, since nixos-generate-config figures them out # automatically in hardware-configuration.nix. #fileSystems."/".device = "/dev/disk/by-label/nixos"; # Enable the OpenSSH server. services.sshd.enable = true; }
For systems without CD drive, the NixOS live CD can be booted from a USB
stick. You can use the dd utility to write the image:
dd if=path-to-image
of=/dev/sdX
. Be careful about specifying
the correct drive; you can use the lsblk command to get a
list of block devices.
$
diskutil list [..] /dev/diskN (external, physical): #: TYPE NAME SIZE IDENTIFIER [..]$
diskutil unmountDisk diskN Unmount of all volumes on diskN was successful$
sudo dd if=nix.iso of=/dev/rdiskN
Using the 'raw' rdiskN device instead of diskN completes in minutes instead of hours. After dd completes, a GUI dialog "The disk you inserted was not readable by this computer" will pop up, which can be ignored.
The dd utility will write the image verbatim to the drive, making it the recommended option for both UEFI and non-UEFI installations.
Advanced users may wish to install NixOS using an existing PXE or iPXE setup.
These instructions assume that you have an existing PXE or iPXE infrastructure and simply want to add the NixOS installer as another option. To build the necessary files from a recent version of nixpkgs, you can run:
nix-build -A netboot nixos/release.nix
This will create a result
directory containing: *
bzImage
– the Linux kernel * initrd
– the initrd file * netboot.ipxe
– an example ipxe
script demonstrating the appropriate kernel command line arguments for this
image
If you’re using plain PXE, configure your boot loader to use the
bzImage
and initrd
files and have it
provide the same kernel command line arguments found in
netboot.ipxe
.
If you’re using iPXE, depending on how your HTTP/FTP/etc. server is
configured you may be able to use netboot.ipxe
unmodified,
or you may need to update the paths to the files to match your server’s
directory layout
In the future we may begin making these files available as build products from hydra at which point we will update this documentation with instructions on how to obtain them either for placing on a dedicated TFTP server or to boot them directly over the internet.
Installing NixOS into a VirtualBox guest is convenient for users who want to try NixOS without installing it on bare metal. If you want to use a pre-made VirtualBox appliance, it is available at the downloads page. If you want to set up a VirtualBox guest manually, follow these instructions:
Add a New Machine in VirtualBox with OS Type "Linux / Other Linux"
Base Memory Size: 768 MB or higher.
New Hard Disk of 8 GB or higher.
Mount the CD-ROM with the NixOS ISO (by clicking on CD/DVD-ROM)
Click on Settings / System / Processor and enable PAE/NX
Click on Settings / System / Acceleration and enable "VT-x/AMD-V" acceleration
Click on Settings / Display / Screen and select VBoxVGA as Graphics Controller
Save the settings, start the virtual machine, and continue installation like normal
There are a few modifications you should make in configuration.nix. Enable booting:
boot.loader.grub.device
= "/dev/sda";
Also remove the fsck that runs at startup. It will always fail to run,
stopping your boot until you press *
.
boot.initrd.checkJournalingFS
= false;
Shared folders can be given a name and a path in the host system in the
VirtualBox settings (Machine / Settings / Shared Folders, then click on the
"Add" icon). Add the following to the
/etc/nixos/configuration.nix
to auto-mount them. If you do
not add "nofail"
, the system will no boot properly. The
same goes for disabling rngd
which is normally used to get
randomness but this does not work in virtual machines.
{ config, pkgs, ...} : { security.rngd.enable = false; // otherwise vm will not boot ... fileSystems."/virtualboxshare" = { fsType = "vboxsf"; device = "nameofthesharedfolder"; options = [ "rw" "nofail" ]; }; }
The folder will be available directly under the root directory.
Because Nix (the package manager) & Nixpkgs (the Nix packages collection) can both be installed on any (most?) Linux distributions, they can be used to install NixOS in various creative ways. You can, for instance:
Install NixOS on another partition, from your existing Linux distribution (without the use of a USB or optical device!)
Install NixOS on the same partition (in place!), from your existing
non-NixOS Linux distribution using NIXOS_LUSTRATE
.
Install NixOS on your hard drive from the Live CD of any Linux distribution.
The first steps to all these are the same:
Install the Nix package manager:
Short version:
$
curl https://nixos.org/nix/install | sh$
. $HOME/.nix-profile/etc/profile.d/nix.sh # …or open a fresh shell
More details in the Nix manual
Switch to the NixOS channel:
If you've just installed Nix on a non-NixOS distribution, you will be on
the nixpkgs
channel by default.
$
nix-channel --list
nixpkgs https://nixos.org/channels/nixpkgs-unstable
As that channel gets released without running the NixOS tests, it will be
safer to use the nixos-*
channels instead:
$
nix-channel --add https://nixos.org/channels/nixos-version
nixpkgs
You may want to throw in a nix-channel --update
for good
measure.
Install the NixOS installation tools:
You'll need nixos-generate-config
and
nixos-install
and we'll throw in some man pages and
nixos-enter
just in case you want to chroot into your
NixOS partition. They are installed by default on NixOS, but you don't have
NixOS yet..
$
nix-env -iE "_: with import <nixpkgs/nixos> { configuration = {}; }; with config.system.build; [ nixos-generate-config nixos-install nixos-enter manual.manpages ]"
NIXOS_LUSTRATE
,
skip ahead.
Prepare your target partition:
At this point it is time to prepare your target partition. Please refer to the partitioning, file-system creation, and mounting steps of Chapter 2, Installing NixOS
If you're about to install NixOS in place using
NIXOS_LUSTRATE
there is nothing to do for this step.
Generate your NixOS configuration:
$
sudo `which nixos-generate-config` --root /mnt
You'll probably want to edit the configuration files. Refer to the
nixos-generate-config
step in
Chapter 2, Installing NixOS for more
information.
Consider setting up the NixOS bootloader to give you the ability to boot on
your existing Linux partition. For instance, if you're using GRUB and your
existing distribution is running Ubuntu, you may want to add something like
this to your configuration.nix
:
boot.loader.grub.extraEntries
= ''
menuentry "Ubuntu" {
search --set=ubuntu --fs-uuid 3cc3e652-0c1f-4800-8451-033754f68e6e
configfile "($ubuntu)/boot/grub/grub.cfg"
}
'';
(You can find the appropriate UUID for your partition in
/dev/disk/by-uuid
)
Create the nixbld
group and user on your original
distribution:
$
sudo groupadd -g 30000 nixbld$
sudo useradd -u 30000 -g nixbld -G nixbld nixbld
Download/build/install NixOS:
$
sudo PATH="$PATH" NIX_PATH="$NIX_PATH" `which nixos-install` --root /mnt
Again, please refer to the nixos-install
step in
Chapter 2, Installing NixOS for more information.
That should be it for installation to another partition!
Optionally, you may want to clean up your non-NixOS distribution:
$
sudo userdel nixbld$
sudo groupdel nixbld
If you do not wish to keep the Nix package manager installed either, run
something like sudo rm -rv ~/.nix-* /nix
and remove the
line that the Nix installer added to your ~/.profile
.
NIXOS_LUSTRATE
:
Generate your NixOS configuration:
$
sudo `which nixos-generate-config` --root /
Note that this will place the generated configuration files in
/etc/nixos
. You'll probably want to edit the
configuration files. Refer to the nixos-generate-config
step in Chapter 2, Installing NixOS for more
information.
You'll likely want to set a root password for your first boot using the
configuration files because you won't have a chance to enter a password
until after you reboot. You can initalize the root password to an empty one
with this line: (and of course don't forget to set one once you've rebooted
or to lock the account with sudo passwd -l root
if you
use sudo
)
users.users.root.initialHashedPassword = "";
Build the NixOS closure and install it in the system
profile:
$
nix-env -p /nix/var/nix/profiles/system -f '<nixpkgs/nixos>' -I nixos-config=/etc/nixos/configuration.nix -iA system
Change ownership of the /nix
tree to root (since your
Nix install was probably single user):
$
sudo chown -R 0.0 /nix
Set up the /etc/NIXOS
and
/etc/NIXOS_LUSTRATE
files:
/etc/NIXOS
officializes that this is now a NixOS
partition (the bootup scripts require its presence).
/etc/NIXOS_LUSTRATE
tells the NixOS bootup scripts to
move everything that's in the root partition to
/old-root
. This will move your existing distribution out
of the way in the very early stages of the NixOS bootup. There are
exceptions (we do need to keep NixOS there after all), so the NixOS
lustrate process will not touch:
The /nix
directory
The /boot
directory
Any file or directory listed in /etc/NIXOS_LUSTRATE
(one per line)
Support for NIXOS_LUSTRATE
was added in NixOS 16.09.
The act of "lustrating" refers to the wiping of the existing distribution.
Creating /etc/NIXOS_LUSTRATE
can also be used on NixOS
to remove all mutable files from your root partition (anything that's not
in /nix
or /boot
gets "lustrated" on
the next boot.
lustrate /ˈlʌstreɪt/ verb.
purify by expiatory sacrifice, ceremonial washing, or some other ritual action.
Let's create the files:
$
sudo touch /etc/NIXOS$
sudo touch /etc/NIXOS_LUSTRATE
Let's also make sure the NixOS configuration files are kept once we reboot on NixOS:
$
echo etc/nixos | sudo tee -a /etc/NIXOS_LUSTRATE
Finally, move the /boot
directory of your current
distribution out of the way (the lustrate process will take care of the
rest once you reboot, but this one must be moved out now because NixOS
needs to install its own boot files:
$
sudo mv -v /boot /boot.bak &&
sudo /nix/var/nix/profiles/system/bin/switch-to-configuration boot
Cross your fingers, reboot, hopefully you should get a NixOS prompt!
If for some reason you want to revert to the old distribution, you'll need to boot on a USB rescue disk and do something along these lines:
# mkdir root # mount /dev/sdaX root # mkdir root/nixos-root # mv -v root/* root/nixos-root/ # mv -v root/nixos-root/old-root/* root/ # mv -v root/boot.bak root/boot # We had renamed this by hand earlier # umount root # reboot
This may work as is or you might also need to reinstall the boot loader
And of course, if you're happy with NixOS and no longer need the old distribution:
sudo rm -rf /old-root
It's also worth noting that this whole process can be automated. This is especially useful for Cloud VMs, where provider do not provide NixOS. For instance, nixos-infect uses the lustrate process to convert Digital Ocean droplets to NixOS from other distributions automatically.
To install NixOS behind a proxy, do the following before running
nixos-install
.
Update proxy configuration in
/mnt/etc/nixos/configuration.nix
to keep the internet
accessible after reboot.
networking.proxy.default = "http://user:password@proxy:port/"; networking.proxy.noProxy = "127.0.0.1,localhost,internal.domain";
Setup the proxy environment variables in the shell where you are running
nixos-install
.
# proxy_url="http://user:password@proxy:port/" # export http_proxy="$proxy_url" # export HTTP_PROXY="$proxy_url" # export https_proxy="$proxy_url" # export HTTPS_PROXY="$proxy_url"
nesting.clone
option in
configuration.nix
to switch proxies at runtime. Refer to
Appendix A, Configuration Options for more information.
The file /etc/nixos/configuration.nix
contains the
current configuration of your machine. Whenever you’ve
changed something in that file, you
should do
#
nixos-rebuild switch
to build the new configuration, make it the default configuration for booting, and try to realise the configuration in the running system (e.g., by restarting system services).
daemon-reload
for each user with running user services.
sudo -i
.
You can also do
#
nixos-rebuild test
to build the configuration and switch the running system to it, but without making it the boot default. So if (say) the configuration locks up your machine, you can just reboot to get back to a working configuration.
There is also
#
nixos-rebuild boot
to build the configuration and make it the boot default, but not switch to it now (so it will only take effect after the next reboot).
You can make your configuration show up in a different submenu of the GRUB 2 boot screen by giving it a different profile name, e.g.
#
nixos-rebuild switch -p test
which causes the new configuration (and previous ones created using
-p test
) to show up in the GRUB submenu “NixOS - Profile
'test'”. This can be useful to separate test configurations from
“stable” configurations.
Finally, you can do
$
nixos-rebuild build
to build the configuration but nothing more. This is useful to see whether everything compiles cleanly.
If you have a machine that supports hardware virtualisation, you can also test the new configuration in a sandbox by building and running a QEMU virtual machine that contains the desired configuration. Just do
$
nixos-rebuild build-vm$
./result/bin/run-*-vm
The VM does not have any data from your host system, so your existing user
accounts and home directories will not be available unless you have set
mutableUsers = false
. Another way is to temporarily add
the following to your configuration:
users.users.your-user.initialHashedPassword = "test";
Important: delete the $hostname.qcow2 file if you have started the virtual machine at least once without the right users, otherwise the changes will not get picked up. You can forward ports on the host to the guest. For instance, the following will forward host port 2222 to guest port 22 (SSH):
$
QEMU_NET_OPTS="hostfwd=tcp::2222-:22" ./result/bin/run-*-vm
allowing you to log in via SSH (assuming you have set the appropriate passwords or SSH authorized keys):
$
ssh -p 2222 localhost
Table of Contents
The best way to keep your NixOS installation up to date is to use one of the NixOS channels. A channel is a Nix mechanism for distributing Nix expressions and associated binaries. The NixOS channels are updated automatically from NixOS’s Git repository after certain tests have passed and all packages have been built. These channels are:
Stable channels, such as
nixos-19.09
.
These only get conservative bug fixes and package upgrades. For instance,
a channel update may cause the Linux kernel on your system to be upgraded
from 4.19.34 to 4.19.38 (a minor bug fix), but not from
4.19.x
to 4.20.x
(a
major change that has the potential to break things). Stable channels are
generally maintained until the next stable branch is created.
The unstable channel,
nixos-unstable
.
This corresponds to NixOS’s main development branch, and may thus see
radical changes between channel updates. It’s not recommended for
production systems.
Small channels, such as
nixos-19.09-small
or
nixos-unstable-small
.
These are identical to the stable and unstable channels described above,
except that they contain fewer binary packages. This means they get
updated faster than the regular channels (for instance, when a critical
security patch is committed to NixOS’s source tree), but may require
more packages to be built from source than usual. They’re mostly
intended for server environments and as such contain few GUI applications.
To see what channels are available, go to https://nixos.org/channels. (Note that the URIs of the various channels redirect to a directory that contains the channel’s latest version and includes ISO images and VirtualBox appliances.) Please note that during the release process, channels that are not yet released will be present here as well. See the Getting NixOS page https://nixos.org/nixos/download.html to find the newest supported stable release.
When you first install NixOS, you’re automatically subscribed to the NixOS
channel that corresponds to your installation source. For instance, if you
installed from a 19.09 ISO, you will be subscribed to the
nixos-19.09
channel. To see which NixOS channel you’re
subscribed to, run the following as root:
# nix-channel --list | grep nixos nixos https://nixos.org/channels/nixos-unstable
To switch to a different NixOS channel, do
# nix-channel --add https://nixos.org/channels/channel-name
nixos
(Be sure to include the nixos
parameter at the end.) For
instance, to use the NixOS 19.09 stable channel:
# nix-channel --add https://nixos.org/channels/nixos-19.09 nixos
If you have a server, you may want to use the “small” channel instead:
# nix-channel --add https://nixos.org/channels/nixos-19.09-small nixos
And if you want to live on the bleeding edge:
# nix-channel --add https://nixos.org/channels/nixos-unstable nixos
You can then upgrade NixOS to the latest version in your chosen channel by running
# nixos-rebuild switch --upgrade
which is equivalent to the more verbose nix-channel --update nixos;
nixos-rebuild switch
.
nix-channel
--add
as a non root user (or without sudo) will not affect
configuration in /etc/nixos/configuration.nix
You can keep a NixOS system up-to-date automatically by adding the following
to configuration.nix
:
system.autoUpgrade.enable
= true;system.autoUpgrade.allowReboot
= true;
This enables a periodically executed systemd service named
nixos-upgrade.service
. If the allowReboot
option is false
, it runs nixos-rebuild switch
--upgrade to upgrade NixOS to the latest version in the current
channel. (To see when the service runs, see systemctl list-timers.)
If allowReboot
is true
, then the
system will automatically reboot if the new generation contains a different
kernel, initrd or kernel modules.
You can also specify a channel explicitly, e.g.
system.autoUpgrade.channel
= https://nixos.org/channels/nixos-19.09;
This chapter describes how to configure various aspects of a NixOS machine
through the configuration file
/etc/nixos/configuration.nix
. As described in
Chapter 3, Changing the Configuration, changes to this file only take
effect after you run nixos-rebuild.
Table of Contents
The NixOS configuration file
/etc/nixos/configuration.nix
is actually a Nix
expression, which is the Nix package manager’s purely functional
language for describing how to build packages and configurations. This means
you have all the expressive power of that language at your disposal,
including the ability to abstract over common patterns, which is very useful
when managing complex systems. The syntax and semantics of the Nix language
are fully described in the
Nix
manual, but here we give a short overview of the most important
constructs useful in NixOS configuration files.
The NixOS configuration file generally looks like this:
{ config, pkgs, ... }:
{ option definitions
}
The first line ({ config, pkgs, ... }:
) denotes that this
is actually a function that takes at least the two arguments
config
and pkgs
. (These are explained
later.) The function returns a set of option definitions
({
). These definitions
have the form ...
}
, where
name
=
value
name
is the name of an option and
value
is its value. For example,
{ config, pkgs, ... }: {services.httpd.enable
= true;services.httpd.adminAddr
= "alice@example.org"; services.httpd.virtualHosts.localhost.documentRoot = "/webroot"; }
defines a configuration with three option definitions that together enable
the Apache HTTP Server with /webroot
as the document
root.
Sets can be nested, and in fact dots in option names are shorthand for
defining a set containing another set. For instance,
services.httpd.enable
defines a set named
services
that contains a set named
httpd
, which in turn contains an option definition named
enable
with value true
. This means that
the example above can also be written as:
{ config, pkgs, ... }: { services = { httpd = { enable = true; adminAddr = "alice@example.org"; virtualHosts = { localhost = { documentRoot = "/webroot"; }; }; }; }; }
which may be more convenient if you have lots of option definitions that
share the same prefix (such as services.httpd
).
NixOS checks your option definitions for correctness. For instance, if you try to define an option that doesn’t exist (that is, doesn’t have a corresponding option declaration), nixos-rebuild will give an error like:
The option `services.httpd.enable' defined in `/etc/nixos/configuration.nix' does not exist.
Likewise, values in option definitions must have a correct type. For
instance, services.httpd.enable
must be a Boolean
(true
or false
). Trying to give it a
value of another type, such as a string, will cause an error:
The option value `services.httpd.enable' in `/etc/nixos/configuration.nix' is not a boolean.
Options have various types of values. The most important are:
Strings are enclosed in double quotes, e.g.
networking.hostName
= "dexter";
Special characters can be escaped by prefixing them with a backslash
(e.g. \"
).
Multi-line strings can be enclosed in double single quotes, e.g.
networking.extraHosts
=
''
127.0.0.2 other-localhost
10.0.0.1 server
'';
The main difference is that it strips from each line a number of spaces
equal to the minimal indentation of the string as a whole (disregarding
the indentation of empty lines), and that characters like
"
and \
are not special (making it
more convenient for including things like shell code). See more info
about this in the Nix manual
here.
These can be true
or false
, e.g.
networking.firewall.enable
= true;networking.firewall.allowPing
= false;
For example,
boot.kernel.sysctl
."net.ipv4.tcp_keepalive_time" = 60;
(Note that here the attribute name
net.ipv4.tcp_keepalive_time
is enclosed in quotes to
prevent it from being interpreted as a set named net
containing a set named ipv4
, and so on. This is
because it’s not a NixOS option but the literal name of a Linux kernel
setting.)
Sets were introduced above. They are name/value pairs enclosed in braces, as in the option definition
fileSystems
."/boot" =
{ device = "/dev/sda1";
fsType = "ext4";
options = [ "rw" "data=ordered" "relatime" ];
};
The important thing to note about lists is that list elements are separated by whitespace, like this:
boot.kernelModules
= [ "fuse" "kvm-intel" "coretemp" ];
List elements can be any other type, e.g. sets:
swapDevices = [ { device = "/dev/disk/by-label/swap"; } ];
Usually, the packages you need are already part of the Nix Packages
collection, which is a set that can be accessed through the function
argument pkgs
. Typical uses:
environment.systemPackages
= [ pkgs.thunderbird pkgs.emacs ];services.postgresql.package
= pkgs.postgresql_10;
The latter option definition changes the default PostgreSQL package used by NixOS’s PostgreSQL service to 10.x. For more information on packages, including how to add new ones, see Section 6.1.2, “Adding Custom Packages”.
If you find yourself repeating yourself over and over, it’s time to abstract. Take, for instance, this Apache HTTP Server configuration:
{
services.httpd.virtualHosts
=
{ "blog.example.org" = {
documentRoot = "/webroot/blog.example.org";
adminAddr = "alice@example.org";
forceSSL = true;
enableACME = true;
enablePHP = true;
};
"wiki.example.org" = {
documentRoot = "/webroot/wiki.example.org";
adminAddr = "alice@example.org";
forceSSL = true;
enableACME = true;
enablePHP = true;
};
};
}
It defines two virtual hosts with nearly identical configuration; the only
difference is the document root directories. To prevent this
duplication, we can use a let
:
let
commonConfig =
{ adminAddr = "alice@example.org";
forceSSL = true;
enableACME = true;
};
in
{
services.httpd.virtualHosts
=
{ "blog.example.org" = (commonConfig // { documentRoot = "/webroot/blog.example.org"; });
"wiki.example.org" = (commonConfig // { documentRoot = "/webroot/wiki.example.com"; });
};
}
The let commonConfig =
defines a variable named ...
commonConfig
. The
//
operator merges two attribute sets, so the
configuration of the second virtual host is the set
commonConfig
extended with the document root option.
You can write a let
wherever an expression is allowed.
Thus, you also could have written:
{services.httpd.virtualHosts
= let commonConfig =...
; in { "blog.example.org" = (commonConfig // {...
}) "wiki.example.org" = (commonConfig // {...
}) }; }
but not { let commonConfig =
since attributes (as opposed to
attribute values) are not expressions.
...
; in
...
; }
Functions provide another method of abstraction. For instance, suppose that we want to generate lots of different virtual hosts, all with identical configuration except for the document root. This can be done as follows:
{
services.httpd.virtualHosts
=
let
makeVirtualHost = webroot:
{ documentRoot = webroot;
adminAddr = "alice@example.org";
forceSSL = true;
enableACME = true;
};
in
{ "example.org" = (makeVirtualHost "/webroot/example.org");
"example.com" = (makeVirtualHost "/webroot/example.com");
"example.gov" = (makeVirtualHost "/webroot/example.gov");
"example.nl" = (makeVirtualHost "/webroot/example.nl");
};
}
Here, makeVirtualHost
is a function that takes a single
argument webroot
and returns the configuration for a virtual
host. That function is then called for several names to produce the list of
virtual host configurations.
The NixOS configuration mechanism is modular. If your
configuration.nix
becomes too big, you can split it into
multiple files. Likewise, if you have multiple NixOS configurations (e.g. for
different computers) with some commonality, you can move the common
configuration into a shared file.
Modules have exactly the same syntax as
configuration.nix
. In fact,
configuration.nix
is itself a module. You can use other
modules by including them from configuration.nix
, e.g.:
{ config, pkgs, ... }: { imports = [ ./vpn.nix ./kde.nix ];services.httpd.enable
= true;environment.systemPackages
= [ pkgs.emacs ];...
}
Here, we include two modules from the same directory,
vpn.nix
and kde.nix
. The latter
might look like this:
{ config, pkgs, ... }: {services.xserver.enable
= true;services.xserver.displayManager.sddm.enable
= true;services.xserver.desktopManager.plasma5.enable
= true; }
Note that both configuration.nix
and
kde.nix
define the option
environment.systemPackages
. When multiple modules
define an option, NixOS will try to merge the
definitions. In the case of environment.systemPackages
,
that’s easy: the lists of packages can simply be concatenated. The value in
configuration.nix
is merged last, so for list-type
options, it will appear at the end of the merged list. If you want it to
appear first, you can use mkBefore
:
boot.kernelModules
= mkBefore [ "kvm-intel" ];
This causes the kvm-intel
kernel module to be loaded
before any other kernel modules.
For other types of options, a merge may not be possible. For instance, if two
modules define services.httpd.adminAddr
,
nixos-rebuild will give an error:
The unique option `services.httpd.adminAddr' is defined multiple times, in `/etc/nixos/httpd.nix' and `/etc/nixos/configuration.nix'.
When that happens, it’s possible to force one definition take precedence over the others:
services.httpd.adminAddr
= pkgs.lib.mkForce "bob@example.org";
When using multiple modules, you may need to access configuration values
defined in other modules. This is what the config
function
argument is for: it contains the complete, merged system configuration. That
is, config
is the result of combining the configurations
returned by every module
[1]
. For example, here is a module that adds some packages to
environment.systemPackages
only if
services.xserver.enable
is set to
true
somewhere else:
{ config, pkgs, ... }: {environment.systemPackages
= if config.services.xserver.enable
then [ pkgs.firefox pkgs.thunderbird ] else [ ]; }
With multiple modules, it may not be obvious what the final value of a
configuration option is. The command nixos-option
allows you
to find out:
$
nixos-optionservices.xserver.enable
true$
nixos-optionboot.kernelModules
[ "tun" "ipv6" "loop"...
]
Interactive exploration of the configuration is possible using nix repl, a read-eval-print loop for Nix expressions. A typical use:
$
nix repl '<nixpkgs/nixos>'nix-repl>
config.networking.hostName
"mandark"nix-repl>
map (x: x.hostName) config.services.httpd.virtualHosts
[ "example.org" "example.gov" ]
While abstracting your configuration, you may find it useful to generate modules using code, instead of writing files. The example below would have the same effect as importing a file which sets those options.
{ config, pkgs, ... }: let netConfig = { hostName }: { networking.hostName = hostName; networking.useDHCP = false; }; in { imports = [ (netConfig "nixos.localdomain") ]; }
Below is a summary of the most important syntactic constructs in the Nix expression language. It’s not complete. In particular, there are many other built-in functions. See the Nix manual for the rest.
Example | Description |
---|---|
Basic values | |
"Hello world"
| A string |
"${pkgs.bash}/bin/sh"
| A string containing an expression (expands to "/nix/store/ ) |
true , false
| Booleans |
123
| An integer |
./foo.png
| A path (relative to the containing Nix expression) |
Compound values | |
{ x = 1; y = 2; }
| A set with attributes named x and y
|
{ foo.bar = 1; }
| A nested set, equivalent to { foo = { bar = 1; }; }
|
rec { x = "foo"; y = x + "bar"; }
| A recursive set, equivalent to { x = "foo"; y = "foobar"; }
|
[ "foo" "bar" ]
| A list with two elements |
Operators | |
"foo" + "bar"
| String concatenation |
1 + 2
| Integer addition |
"foo" == "f" + "oo"
| Equality test (evaluates to true ) |
"foo" != "bar"
| Inequality test (evaluates to true ) |
!true
| Boolean negation |
{ x = 1; y = 2; }.x
| Attribute selection (evaluates to 1 ) |
{ x = 1; y = 2; }.z or 3
| Attribute selection with default (evaluates to 3 ) |
{ x = 1; y = 2; } // { z = 3; }
| Merge two sets (attributes in the right-hand set taking precedence) |
Control structures | |
if 1 + 1 == 2 then "yes!" else "no!"
| Conditional expression |
assert 1 + 1 == 2; "yes!"
| Assertion check (evaluates to "yes!" ). See Section 44.4, “Warnings and Assertions” for using assertions in modules |
let x = "foo"; y = "bar"; in x + y
| Variable definition |
with pkgs.lib; head [ 1 2 3 ]
| Add all attributes from the given set to the scope
(evaluates to 1 ) |
Functions (lambdas) | |
x: x + 1
| A function that expects an integer and returns it increased by 1 |
(x: x + 1) 100
| A function call (evaluates to 101) |
let inc = x: x + 1; in inc (inc (inc 100))
| A function bound to a variable and subsequently called by name (evaluates to 103) |
{ x, y }: x + y
| A function that expects a set with required attributes
x and y and concatenates
them |
{ x, y ? "bar" }: x + y
| A function that expects a set with required attribute
x and optional y , using
"bar" as default value for
y
|
{ x, y, ... }: x + y
| A function that expects a set with required attributes
x and y and ignores any
other attributes |
{ x, y } @ args: x + y
| A function that expects a set with required attributes
x and y , and binds the
whole set to args
|
Built-in functions | |
import ./foo.nix
| Load and return Nix expression in given file |
map (x: x + x) [ 1 2 3 ]
| Apply a function to every element of a list (evaluates to [ 2 4 6 ] ) |
[1] If you’re wondering how it’s possible that the (indirect) result of a function is passed as an input to that same function: that’s because Nix is a “lazy” language — it only computes values when they are needed. This works as long as no individual configuration value depends on itself.
Table of Contents
This section describes how to add additional packages to your system. NixOS has two distinct styles of package management:
Declarative, where you declare what packages you want
in your configuration.nix
. Every time you run
nixos-rebuild, NixOS will ensure that you get a
consistent set of binaries corresponding to your specification.
Ad hoc, where you install, upgrade and uninstall packages via the nix-env command. This style allows mixing packages from different Nixpkgs versions. It’s the only choice for non-root users.
With declarative package management, you specify which packages you want on
your system by setting the option
environment.systemPackages
. For instance, adding the
following line to configuration.nix
enables the Mozilla
Thunderbird email application:
environment.systemPackages
= [ pkgs.thunderbird ];
The effect of this specification is that the Thunderbird package from Nixpkgs will be built or downloaded as part of the system when you run nixos-rebuild switch.
environment.systemPackages
might not be sufficient. You are advised to check the list of options whether a NixOS module for the package does not exist.
You can get a list of the available packages as follows:
$
nix-env -qaP '*' --description nixos.firefox firefox-23.0 Mozilla Firefox - the browser, reloaded...
The first column in the output is the attribute name,
such as nixos.thunderbird
.
Note: the nixos
prefix tells us that we want to get the
package from the nixos
channel and works only in CLI tools.
In declarative configuration use pkgs
prefix (variable).
To “uninstall” a package, simply remove it from
environment.systemPackages
and run
nixos-rebuild switch.
Some packages in Nixpkgs have options to enable or disable optional
functionality or change other aspects of the package. For instance, the
Firefox wrapper package (which provides Firefox with a set of plugins such as
the Adobe Flash player) has an option to enable the Google Talk plugin. It
can be set in configuration.nix
as follows:
nixpkgs.config.firefox.enableGoogleTalkPlugin = true;
Apart from high-level options, it’s possible to tweak a package in almost arbitrary ways, such as changing or disabling dependencies of a package. For instance, the Emacs package in Nixpkgs by default has a dependency on GTK 2. If you want to build it against GTK 3, you can specify that as follows:
environment.systemPackages
= [ (pkgs.emacs.override { gtk = pkgs.gtk3; }) ];
The function override
performs the call to the Nix
function that produces Emacs, with the original arguments amended by the set
of arguments specified by you. So here the function argument
gtk
gets the value pkgs.gtk3
, causing
Emacs to depend on GTK 3. (The parentheses are necessary because in Nix,
function application binds more weakly than list construction, so without
them, environment.systemPackages
would be a list with
two elements.)
Even greater customisation is possible using the function
overrideAttrs
. While the override
mechanism above overrides the arguments of a package function,
overrideAttrs
allows changing the
attributes passed to mkDerivation
.
This permits changing any aspect of the package, such as the source code. For
instance, if you want to override the source code of Emacs, you can say:
environment.systemPackages
= [
(pkgs.emacs.overrideAttrs (oldAttrs: {
name = "emacs-25.0-pre";
src = /path/to/my/emacs/tree;
}))
];
Here, overrideAttrs
takes the Nix derivation specified by
pkgs.emacs
and produces a new derivation in which the
original’s name
and src
attribute
have been replaced by the given values by re-calling
stdenv.mkDerivation
. The original attributes are
accessible via the function argument, which is conventionally named
oldAttrs
.
The overrides shown above are not global. They do not affect the original package; other packages in Nixpkgs continue to depend on the original rather than the customised package. This means that if another package in your system depends on the original package, you end up with two instances of the package. If you want to have everything depend on your customised instance, you can apply a global override as follows:
nixpkgs.config.packageOverrides = pkgs: { emacs = pkgs.emacs.override { gtk = pkgs.gtk3; }; };
The effect of this definition is essentially equivalent to modifying the
emacs
attribute in the Nixpkgs source tree. Any package in
Nixpkgs that depends on emacs
will be passed your
customised instance. (However, the value pkgs.emacs
in
nixpkgs.config.packageOverrides
refers to the original
rather than overridden instance, to prevent an infinite recursion.)
It’s possible that a package you need is not available in NixOS. In that case, you can do two things. First, you can clone the Nixpkgs repository, add the package to your clone, and (optionally) submit a patch or pull request to have it accepted into the main Nixpkgs repository. This is described in detail in the Nixpkgs manual. In short, you clone Nixpkgs:
$
git clone https://github.com/NixOS/nixpkgs$
cd nixpkgs
Then you write and test the package as described in the Nixpkgs manual.
Finally, you add it to environment.systemPackages
, e.g.
environment.systemPackages
= [ pkgs.my-package ];
and you run nixos-rebuild, specifying your own Nixpkgs tree:
# nixos-rebuild switch -I nixpkgs=/path/to/my/nixpkgs
The second possibility is to add the package outside of the Nixpkgs tree. For
instance, here is how you specify a build of the
GNU Hello
package directly in configuration.nix
:
environment.systemPackages
=
let
my-hello = with pkgs; stdenv.mkDerivation rec {
name = "hello-2.8";
src = fetchurl {
url = "mirror://gnu/hello/${name}.tar.gz";
sha256 = "0wqd8sjmxfskrflaxywc7gqw7sfawrfvdxd9skxawzfgyy0pzdz6";
};
};
in
[ my-hello ];
Of course, you can also move the definition of my-hello
into a separate Nix expression, e.g.
environment.systemPackages
= [ (import ./my-hello.nix) ];
where my-hello.nix
contains:
with import <nixpkgs> {}; # bring all of Nixpkgs into scope stdenv.mkDerivation rec { name = "hello-2.8"; src = fetchurl { url = "mirror://gnu/hello/${name}.tar.gz"; sha256 = "0wqd8sjmxfskrflaxywc7gqw7sfawrfvdxd9skxawzfgyy0pzdz6"; }; }
This allows testing the package easily:
$
nix-build my-hello.nix$
./result/bin/hello Hello, world!
With the command nix-env, you can install and uninstall packages from the command line. For instance, to install Mozilla Thunderbird:
$
nix-env -iA nixos.thunderbird
If you invoke this as root, the package is installed in the Nix profile
/nix/var/nix/profiles/default
and visible to all users
of the system; otherwise, the package ends up in
/nix/var/nix/profiles/per-user/
and is not visible to other users. The username
/profile-A
flag specifies the
package by its attribute name; without it, the package is installed by
matching against its package name (e.g. thunderbird
). The
latter is slower because it requires matching against all available Nix
packages, and is ambiguous if there are multiple matching packages.
Packages come from the NixOS channel. You typically upgrade a package by updating to the latest version of the NixOS channel:
$
nix-channel --update nixos
and then running nix-env -i
again. Other packages in the
profile are not affected; this is the crucial difference
with the declarative style of package management, where running
nixos-rebuild switch causes all packages to be updated to
their current versions in the NixOS channel. You can however upgrade all
packages for which there is a newer version by doing:
$
nix-env -u '*'
A package can be uninstalled using the -e
flag:
$
nix-env -e thunderbird
Finally, you can roll back an undesirable nix-env action:
$
nix-env --rollback
nix-env has many more flags. For details, see the nix-env(1) manpage or the Nix manual.
NixOS supports both declarative and imperative styles of user management. In
the declarative style, users are specified in
configuration.nix
. For instance, the following states
that a user account named alice
shall exist:
users.users
.alice = {
isNormalUser = true;
home = "/home/alice";
description = "Alice Foobar";
extraGroups = [ "wheel" "networkmanager" ];
openssh.authorizedKeys.keys = [ "ssh-dss AAAAB3Nza... alice@foobar" ];
};
Note that alice
is a member of the
wheel
and networkmanager
groups, which
allows her to use sudo to execute commands as
root
and to configure the network, respectively. Also note
the SSH public key that allows remote logins with the corresponding private
key. Users created in this way do not have a password by default, so they
cannot log in via mechanisms that require a password. However, you can use
the passwd program to set a password, which is retained
across invocations of nixos-rebuild.
If you set users.mutableUsers
to false, then the
contents of /etc/passwd
and /etc/group
will be congruent to your NixOS configuration. For instance, if you remove a
user from users.users
and run nixos-rebuild, the user
account will cease to exist. Also, imperative commands for managing users and
groups, such as useradd, are no longer available. Passwords may still be
assigned by setting the user's
hashedPassword
option. A hashed password can be generated using mkpasswd -m
sha-512 after installing the mkpasswd
package.
A user ID (uid) is assigned automatically. You can also specify a uid manually by adding
uid = 1000;
to the user specification.
Groups can be specified similarly. The following states that a group named
students
shall exist:
users.groups
.students.gid = 1000;
As with users, the group ID (gid) is optional and will be assigned automatically if it’s missing.
In the imperative style, users and groups are managed by commands such as
useradd, groupmod and so on. For
instance, to create a user account named alice
:
# useradd -m alice
To make all nix tools available to this new user use `su - USER` which opens a login shell (==shell that loads the profile) for given user. This will create the ~/.nix-defexpr symlink. So run:
# su - alice -c "true"
The flag -m
causes the creation of a home directory for the
new user, which is generally what you want. The user does not have an initial
password and therefore cannot log in. A password can be set using the
passwd utility:
# passwd alice Enter new UNIX password: *** Retype new UNIX password: ***
A user can be deleted using userdel:
# userdel -r alice
The flag -r
deletes the user’s home directory. Accounts
can be modified using usermod. Unix groups can be managed
using groupadd, groupmod and
groupdel.
Table of Contents
You can define file systems using the fileSystems
configuration option. For instance, the following definition causes NixOS to
mount the Ext4 file system on device
/dev/disk/by-label/data
onto the mount point
/data
:
fileSystems
."/data" =
{ device = "/dev/disk/by-label/data";
fsType = "ext4";
};
Mount points are created automatically if they don’t already exist. For
device
,
it’s best to use the topology-independent device aliases in
/dev/disk/by-label
and
/dev/disk/by-uuid
, as these don’t change if the
topology changes (e.g. if a disk is moved to another IDE controller).
You can usually omit the file system type
(fsType
),
since mount can usually detect the type and load the
necessary kernel module automatically. However, if the file system is needed
at early boot (in the initial ramdisk) and is not ext2
,
ext3
or ext4
, then it’s best to
specify fsType
to ensure that the kernel module is
available.
options = [
"nofail" ];
.
NixOS supports file systems that are encrypted using
LUKS (Linux Unified Key Setup). For example, here is how
you create an encrypted Ext4 file system on the device
/dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d
:
# cryptsetup luksFormat /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d WARNING! ======== This will overwrite data on /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d irrevocably. Are you sure? (Type uppercase yes): YES Enter LUKS passphrase: *** Verify passphrase: *** # cryptsetup luksOpen /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d crypted Enter passphrase for /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d: *** # mkfs.ext4 /dev/mapper/crypted
To ensure that this file system is automatically mounted at boot time as
/
, add the following to
configuration.nix
:
boot.initrd.luks.devices.crypted.device = "/dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d";
fileSystems
."/".device = "/dev/mapper/crypted";
Should grub be used as bootloader, and /boot
is located
on an encrypted partition, it is necessary to add the following grub option:
boot.loader.grub.enableCryptodisk
= true;
NixOS also supports unlocking your LUKS-Encrypted file system using a FIDO2 compatible token. In the following example, we will create a new FIDO2 credential
and add it as a new key to our existing device /dev/sda2
:
# export FIDO2_LABEL="/dev/sda2 @ $HOSTNAME" # fido2luks credential "$FIDO2_LABEL" f1d00200108b9d6e849a8b388da457688e3dd653b4e53770012d8f28e5d3b269865038c346802f36f3da7278b13ad6a3bb6a1452e24ebeeaa24ba40eef559b1b287d2a2f80b7 # fido2luks -i add-key /dev/sda2 f1d00200108b9d6e849a8b388da457688e3dd653b4e53770012d8f28e5d3b269865038c346802f36f3da7278b13ad6a3bb6a1452e24ebeeaa24ba40eef559b1b287d2a2f80b7 Password: Password (again): Old password: Old password (again): Added to key to device /dev/sda2, slot: 2
To ensure that this file system is decrypted using the FIDO2 compatible key, add the following to configuration.nix
:
boot.initrd.luks.fido2Support = true; boot.initrd.luks.devices."/dev/sda2".fido2.credential = "f1d00200108b9d6e849a8b388da457688e3dd653b4e53770012d8f28e5d3b269865038c346802f36f3da7278b13ad6a3bb6a1452e24ebeeaa24ba40eef559b1b287d2a2f80b7";
You can also use the FIDO2 passwordless setup, but for security reasons, you might want to enable it only when your device is PIN protected, such as Trezor.
boot.initrd.luks.devices."/dev/sda2".fido2.passwordLess = true;
The X Window System (X11) provides the basis of NixOS’ graphical user interface. It can be enabled as follows:
services.xserver.enable
= true;
The X server will automatically detect and use the appropriate video driver
from a set of X.org drivers (such as vesa
and
intel
). You can also specify a driver manually, e.g.
services.xserver.videoDrivers
= [ "r128" ];
to enable X.org’s xf86-video-r128
driver.
You also need to enable at least one desktop or window manager. Otherwise, you can only log into a plain undecorated xterm window. Thus you should pick one or more of the following lines:
services.xserver.desktopManager.plasma5.enable
= true;services.xserver.desktopManager.xfce.enable
= true;services.xserver.desktopManager.gnome3.enable
= true;services.xserver.desktopManager.mate.enable
= true;services.xserver.windowManager.xmonad.enable
= true;services.xserver.windowManager.twm.enable
= true;services.xserver.windowManager.icewm.enable
= true;services.xserver.windowManager.i3.enable
= true;
NixOS’s default display manager (the program that provides a graphical login prompt and manages the X server) is LightDM. You can select an alternative one by picking one of the following lines:
services.xserver.displayManager.sddm.enable
= true;services.xserver.displayManager.gdm.enable
= true;
You can set the keyboard layout (and optionally the layout variant):
services.xserver.layout
= "de";services.xserver.xkbVariant
= "neo";
The X server is started automatically at boot time. If you don’t want this to happen, you can set:
services.xserver.autorun
= false;
The X server can then be started manually:
# systemctl start display-manager.service
On 64-bit systems, if you want OpenGL for 32-bit programs such as in Wine, you should also set the following:
hardware.opengl.driSupport32Bit
= true;
The x11 login screen can be skipped entirely, automatically logging you into your window manager and desktop environment when you boot your computer.
This is especially helpful if you have disk encryption enabled. Since you already have to provide a password to decrypt your disk, entering a second password to login can be redundant.
To enable auto-login, you need to define your default window manager and desktop environment. If you wanted no desktop environment and i3 as your your window manager, you'd define:
services.xserver.displayManager.defaultSession
= "none+i3";
Every display manager in NixOS supports auto-login, here is an example
using lightdm for a user alice
:
services.xserver.displayManager.lightdm.enable
= true;services.xserver.displayManager.lightdm.autoLogin.enable
= true;services.xserver.displayManager.lightdm.autoLogin.user
= "alice";
The options are named identically for all other display managers.
NVIDIA provides a proprietary driver for its graphics cards that has better 3D performance than the X.org drivers. It is not enabled by default because it’s not free software. You can enable it as follows:
services.xserver.videoDrivers
= [ "nvidia" ];
Or if you have an older card, you may have to use one of the legacy drivers:
services.xserver.videoDrivers
= [ "nvidiaLegacy390" ];services.xserver.videoDrivers
= [ "nvidiaLegacy340" ];services.xserver.videoDrivers
= [ "nvidiaLegacy304" ];services.xserver.videoDrivers
= [ "nvidiaLegacy173" ];
You may need to reboot after enabling this driver to prevent a clash with other kernel modules.
AMD provides a proprietary driver for its graphics cards that has better 3D performance than the X.org drivers. It is not enabled by default because it’s not free software. You can enable it as follows:
services.xserver.videoDrivers
= [ "ati_unfree" ];
You will need to reboot after enabling this driver to prevent a clash with other kernel modules.
"amdgpu"
(both free).
Support for Synaptics touchpads (found in many laptops such as the Dell Latitude series) can be enabled as follows:
services.xserver.libinput.enable
= true;
The driver has many options (see Appendix A, Configuration Options). For instance, the following disables tap-to-click behavior:
services.xserver.libinput.tapping
= false;
Note: the use of services.xserver.synaptics
is deprecated
since NixOS 17.09.
GTK themes can be installed either to user profile or system-wide (via
environment.systemPackages
). To make Qt 5 applications
look similar to GTK2 ones, you can install qt5.qtbase.gtk
package into your system environment. It should work for all Qt 5 library
versions.
It is possible to install custom
XKB
keyboard layouts using the option
services.xserver.extraLayouts
.
As a first example, we are going to create a layout based on the basic US
layout, with an additional layer to type some greek symbols by pressing the
right-alt key.
To do this we are going to create a us-greek
file
with a xkb_symbols
section.
xkb_symbols "us-greek" { include "us(basic)" // includes the base US keys include "level3(ralt_switch)" // configures right alt as a third level switch key <LatA> { [ a, A, Greek_alpha ] }; key <LatB> { [ b, B, Greek_beta ] }; key <LatG> { [ g, G, Greek_gamma ] }; key <LatD> { [ d, D, Greek_delta ] }; key <LatZ> { [ z, Z, Greek_zeta ] }; };
To install the layout, the filepath, a description and the list of languages must be given:
services.xserver.extraLayouts
.us-greek = {
description = "US layout with alt-gr greek";
languages = [ "eng" ];
symbolsFile = /path/to/us-greek;
}
xkb_symbols
block.
The layout should now be installed and ready to use: try it by
running setxkbmap us-greek
and type
<alt>+a
. To change the default the usual
services.xserver.layout
option can still be used.
A layout can have several other components besides
xkb_symbols
, for example we will define new
keycodes for some multimedia key and bind these to some symbol.
Use the xev utility from
pkgs.xorg.xev
to find the codes of the keys of
interest, then create a media-key
file to hold
the keycodes definitions
xkb_keycodes "media" { <volUp> = 123; <volDown> = 456; }
Now use the newly define keycodes in media-sym
:
xkb_symbols "media" { key.type = "ONE_LEVEL"; key <volUp> { [ XF86AudioLowerVolume ] }; key <volDown> { [ XF86AudioRaiseVolume ] }; }
As before, to install the layout do
services.xserver.extraLayouts
.media = {
description = "Multimedia keys remapping";
languages = [ "eng" ];
symbolsFile = /path/to/media-key;
keycodesFile = /path/to/media-sym;
};
pkgs.writeText <filename> <content>
can be useful if you prefer to keep the layout definitions
inside the NixOS configuration.
Unfortunately, the Xorg server does not (currently) support setting a
keymap directly but relies instead on XKB rules to select the matching
components (keycodes, types, ...) of a layout. This means that components
other than symbols won't be loaded by default. As a workaround, you
can set the keymap using setxkbmap
at the start of the
session with:
services.xserver.displayManager.sessionCommands
= "setxkbmap -keycodes media";
If you are manually starting the X server, you should set the argument
-xkbdir /etc/X11/xkb
, otherwise X won't find your layout files.
For example with xinit run
$
xinit -- -xkbdir /etc/X11/xkb
To learn how to write layouts take a look at the XKB documentation . More example layouts can also be found here .
To enable the Xfce Desktop Environment, set
services.xserver.desktopManager.xfce.enable
= true;services.xserver.displayManager.defaultSession
= "xfce";
Optionally, picom can be enabled for nice graphical effects, some example settings:
services.picom = { enable = true; fade = true; inactiveOpacity = "0.9"; shadow = true; fadeDelta = 4; };
Some Xfce programs are not installed automatically. To install them manually
(system wide), put them into your
environment.systemPackages
from pkgs.xfce
.
If you'd like to add extra plugins to Thunar, add them to
services.xserver.desktopManager.xfce.thunarPlugins
.
You shouldn't just add them to environment.systemPackages
.
Even after enabling udisks2, volume management might not work. Thunar and/or the desktop takes time to show up. Thunar will spit out this kind of message on start (look at journalctl --user -b).
Thunar:2410): GVFS-RemoteVolumeMonitor-WARNING **: remote volume monitor with dbus name org.gtk.Private.UDisks2VolumeMonitor is not supported
This is caused by some needed GNOME services not running. This is all fixed by enabling "Launch GNOME services on startup" in the Advanced tab of the Session and Startup settings panel. Alternatively, you can run this command to do the same thing.
$
xfconf-query -c xfce4-session -p /compat/LaunchGNOME -s true
A log-out and re-log will be needed for this to take effect.
Table of Contents
This section describes how to configure networking components on your NixOS machine.
To facilitate network configuration, some desktop environments use NetworkManager. You can enable NetworkManager by setting:
networking.networkmanager.enable
= true;
some desktop managers (e.g., GNOME) enable NetworkManager automatically for you.
All users that should have permission to change network settings must belong
to the networkmanager
group:
users.users.alice.extraGroups = [ "networkmanager" ];
NetworkManager is controlled using either nmcli or
nmtui (curses-based terminal user interface). See their
manual pages for details on their usage. Some desktop environments (GNOME,
KDE) have their own configuration tools for NetworkManager. On XFCE, there is
no configuration tool for NetworkManager by default: by enabling programs.nm-applet.enable
, the
graphical applet will be installed and will launch automatically when the graphical session is started.
networking.networkmanager
and networking.wireless
(WPA Supplicant) can be used together if desired. To do this you need to instruct
NetworkManager to ignore those interfaces like:
networking.networkmanager.unmanaged
= [
"*" "except:type:wwan" "except:type:gsm"
];
Refer to the option description for the exact syntax and references to external documentation.
Secure shell (SSH) access to your machine can be enabled by setting:
services.openssh.enable
= true;
By default, root logins using a password are disallowed. They can be disabled
entirely by setting services.openssh.permitRootLogin
to
"no"
.
You can declaratively specify authorised RSA/DSA public keys for a user as follows:
users.users.alice.openssh.authorizedKeys.keys = [ "ssh-dss AAAAB3NzaC1kc3MAAACBAPIkGWVEt4..." ];
By default, NixOS uses DHCP (specifically, dhcpcd) to automatically configure network interfaces. However, you can configure an interface manually as follows:
networking.interfaces.eth0.ipv4.addresses = [ { address = "192.168.1.2"; prefixLength = 24; } ];
Typically you’ll also want to set a default gateway and set of name servers:
networking.defaultGateway
= "192.168.1.1";networking.nameservers
= [ "8.8.8.8" ];
interface-name
-cfg.service
.
The default gateway and name server configuration is performed by
network-setup.service
.
The host name is set using networking.hostName
:
networking.hostName
= "cartman";
The default host name is nixos
. Set it to the empty string
(""
) to allow the DHCP server to provide the host name.
IPv6 is enabled by default. Stateless address autoconfiguration is used to automatically assign IPv6 addresses to all interfaces. You can disable IPv6 support globally by setting:
networking.enableIPv6
= false;
You can disable IPv6 on a single interface using a normal sysctl (in this
example, we use interface eth0
):
boot.kernel.sysctl
."net.ipv6.conf.eth0.disable_ipv6" = true;
As with IPv4 networking interfaces are automatically configured via DHCPv6. You can configure an interface manually:
networking.interfaces.eth0.ipv6.addresses = [ { address = "fe00:aa:bb:cc::2"; prefixLength = 64; } ];
For configuring a gateway, optionally with explicitly specified interface:
networking.defaultGateway6
= {
address = "fe00::1";
interface = "enp0s3";
};
See Section 11.3, “IPv4 Configuration” for similar examples and additional information.
NixOS has a simple stateful firewall that blocks incoming connections and other unexpected packets. The firewall applies to both IPv4 and IPv6 traffic. It is enabled by default. It can be disabled as follows:
networking.firewall.enable
= false;
If the firewall is enabled, you can open specific TCP ports to the outside world:
networking.firewall.allowedTCPPorts
= [ 80 443 ];
Note that TCP port 22 (ssh) is opened automatically if the SSH daemon is
enabled (
). UDP ports can be opened through
services.openssh.enable
=
truenetworking.firewall.allowedUDPPorts
.
To open ranges of TCP ports:
networking.firewall.allowedTCPPortRanges
= [
{ from = 4000; to = 4007; }
{ from = 8000; to = 8010; }
];
Similarly, UDP port ranges can be opened through
networking.firewall.allowedUDPPortRanges
.
For a desktop installation using NetworkManager (e.g., GNOME), you just have
to make sure the user is in the networkmanager
group and you can
skip the rest of this section on wireless networks.
NixOS will start wpa_supplicant for you if you enable this setting:
networking.wireless.enable
= true;
NixOS lets you specify networks for wpa_supplicant declaratively:
networking.wireless.networks
= {
echelon = { # SSID with no spaces or special characters
psk = "abcdefgh";
};
"echelon's AP" = { # SSID with spaces and/or special characters
psk = "ijklmnop";
};
echelon = { # Hidden SSID
hidden = true;
psk = "qrstuvwx";
};
free.wifi = {}; # Public wireless network
};
Be aware that keys will be written to the nix store in plaintext! When no
networks are set, it will default to using a configuration file at
/etc/wpa_supplicant.conf
. You should edit this file
yourself to define wireless networks, WPA keys and so on (see wpa_supplicant.conf(5)).
If you are using WPA2 you can generate pskRaw key using wpa_passphrase:
$
wpa_passphrase ESSID PSK
network={
ssid="echelon"
#psk="abcdefgh"
psk=dca6d6ed41f4ab5a984c9f55f6f66d4efdc720ebf66959810f4329bb391c5435
}
networking.wireless.networks
= {
echelon = {
pskRaw = "dca6d6ed41f4ab5a984c9f55f6f66d4efdc720ebf66959810f4329bb391c5435";
};
}
or you can use it to directly generate the
wpa_supplicant.conf
:
#
wpa_passphrase ESSID PSK > /etc/wpa_supplicant.conf
After you have edited the wpa_supplicant.conf
, you need to
restart the wpa_supplicant service.
#
systemctl restart wpa_supplicant.service
You can use networking.localCommands
to specify shell
commands to be run at the end of network-setup.service
.
This is useful for doing network configuration not covered by the existing
NixOS modules. For instance, to statically configure an IPv6 address:
networking.localCommands
=
''
ip -6 addr add 2001:610:685:1::1/64 dev eth0
'';
Table of Contents
You can override the Linux kernel and associated packages using the option
boot.kernelPackages
. For instance, this selects the Linux
3.10 kernel:
boot.kernelPackages
= pkgs.linuxPackages_3_10;
Note that this not only replaces the kernel, but also packages that are specific to the kernel version, such as the NVIDIA video drivers. This ensures that driver packages are consistent with the kernel.
The default Linux kernel configuration should be fine for most users. You can see the configuration of your current kernel with the following command:
zcat /proc/config.gz
If you want to change the kernel configuration, you can use the
packageOverrides
feature (see
Section 6.1.1, “Customising Packages”). For instance, to enable support
for the kernel debugger KGDB:
nixpkgs.config.packageOverrides = pkgs: { linux_3_4 = pkgs.linux_3_4.override { extraConfig = '' KGDB y ''; }; };
extraConfig
takes a list of Linux kernel configuration
options, one per line. The name of the option should not include the prefix
CONFIG_
. The option value is typically
y
, n
or m
(to build
something as a kernel module).
Kernel modules for hardware devices are generally loaded automatically by
udev. You can force a module to be loaded via
boot.kernelModules
, e.g.
boot.kernelModules
= [ "fuse" "kvm-intel" "coretemp" ];
If the module is required early during the boot (e.g. to mount the root file
system), you can use boot.initrd.kernelModules
:
boot.initrd.kernelModules
= [ "cifs" ];
This causes the specified modules and their dependencies to be added to the initial ramdisk.
Kernel runtime parameters can be set through
boot.kernel.sysctl
, e.g.
boot.kernel.sysctl
."net.ipv4.tcp_keepalive_time" = 120;
sets the kernel’s TCP keepalive time to 120 seconds. To see the available parameters, run sysctl -a.
The first step before compiling the kernel is to generate an appropriate
.config
configuration. Either you pass your own config
via the configfile
setting of
linuxManualConfig
:
custom-kernel = super.linuxManualConfig { inherit (super) stdenv hostPlatform; inherit (linux_4_9) src; version = "${linux_4_9.version}-custom"; configfile = /home/me/my_kernel_config; allowImportFromDerivation = true; };
You can edit the config with this snippet (by default make menuconfig won't work out of the box on nixos):
nix-shell -E 'with import <nixpkgs> {}; kernelToOverride.overrideAttrs (o: {nativeBuildInputs=o.nativeBuildInputs ++ [ pkgconfig ncurses ];})'
or you can let nixpkgs generate the configuration. Nixpkgs generates it via
answering the interactive kernel utility make config. The
answers depend on parameters passed to
pkgs/os-specific/linux/kernel/generic.nix
(which you
can influence by overriding extraConfig, autoModules,
modDirVersion, preferBuiltin, extraConfig
).
mptcp93.override ({ name="mptcp-local"; ignoreConfigErrors = true; autoModules = false; kernelPreferBuiltin = true; enableParallelBuilding = true; extraConfig = '' DEBUG_KERNEL y FRAME_POINTER y KGDB y KGDB_SERIAL_CONSOLE y DEBUG_INFO y ''; });
When developing kernel modules it's often convenient to run edit-compile-run
loop as quickly as possible. See below snippet as an example of developing
mellanox
drivers.
$ nix-build '<nixpkgs>' -A linuxPackages.kernel.dev $ nix-shell '<nixpkgs>' -A linuxPackages.kernel $ unpackPhase $ cd linux-* $ make -C $dev/lib/modules/*/build M=$(pwd)/drivers/net/ethernet/mellanox modules # insmod ./drivers/net/ethernet/mellanox/mlx5/core/mlx5_core.ko
Pantheon is the desktop environment created for the elementary OS distribution. It is written from scratch in Vala, utilizing GNOME technologies with GTK 3 and Granite.
All of Pantheon is working in NixOS and the applications should be available, aside from a few exceptions. To enable Pantheon, set
services.xserver.desktopManager.pantheon.enable
= true;
This automatically enables LightDM and Pantheon's LightDM greeter. If you'd like to disable this, set
services.xserver.displayManager.lightdm.greeters.pantheon.enable
= false;services.xserver.displayManager.lightdm.enable
= false;
but please be aware using Pantheon without LightDM as a display manager will break screenlocking from the UI. The NixOS module for Pantheon installs all of Pantheon's default applications. If you'd like to not install Pantheon's apps, set
services.pantheon.apps.enable
= false;
You can also use environment.pantheon.excludePackages
to remove any other app (like geary).
Wingpanel and Switchboard work differently than they do in other distributions, as far as using plugins. You cannot install a plugin globally (like with environment.systemPackages
) to start using it. You should instead be using the following options:
to configure the programs with plugs or indicators.
The difference in NixOS is both these programs are patched to load plugins from a directory that is the value of an environment variable. All of which is controlled in Nix. If you need to configure the particular packages manually you can override the packages like:
wingpanel-with-indicators.override { indicators = [ pkgs.some-special-indicator ]; }; switchboard-with-plugs.override { plugs = [ pkgs.some-special-plug ]; };
please note that, like how the NixOS options describe these as extra plugins, this would only add to the default plugins included with the programs. If for some reason you'd like to configure which plugins to use exactly, both packages have an argument for this:
wingpanel-with-indicators.override { useDefaultIndicators = false; indicators = specialListOfIndicators; }; switchboard-with-plugs.override { useDefaultPlugs = false; plugs = specialListOfPlugs; };
this could be most useful for testing a particular plug-in in isolation.
Open Switchboard and go to: Administration → About → Restore Default Settings → . This will reset any dconf settings to their Pantheon defaults. Note this could reset certain GNOME specific preferences if that desktop was used prior.
This is a known issue and there is no known workaround.
AppCenter has been available since 20.03, but it is of little use. This is because there is no functioning PackageKit backend for Nix 2.0. In the near future you will be able to install Flatpak applications from AppCenter on NixOS. See this issue.
Table of Contents
Matomo is a real-time web analytics application. This module configures php-fpm as backend for Matomo, optionally configuring an nginx vhost as well.
An automatic setup is not suported by Matomo, so you need to configure Matomo itself in the browser-based Matomo setup.
You also need to configure a MariaDB or MySQL database and -user for Matomo yourself, and enter those credentials in your browser. You can use passwordless database authentication via the UNIX_SOCKET authentication plugin with the following SQL commands:
# For MariaDB INSTALL PLUGIN unix_socket SONAME 'auth_socket'; CREATE DATABASE matomo; CREATE USER 'matomo'@'localhost' IDENTIFIED WITH unix_socket; GRANT ALL PRIVILEGES ON matomo.* TO 'matomo'@'localhost'; # For MySQL INSTALL PLUGIN auth_socket SONAME 'auth_socket.so'; CREATE DATABASE matomo; CREATE USER 'matomo'@'localhost' IDENTIFIED WITH auth_socket; GRANT ALL PRIVILEGES ON matomo.* TO 'matomo'@'localhost';
Then fill in matomo
as database user and database name,
and leave the password field blank. This authentication works by allowing
only the matomo
unix user to authenticate as the
matomo
database user (without needing a password), but no
other users. For more information on passwordless login, see
https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/.
Of course, you can use password based authentication as well, e.g. when the database is not on the same host.
This module comes with the systemd service
matomo-archive-processing.service
and a timer that
automatically triggers archive processing every hour. This means that you
can safely
disable browser triggers for Matomo archiving at
Administration > System > General Settings
.
With automatic archive processing, you can now also enable to
delete old visitor logs at Administration > System >
Privacy
, but make sure that you run systemctl start
matomo-archive-processing.service
at least once without errors if
you have already collected data before, so that the reports get archived
before the source data gets deleted.
You only need to take backups of your MySQL database and the
/var/lib/matomo/config/config.ini.php
file. Use a user
in the matomo
group or root to access the file. For more
information, see
https://matomo.org/faq/how-to-install/faq_138/.
Matomo will warn you that the JavaScript tracker is not writable. This is because it's located in the read-only nix store. You can safely ignore this, unless you need a plugin that needs JavaScript tracker access.
You can use other web servers by forwarding calls for
index.php
and piwik.php
to the
services.phpfpm.pools.<name>.socket
fastcgi unix socket. You can use
the nginx configuration in the module code as a reference to what else
should be configured.
Table of Contents
Nextcloud is an open-source,
self-hostable cloud platform. The server setup can be automated using
services.nextcloud. A
desktop client is packaged at pkgs.nextcloud-client
.
Nextcloud is a PHP-based application which requires an HTTP server
(services.nextcloud
optionally supports
services.nginx
)
and a database (it's recommended to use
services.postgresql
).
A very basic configuration may look like this:
{ pkgs, ... }: { services.nextcloud = { enable = true; hostName = "nextcloud.tld"; nginx.enable = true; config = { dbtype = "pgsql"; dbuser = "nextcloud"; dbhost = "/run/postgresql"; # nextcloud will add /.s.PGSQL.5432 by itself dbname = "nextcloud"; adminpassFile = "/path/to/admin-pass-file"; adminuser = "root"; }; }; services.postgresql = { enable = true; ensureDatabases = [ "nextcloud" ]; ensureUsers = [ { name = "nextcloud"; ensurePermissions."DATABASE nextcloud" = "ALL PRIVILEGES"; } ]; }; # ensure that postgres is running *before* running the setup systemd.services."nextcloud-setup" = { requires = ["postgresql.service"]; after = ["postgresql.service"]; }; networking.firewall.allowedTCPPorts = [ 80 443 ]; }
The options hostName
and nginx.enable
are used internally to configure an HTTP server using
PHP-FPM
and nginx
. The config
attribute set is
used by the imperative installer and all values are written to an additional file
to ensure that changes can be applied by changing the module's options.
In case the application serves multiple domains (those are checked with
$_SERVER['HTTP_HOST']
)
it's needed to add them to
services.nextcloud.config.extraTrustedDomains
.
Auto updates for Nextcloud apps can be enabled using
services.nextcloud.autoUpdateApps
.
Unfortunately Nextcloud appears to be very stateful when it comes to
managing its own configuration. The config file lives in the home directory
of the nextcloud
user (by default
/var/lib/nextcloud/config/config.php
) and is also used to
track several states of the application (e.g. whether installed or not).
All configuration parameters are also stored in
/var/lib/nextcloud/config/override.config.php
which is generated by
the module and linked from the store to ensure that all values from config.php
can be modified by the module.
However config.php
manages the application's state and shouldn't be touched
manually because of that.
config.php
! This file
tracks the application's state and a deletion can cause unwanted
side-effects!nextcloud-occ
maintenance:install
! This command tries to install the application
and can cause unwanted side-effects!
Nextcloud doesn't allow to move more than one major-version forward. If you're e.g. on
v16
, you cannot upgrade to v18
, you need to upgrade to
v17
first. This is ensured automatically as long as the
stateVersion is declared properly. In that case
the oldest version available (one major behind the one from the previous NixOS
release) will be selected by default and the module will generate a warning that reminds
the user to upgrade to latest Nextcloud after that deploy.
As stated in the previous paragraph, we must provide a clean upgrade-path for Nextcloud since it cannot move more than one major version forward on a single upgrade. This chapter adds some notes how Nextcloud updates should be rolled out in the future.
While minor and patch-level updates are no problem and can be done directly in the
package-expression (and should be backported to supported stable branches after that),
major-releases should be added in a new attribute (e.g. Nextcloud v19.0.0
should be available in nixpkgs
as pkgs.nextcloud19
).
To provide simple upgrade paths it's generally useful to backport those as well to stable
branches. As long as the package-default isn't altered, this won't break existing setups.
After that, the versioning-warning in the nextcloud
-module should be
updated to make sure that the
package-option selects the latest version
on fresh setups.
If major-releases will be abandoned by upstream, we should check first if those are needed
in NixOS for a safe upgrade-path before removing those. In that case we shold keep those
packages, but mark them as insecure in an expression like this (in
<nixpkgs/pkgs/servers/nextcloud/default.nix>
):
/* ... */ { nextcloud17 = generic { version = "17.0.x"; sha256 = "0000000000000000000000000000000000000000000000000000"; insecure = true; }; }
Table of Contents
Grocy is a web-based self-hosted groceries & household management solution for your home.
A very basic configuration may look like this:
{ pkgs, ... }: { services.grocy = { enable = true; hostName = "grocy.tld"; }; }
This configures a simple vhost using nginx
which listens to grocy.tld
with fully configured ACME/LE (this can be
disabled by setting services.grocy.nginx.enableSSL
to false
). After the initial setup the credentials admin:admin
can be used to login.
The application's state is persisted at /var/lib/grocy/grocy.db
in a
sqlite3 database. The migration is applied when requesting the /
-route
of the application.
The configuration for grocy
is located at /etc/grocy/config.php
.
By default, the following settings can be defined in the NixOS-configuration:
{ pkgs, ... }: { services.grocy.settings = { # The default currency in the system for invoices etc. # Please note that exchange rates aren't taken into account, this # is just the setting for what's shown in the frontend. currency = "EUR"; # The display language (and locale configuration) for grocy. culture = "de"; calendar = { # Whether or not to show the week-numbers # in the calendar. showWeekNumber = true; # Index of the first day to be shown in the calendar (0=Sunday, 1=Monday, # 2=Tuesday and so on). firstDayOfWeek = 2; }; }; }
If you want to alter the configuration file on your own, you can do this manually with an expression like this:
{ lib, ... }: { environment.etc."grocy/config.php".text = lib.mkAfter '' // Arbitrary PHP code in grocy's configuration file ''; }
Prometheus exporters provide metrics for the prometheus monitoring system.
One of the most common exporters is the node exporter, it provides hardware and OS metrics from the host it's running on. The exporter could be configured as follows:
services.prometheus.exporters.node = { enable = true; enabledCollectors = [ "logind" "systemd" ]; disabledCollectors = [ "textfile" ]; openFirewall = true; firewallFilter = "-i br0 -p tcp -m tcp --dport 9100"; };
It should now serve all metrics from the collectors that are explicitly
enabled and the ones that are
enabled
by default, via http under /metrics
. In this
example the firewall should just allow incoming connections to the
exporter's port on the bridge interface br0
(this would
have to be configured seperately of course). For more information about
configuration see man configuration.nix
or search through
the
available
options.
To add a new exporter, it has to be packaged first (see
nixpkgs/pkgs/servers/monitoring/prometheus/
for
examples), then a module can be added. The postfix exporter is used in this
example:
Some default options for all exporters are provided by
nixpkgs/nixos/modules/services/monitoring/prometheus/exporters.nix
:
enable
port
listenAddress
extraFlags
openFirewall
firewallFilter
user
group
As there is already a package available, the module can now be added. This
is accomplished by adding a new file to the
nixos/modules/services/monitoring/prometheus/exporters/
directory, which will be called postfix.nix and contains all exporter
specific options and configuration:
# nixpgs/nixos/modules/services/prometheus/exporters/postfix.nix { config, lib, pkgs, options }: with lib; let # for convenience we define cfg here cfg = config.services.prometheus.exporters.postfix; in { port = 9154; # The postfix exporter listens on this port by default # `extraOpts` is an attribute set which contains additional options # (and optional overrides for default options). # Note that this attribute is optional. extraOpts = { telemetryPath = mkOption { type = types.str; default = "/metrics"; description = '' Path under which to expose metrics. ''; }; logfilePath = mkOption { type = types.path; default = /var/log/postfix_exporter_input.log; example = /var/log/mail.log; description = '' Path where Postfix writes log entries. This file will be truncated by this exporter! ''; }; showqPath = mkOption { type = types.path; default = /var/spool/postfix/public/showq; example = /var/lib/postfix/queue/public/showq; description = '' Path at which Postfix places its showq socket. ''; }; }; # `serviceOpts` is an attribute set which contains configuration # for the exporter's systemd service. One of # `serviceOpts.script` and `serviceOpts.serviceConfig.ExecStart` # has to be specified here. This will be merged with the default # service confiuration. # Note that by default 'DynamicUser' is 'true'. serviceOpts = { serviceConfig = { DynamicUser = false; ExecStart = '' ${pkgs.prometheus-postfix-exporter}/bin/postfix_exporter \ --web.listen-address ${cfg.listenAddress}:${toString cfg.port} \ --web.telemetry-path ${cfg.telemetryPath} \ ${concatStringsSep " \\\n " cfg.extraFlags} ''; }; }; }
This should already be enough for the postfix exporter. Additionally one
could now add assertions and conditional default values. This can be done
in the 'meta-module' that combines all exporter definitions and generates
the submodules:
nixpkgs/nixos/modules/services/prometheus/exporters.nix
Should an exporter option change at some point, it is possible to add
information about the change to the exporter definition similar to
nixpkgs/nixos/modules/rename.nix
:
{ config, lib, pkgs, options }: with lib; let cfg = config.services.prometheus.exporters.nginx; in { port = 9113; extraOpts = { # additional module options # ... }; serviceOpts = { # service configuration # ... }; imports = [ # 'services.prometheus.exporters.nginx.telemetryEndpoint' -> 'services.prometheus.exporters.nginx.telemetryPath' (mkRenamedOptionModule [ "telemetryEndpoint" ] [ "telemetryPath" ]) # removed option 'services.prometheus.exporters.nginx.insecure' (mkRemovedOptionModule [ "insecure" ] '' This option was replaced by 'prometheus.exporters.nginx.sslVerify' which defaults to true. '') ({ options.warnings = options.warnings; }) ]; }
Table of Contents
WeeChat is a fast and extensible IRC client.
By default, the module creates a
systemd
unit which runs the chat client in a detached
screen
session.
This can be done by enabling the weechat
service:
{ ... }: { services.weechat.enable = true; }
The service is managed by a dedicated user named weechat
in the state directory /var/lib/weechat
.
WeeChat runs in a screen session owned by a dedicated user. To explicitly
allow your another user to attach to this session, the
screenrc
needs to be tweaked by adding
multiuser
support:
{ programs.screen.screenrc = '' multiuser on acladd normal_user ''; }
Now, the session can be re-attached like this:
screen -x weechat/weechat-screen
The session name can be changed using services.weechat.sessionName.
Table of Contents
Taskserver is the server component of Taskwarrior, a free and open source todo list application.
Upstream documentation: https://taskwarrior.org/docs/#taskd
Taskserver does all of its authentication via TLS using client certificates, so you either need to roll your own CA or purchase a certificate from a known CA, which allows creation of client certificates. These certificates are usually advertised as “server certificates”.
So in order to make it easier to handle your own CA, there is a helper tool called nixos-taskserver which manages the custom CA along with Taskserver organisations, users and groups.
While the client certificates in Taskserver only authenticate whether a user is allowed to connect, every user has its own UUID which identifies it as an entity.
With nixos-taskserver the client certificate is created along with the UUID of the user, so it handles all of the credentials needed in order to setup the Taskwarrior client to work with a Taskserver.
Because Taskserver by default only provides scripts to setup users
imperatively, the nixos-taskserver tool is used for
addition and deletion of organisations along with users and groups defined
by services.taskserver.organisations
and as well for
imperative set up.
The tool is designed to not interfere if the command is used to manually set up some organisations, users or groups.
For example if you add a new organisation using nixos-taskserver
org add foo, the organisation is not modified and deleted no
matter what you define in
services.taskserver.organisations
, even if you're adding
the same organisation in that option.
The tool is modelled to imitate the official taskd
command, documentation for each subcommand can be shown by using the
--help
switch.
Everything is done according to what you specify in the module options, however in order to set up a Taskwarrior client for synchronisation with a Taskserver instance, you have to transfer the keys and certificates to the client machine.
This is done using nixos-taskserver user export $orgname $username which is printing a shell script fragment to stdout which can either be used verbatim or adjusted to import the user on the client machine.
For example, let's say you have the following configuration:
{services.taskserver.enable
= true;services.taskserver.fqdn
= "server";services.taskserver.listenHost
= "::"; services.taskserver.organisations.my-company.users = [ "alice" ]; }
This creates an organisation called my-company
with the
user alice
.
Now in order to import the alice
user to another machine
alicebox
, all we need to do is something like this:
$
ssh server nixos-taskserver user export my-company alice | sh
Of course, if no SSH daemon is available on the server you can also copy & paste it directly into a shell.
After this step the user should be set up and you can start synchronising
your tasks for the first time with task sync init on
alicebox
.
Subsequent synchronisation requests merely require the command task sync after that stage.
If you set any options within service.taskserver.pki.manual.*, nixos-taskserver won't issue certificates, but you can still use it for adding or removing user accounts.
Table of Contents
Matrix is an open standard for interoperable, decentralised, real-time communication over IP. It can be used to power Instant Messaging, VoIP/WebRTC signalling, Internet of Things communication - or anywhere you need a standard HTTP API for publishing and subscribing to data whilst tracking the conversation history.
This chapter will show you how to set up your own, self-hosted Matrix homeserver using the Synapse reference homeserver, and how to serve your own copy of the Riot web client. See the Try Matrix Now! overview page for links to Riot Apps for Android and iOS, desktop clients, as well as bridges to other networks and other projects around Matrix.
Synapse is
the reference homeserver implementation of Matrix from the core development
team at matrix.org. The following configuration example will set up a
synapse server for the example.org
domain, served from
the host myhostname.example.org
. For more information,
please refer to the
installation instructions of Synapse .
let fqdn = let join = hostName: domain: hostName + optionalString (domain != null) ".${domain}"; in join config.networking.hostName config.networking.domain; in { networking = { hostName = "myhostname"; domain = "example.org"; }; networking.firewall.allowedTCPPorts = [ 80 443 ]; services.postgresql.enable = true; services.postgresql.initialScript = '' CREATE ROLE "matrix-synapse" WITH LOGIN PASSWORD 'synapse'; CREATE DATABASE "matrix-synapse" WITH OWNER "matrix-synapse" TEMPLATE template0 LC_COLLATE = "C" LC_CTYPE = "C"; ''; services.nginx = { enable = true; # only recommendedProxySettings and recommendedGzipSettings are strictly required, # but the rest make sense as well recommendedTlsSettings = true; recommendedOptimisation = true; recommendedGzipSettings = true; recommendedProxySettings = true; virtualHosts = { # This host section can be placed on a different host than the rest, # i.e. to delegate from the host being accessible as ${config.networking.domain} # to another host actually running the Matrix homeserver. "${config.networking.domain}" = { locations."= /.well-known/matrix/server".extraConfig = let # use 443 instead of the default 8448 port to unite # the client-server and server-server port for simplicity server = { "m.server" = "${fqdn}:443"; }; in '' add_header Content-Type application/json; return 200 '${builtins.toJSON server}'; ''; locations."= /.well-known/matrix/client".extraConfig = let client = { "m.homeserver" = { "base_url" = "https://${fqdn}"; }; "m.identity_server" = { "base_url" = "https://vector.im"; }; }; # ACAO required to allow riot-web on any URL to request this json file in '' add_header Content-Type application/json; add_header Access-Control-Allow-Origin *; return 200 '${builtins.toJSON client}'; ''; }; # Reverse proxy for Matrix client-server and server-server communication ${fqdn} = { enableACME = true; forceSSL = true; # Or do a redirect instead of the 404, or whatever is appropriate for you. # But do not put a Matrix Web client here! See the Riot Web section below. locations."/".extraConfig = '' return 404; ''; # forward all Matrix API calls to the synapse Matrix homeserver locations."/_matrix" = { proxyPass = "http://[::1]:8008"; # without a trailing / }; }; }; }; services.matrix-synapse = { enable = true; server_name = config.networking.domain; listeners = [ { port = 8008; bind_address = "::1"; type = "http"; tls = false; x_forwarded = true; resources = [ { names = [ "client" "federation" ]; compress = false; } ]; } ]; }; };
If the A
and AAAA
DNS records on
example.org
do not point on the same host as the records
for myhostname.example.org
, you can easily move the
/.well-known
virtualHost section of the code to the host that
is serving example.org
, while the rest stays on
myhostname.example.org
with no other changes required.
This pattern also allows to seamlessly move the homeserver from
myhostname.example.org
to
myotherhost.example.org
by only changing the
/.well-known
redirection target.
If you want to run a server with public registration by anybody, you can
then enable services.matrix-synapse.enable_registration =
true;
. Otherwise, or you can generate a registration secret with
pwgen -s 64 1 and set it with
services.matrix-synapse.registration_shared_secret
. To
create a new user or admin, run the following after you have set the secret
and have rebuilt NixOS:
$
nix run nixpkgs.matrix-synapse$
register_new_matrix_user -kyour-registration-shared-secret
http://localhost:8008New user localpart:
your-username
Password:
Confirm password:
Make admin [no]:
Success!
In the example, this would create a user with the Matrix Identifier
@your-username:example.org
. Note that the registration
secret ends up in the nix store and therefore is world-readable by any user
on your machine, so it makes sense to only temporarily activate the
registration_shared_secret
option until a better solution for NixOS is in place.
Riot Web is
the reference web client for Matrix and developed by the core team at
matrix.org. The following snippet can be optionally added to the code before
to complete the synapse installation with a web client served at
https://riot.myhostname.example.org
and
https://riot.example.org
. Alternatively, you can use the hosted
copy at https://riot.im/app,
or use other web clients or native client applications. Due to the
/.well-known
urls set up done above, many clients should
fill in the required connection details automatically when you enter your
Matrix Identifier. See
Try
Matrix Now! for a list of existing clients and their supported
featureset.
{ services.nginx.virtualHosts."riot.${fqdn}" = { enableACME = true; forceSSL = true; serverAliases = [ "riot.${config.networking.domain}" ]; root = pkgs.riot-web.override { conf = { default_server_config."m.homeserver" = { "base_url" = "${config.networking.domain}"; "server_name" = "${fqdn}"; }; }; }; }; }
Note that the Riot developers do not recommend running Riot and your Matrix
homeserver on the same fully-qualified domain name for security reasons. In
the example, this means that you should not reuse the
myhostname.example.org
virtualHost to also serve Riot,
but instead serve it on a different subdomain, like
riot.example.org
in the example. See the
Riot
Important Security Notes for more information on this subject.
Table of Contents
Gitlab is a feature-rich git hosting service.
The gitlab service exposes only an Unix socket at
/run/gitlab/gitlab-workhorse.socket
. You need to
configure a webserver to proxy HTTP requests to the socket.
For instance, the following configuration could be used to use nginx as frontend proxy:
services.nginx = { enable = true; recommendedGzipSettings = true; recommendedOptimisation = true; recommendedProxySettings = true; recommendedTlsSettings = true; virtualHosts."git.example.com" = { enableACME = true; forceSSL = true; locations."/".proxyPass = "http://unix:/run/gitlab/gitlab-workhorse.socket"; }; };
Gitlab depends on both PostgreSQL and Redis and will automatically enable both services. In the case of PostgreSQL, a database and a role will be created.
The default state dir is /var/gitlab/state
. This is where
all data like the repositories and uploads will be stored.
A basic configuration with some custom settings could look like this:
services.gitlab = { enable = true; databasePasswordFile = "/var/keys/gitlab/db_password"; initialRootPasswordFile = "/var/keys/gitlab/root_password"; https = true; host = "git.example.com"; port = 443; user = "git"; group = "git"; smtp = { enable = true; address = "localhost"; port = 25; }; secrets = { dbFile = "/var/keys/gitlab/db"; secretFile = "/var/keys/gitlab/secret"; otpFile = "/var/keys/gitlab/otp"; jwsFile = "/var/keys/gitlab/jws"; }; extraConfig = { gitlab = { email_from = "gitlab-no-reply@example.com"; email_display_name = "Example GitLab"; email_reply_to = "gitlab-no-reply@example.com"; default_projects_features = { builds = false; }; }; }; };
If you're setting up a new Gitlab instance, generate new
secrets. You for instance use tr -dc A-Za-z0-9 <
/dev/urandom | head -c 128 > /var/keys/gitlab/db
to
generate a new db secret. Make sure the files can be read by, and
only by, the user specified by services.gitlab.user. Gitlab
encrypts sensitive data stored in the database. If you're restoring
an existing Gitlab instance, you must specify the secrets secret
from config/secrets.yml
located in your Gitlab
state folder.
Refer to Appendix A, Configuration Options for all available configuration options for the services.gitlab module.
You can run Gitlab's rake tasks with gitlab-rake
which
will be available on the system when gitlab is enabled. You will have to run
the command as the user that you configured to run gitlab with.
For example, to backup a Gitlab instance:
$
sudo -u git -H gitlab-rake gitlab:backup:create
A list of all availabe rake tasks can be obtained by running:
$
sudo -u git -H gitlab-rake -T
Trezor is an open-source cryptocurrency hardware wallet and security token allowing secure storage of private keys.
It offers advanced features such U2F two-factor authorization, SSH login through Trezor SSH agent, GPG and a password manager. For more information, guides and documentation, see https://wiki.trezor.io.
To enable Trezor support, add the following to your configuration.nix
:
services.trezord.enable
= true;
This will add all necessary udev rules and start Trezor Bridge.
Emacs is an extensible, customizable, self-documenting real-time display editor — and more. At its core is an interpreter for Emacs Lisp, a dialect of the Lisp programming language with extensions to support text editing.
Emacs runs within a graphical desktop environment using the X Window System, but works equally well on a text terminal. Under macOS, a "Mac port" edition is available, which uses Apple's native GUI frameworks.
Nixpkgs provides a superior environment for running Emacs. It's simple to create custom builds by overriding the default packages. Chaotic collections of Emacs Lisp code and extensions can be brought under control using declarative package management. NixOS even provides a systemd user service for automatically starting the Emacs daemon.
Emacs can be installed in the normal way for Nix (see Chapter 6, Package Management). In addition, a NixOS service can be enabled.
Nixpkgs defines several basic Emacs packages.
The following are attributes belonging to the pkgs
set:
emacs
,
emacs25
The latest stable version of Emacs 25 using the GTK 2 widget toolkit.
emacs25-nox
Emacs 25 built without any dependency on X11 libraries.
emacsMacport
,
emacs25Macport
Emacs 25 with the "Mac port" patches, providing a more native look and feel under macOS.
If those aren't suitable, then the following imitation Emacs editors are also available in Nixpkgs: Zile, mg, Yi, jmacs.
Emacs includes an entire ecosystem of functionality beyond text editing, including a project planner, mail and news reader, debugger interface, calendar, and more.
Most extensions are gotten with the Emacs packaging system
(package.el
) from
Emacs Lisp Package Archive
(ELPA),
MELPA,
MELPA Stable, and
Org ELPA. Nixpkgs is
regularly updated to mirror all these archives.
Under NixOS, you can continue to use
package-list-packages
and
package-install
to install packages. You can also
declare the set of Emacs packages you need using the derivations from
Nixpkgs. The rest of this section discusses declarative installation of
Emacs packages through nixpkgs.
The first step to declare the list of packages you want in your Emacs
installation is to create a dedicated derivation. This can be done in a
dedicated emacs.nix
file such as:
Example 23.1. Nix expression to build Emacs with packages (emacs.nix
)
/* This is a nix expression to build Emacs and some Emacs packages I like from source on any distribution where Nix is installed. This will install all the dependencies from the nixpkgs repository and build the binary files without interfering with the host distribution. To build the project, type the following from the current directory: $ nix-build emacs.nix To run the newly compiled executable: $ ./result/bin/emacs */ { pkgs ? import <nixpkgs> {} }: let myEmacs = pkgs.emacs; emacsWithPackages = (pkgs.emacsPackagesGen myEmacs).emacsWithPackages; in emacsWithPackages (epkgs: (with epkgs.melpaStablePackages; [ magit # ; Integrate git <C-x g> zerodark-theme # ; Nicolas' theme ]) ++ (with epkgs.melpaPackages; [ undo-tree # ; <C-x u> to show the undo tree zoom-frm # ; increase/decrease font size for all buffers %lt;C-x C-+> ]) ++ (with epkgs.elpaPackages; [ auctex # ; LaTeX mode beacon # ; highlight my cursor when scrolling nameless # ; hide current package name everywhere in elisp code ]) ++ [ pkgs.notmuch # From main packages set ])
The first non-comment line in this file ( | |
The | |
This generates an | |
The rest of the file specifies the list of packages to install. In the
example, two packages ( | |
Two packages ( | |
Three packages are taken from GNU ELPA. | |
|
The result of this configuration will be an emacs
command which launches Emacs with all of your chosen packages in the
load-path
.
You can check that it works by executing this in a terminal:
$
nix-build emacs.nix$
./result/bin/emacs -q
and then typing M-x package-initialize
. Check that you
can use all the packages you want in this Emacs instance. For example, try
switching to the zerodark theme through M-x load-theme <RET>
zerodark <RET> y
.
A few popular extensions worth checking out are: auctex, company, edit-server, flycheck, helm, iedit, magit, multiple-cursors, projectile, and yasnippet.
The list of available packages in the various ELPA repositories can be seen with the following commands:
Example 23.2. Querying Emacs packages
nix-env -f "<nixpkgs>" -qaP -A emacsPackages.elpaPackages nix-env -f "<nixpkgs>" -qaP -A emacsPackages.melpaPackages nix-env -f "<nixpkgs>" -qaP -A emacsPackages.melpaStablePackages nix-env -f "<nixpkgs>" -qaP -A emacsPackages.orgPackages
If you are on NixOS, you can install this particular Emacs for all users by
adding it to the list of system packages (see
Section 6.1, “Declarative Package Management”). Simply modify your file
configuration.nix
to make it contain:
Example 23.3. Custom Emacs in configuration.nix
{ environment.systemPackages = [ # [...] (import /path/to/emacs.nix { inherit pkgs; }) ]; }
In this case, the next nixos-rebuild switch will take
care of adding your emacs to the PATH
environment variable (see Chapter 3, Changing the Configuration).
If you are not on NixOS or want to install this particular Emacs only for
yourself, you can do so by adding it to your
~/.config/nixpkgs/config.nix
(see
Nixpkgs
manual):
Example 23.4. Custom Emacs in ~/.config/nixpkgs/config.nix
{ packageOverrides = super: let self = super.pkgs; in { myemacs = import /path/to/emacs.nix { pkgs = self; }; }; }
In this case, the next nix-env -f '<nixpkgs>' -iA
myemacs
will take care of adding your emacs to the
PATH
environment variable.
If you want, you can tweak the Emacs package itself from your
emacs.nix
. For example, if you want to have a
GTK 3-based Emacs instead of the default GTK 2-based binary and remove the
automatically generated emacs.desktop
(useful is you
only use emacsclient), you can change your file
emacs.nix
in this way:
Example 23.5. Custom Emacs build
{ pkgs ? import <nixpkgs> {} }: let myEmacs = (pkgs.emacs.override { # Use gtk3 instead of the default gtk2 withGTK3 = true; withGTK2 = false; }).overrideAttrs (attrs: { # I don't want emacs.desktop file because I only use # emacsclient. postInstall = (attrs.postInstall or "") + '' rm $out/share/applications/emacs.desktop ''; }); in [...]
After building this file as shown in Example 23.1, “Nix expression to build Emacs with packages (emacs.nix
)”, you
will get an GTK 3-based Emacs binary pre-loaded with your favorite packages.
NixOS provides an optional systemd service which launches Emacs daemon with the user's login session.
Source:
modules/services/editors/emacs.nix
To install and enable the systemd user service for Emacs
daemon, add the following to your configuration.nix
:
services.emacs.enable
= true;services.emacs.package
= import /home/cassou/.emacs.d { pkgs = pkgs; };
The services.emacs.package
option allows a custom
derivation to be used, for example, one created by
emacsWithPackages
.
Ensure that the Emacs server is enabled for your user's Emacs
configuration, either by customizing the server-mode
variable, or by adding (server-start)
to
~/.emacs.d/init.el
.
To start the daemon, execute the following:
$
nixos-rebuild switch # to activate the new configuration.nix$
systemctl --user daemon-reload # to force systemd reload$
systemctl --user start emacs.service # to start the Emacs daemon
The server should now be ready to serve Emacs clients.
Ensure that the emacs server is enabled, either by customizing the
server-mode
variable, or by adding
(server-start)
to ~/.emacs
.
To connect to the emacs daemon, run one of the following:
emacsclient FILENAME emacsclient --create-frame # opens a new frame (window) emacsclient --create-frame --tty # opens a new frame on the current terminal
EDITOR
variable
If services.emacs.defaultEditor
is
true
, the EDITOR
variable will be set
to a wrapper script which launches emacsclient.
Any setting of EDITOR
in the shell config files will
override services.emacs.defaultEditor
. To make sure
EDITOR
refers to the Emacs wrapper script, remove any
existing EDITOR
assignment from
.profile
, .bashrc
,
.zshenv
or any other shell config file.
If you have formed certain bad habits when editing files, these can be corrected with a shell alias to the wrapper script:
alias vi=$EDITOR
In general, systemd user services are globally enabled
by symlinks in /etc/systemd/user
. In the case where
Emacs daemon is not wanted for all users, it is possible to install the
service but not globally enable it:
services.emacs.enable
= false;services.emacs.install
= true;
To enable the systemd user service for just the currently logged in user, run:
systemctl --user enable emacs
This will add the symlink
~/.config/systemd/user/emacs.service
.
The Emacs init file should be changed to load the extension packages at startup:
Example 23.6. Package initialization in .emacs
(require 'package) ;; optional. makes unpure packages archives unavailable (setq package-archives nil) (setq package-enable-at-startup nil) (package-initialize)
After the declarative emacs package configuration has been tested,
previously downloaded packages can be cleaned up by removing
~/.emacs.d/elpa
(do make a backup first, in case you
forgot a package).
Of interest may be melpaPackages.nix-mode
, which
provides syntax highlighting for the Nix language. This is particularly
convenient if you regularly edit Nix files.
You can use woman
to get completion of all available
man pages. For example, type M-x woman <RET> nixos-rebuild
<RET>.
Emacs includes nXML, a major-mode for validating and editing XML documents. When editing DocBook 5.0 documents, such as this one, nXML needs to be configured with the relevant schema, which is not included.
To install the DocBook 5.0 schemas, either add
pkgs.docbook5
to
environment.systemPackages
(NixOS), or run
nix-env -f '<nixpkgs>' -iA docbook5
(Nix).
Then customize the variable rng-schema-locating-files
to
include ~/.emacs.d/schemas.xml
and put the following
text into that file:
Example 23.7. nXML Schema Configuration (~/.emacs.d/schemas.xml
)
<?xml version="1.0"?> <!-- To let emacs find this file, evaluate: (add-to-list 'rng-schema-locating-files "~/.emacs.d/schemas.xml") --> <locatingRules xmlns="http://thaiopensource.com/ns/locating-rules/1.0"> <!-- Use this variation if pkgs.docbook5 is added to environment.systemPackages --> <namespace ns="http://docbook.org/ns/docbook" uri="/run/current-system/sw/share/xml/docbook-5.0/rng/docbookxi.rnc"/> <!-- Use this variation if installing schema with "nix-env -iA pkgs.docbook5". <namespace ns="http://docbook.org/ns/docbook" uri="../.nix-profile/share/xml/docbook-5.0/rng/docbookxi.rnc"/> --> </locatingRules>
Source:
modules/services/desktop/flatpak.nix
Upstream documentation: https://github.com/flatpak/flatpak/wiki
Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux.
To enable Flatpak, add the following to your
configuration.nix
:
services.flatpak.enable
= true;
For the sandboxed apps to work correctly, desktop integration portals need to
be installed. If you run GNOME, this will be handled automatically for you;
in other cases, you will need to add something like the following to your
configuration.nix
:
xdg.portal.extraPortals
= [ pkgs.xdg-desktop-portal-gtk ];
Then, you will need to add a repository, for example, Flathub, either using the following commands:
$
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo$
flatpak update
or by opening the repository file in GNOME Software.
Finally, you can search and install programs:
$
flatpak search bustle$
flatpak install flathub org.freedesktop.Bustle$
flatpak run org.freedesktop.Bustle
Again, GNOME Software offers graphical interface for these tasks.
Table of Contents
Source: modules/services/databases/postgresql.nix
Upstream documentation: http://www.postgresql.org/docs/
PostgreSQL is an advanced, free relational database.
To enable PostgreSQL, add the following to your configuration.nix
:
services.postgresql.enable
= true;services.postgresql.package
= pkgs.postgresql_11;
Note that you are required to specify the desired version of PostgreSQL (e.g. pkgs.postgresql_11
). Since upgrading your PostgreSQL version requires a database dump and reload (see below), NixOS cannot provide a default value for services.postgresql.package
such as the most recent release of PostgreSQL.
By default, PostgreSQL stores its databases in /var/lib/postgresql/$psqlSchema
. You can override this using services.postgresql.dataDir
, e.g.
services.postgresql.dataDir
= "/data/postgresql";
Major PostgreSQL upgrade requires PostgreSQL downtime and a few imperative steps to be called. To simplify this process, use the following NixOS module:
containers.temp-pg.config.services.postgresql = { enable = true; package = pkgs.postgresql_12; ## set a custom new dataDir # dataDir = "/some/data/dir"; }; environment.systemPackages = let newpg = config.containers.temp-pg.config.services.postgresql; in [ (pkgs.writeScriptBin "upgrade-pg-cluster" '' set -x export OLDDATA="${config.services.postgresql.dataDir}" export NEWDATA="${newpg.dataDir}" export OLDBIN="${config.services.postgresql.package}/bin" export NEWBIN="${newpg.package}/bin" install -d -m 0700 -o postgres -g postgres "$NEWDATA" cd "$NEWDATA" sudo -u postgres $NEWBIN/initdb -D "$NEWDATA" systemctl stop postgresql # old one sudo -u postgres $NEWBIN/pg_upgrade \ --old-datadir "$OLDDATA" --new-datadir "$NEWDATA" \ --old-bindir $OLDBIN --new-bindir $NEWBIN \ "$@" '') ];
The upgrade process is:
Rebuild nixos configuration with the configuration above added to your configuration.nix
. Alternatively, add that into separate file and reference it in imports
list.
Login as root (sudo su -
)
Run upgrade-pg-cluster
. It will stop old postgresql, initialize new one and migrate old one to new one. You may supply arguments like --jobs 4
and --link
to speedup migration process. See https://www.postgresql.org/docs/current/pgupgrade.html for details.
Change postgresql package in NixOS configuration to the one you were upgrading to, and change dataDir
to the one you have migrated to. Rebuild NixOS. This should start new postgres using upgraded data directory.
After upgrade you may want to ANALYZE
new db.
A complete list of options for the PostgreSQL module may be found here.
Plugins collection for each PostgreSQL version can be accessed with .pkgs
. For example, for pkgs.postgresql_11
package, its plugin collection is accessed by pkgs.postgresql_11.pkgs
:
$
nix repl '<nixpkgs>' Loading '<nixpkgs>'... Added 10574 variables.nix-repl>
postgresql_11.pkgs.<TAB><TAB> postgresql_11.pkgs.cstore_fdw postgresql_11.pkgs.pg_repack postgresql_11.pkgs.pg_auto_failover postgresql_11.pkgs.pg_safeupdate postgresql_11.pkgs.pg_bigm postgresql_11.pkgs.pg_similarity postgresql_11.pkgs.pg_cron postgresql_11.pkgs.pg_topn postgresql_11.pkgs.pg_hll postgresql_11.pkgs.pgjwt postgresql_11.pkgs.pg_partman postgresql_11.pkgs.pgroonga ...
To add plugins via NixOS configuration, set services.postgresql.extraPlugins
:
services.postgresql.package
= pkgs.postgresql_11;services.postgresql.extraPlugins
= with pkgs.postgresql_11.pkgs; [ pg_repack postgis ];
You can build custom PostgreSQL-with-plugins (to be used outside of NixOS) using function .withPackages
. For example, creating a custom PostgreSQL package in an overlay can look like:
self: super: { postgresql_custom = self.postgresql_11.withPackages (ps: [ ps.pg_repack ps.postgis ]); }
Here's a recipe on how to override a particular plugin through an overlay:
self: super: { postgresql_11 = super.postgresql_11.override { this = self.postgresql_11; } // { pkgs = super.postgresql_11.pkgs // { pg_repack = super.postgresql_11.pkgs.pg_repack.overrideAttrs (_: { name = "pg_repack-v20181024"; src = self.fetchzip { url = "https://github.com/reorg/pg_repack/archive/923fa2f3c709a506e111cc963034bf2fd127aa00.tar.gz"; sha256 = "17k6hq9xaax87yz79j773qyigm4fwk8z4zh5cyp6z0sxnwfqxxw5"; }; }); }; }; }
Table of Contents
Source:
modules/services/databases/foundationdb.nix
Upstream documentation: https://apple.github.io/foundationdb/
Maintainer: Austin Seipp
Available version(s): 5.1.x, 5.2.x, 6.0.x
FoundationDB (or "FDB") is an open source, distributed, transactional key-value store.
To enable FoundationDB, add the following to your
configuration.nix
:
services.foundationdb.enable = true; services.foundationdb.package = pkgs.foundationdb52; # FoundationDB 5.2.x
The services.foundationdb.package
option is required, and
must always be specified. Due to the fact FoundationDB network protocols and
on-disk storage formats may change between (major) versions, and upgrades
must be explicitly handled by the user, you must always manually specify
this yourself so that the NixOS module will use the proper version. Note
that minor, bugfix releases are always compatible.
After running nixos-rebuild, you can verify whether
FoundationDB is running by executing fdbcli (which is
added to environment.systemPackages
):
$
sudo -u foundationdb fdbcli Using cluster file `/etc/foundationdb/fdb.cluster'. The database is available. Welcome to the fdbcli. For help, type `help'.fdb>
status Using cluster file `/etc/foundationdb/fdb.cluster'. Configuration: Redundancy mode - single Storage engine - memory Coordinators - 1 Cluster: FoundationDB processes - 1 Machines - 1 Memory availability - 5.4 GB per process on machine with least available Fault Tolerance - 0 machines Server time - 04/20/18 15:21:14 ...fdb>
You can also write programs using the available client libraries. For example, the following Python program can be run in order to grab the cluster status, as a quick example. (This example uses nix-shell shebang support to automatically supply the necessary Python modules).
a@link>
cat fdb-status.py #! /usr/bin/env nix-shell #! nix-shell -i python -p python pythonPackages.foundationdb52 import fdb import json def main(): fdb.api_version(520) db = fdb.open() @fdb.transactional def get_status(tr): return str(tr['\xff\xff/status/json']) obj = json.loads(get_status(db)) print('FoundationDB available: %s' % obj['client']['database_status']['available']) if __name__ == "__main__": main()a@link>
chmod +x fdb-status.pya@link>
./fdb-status.py FoundationDB available: Truea@link>
FoundationDB is run under the foundationdb user and group by default, but this may be changed in the NixOS configuration. The systemd unit foundationdb.service controls the fdbmonitor process.
By default, the NixOS module for FoundationDB creates a single SSD-storage based database for development and basic usage. This storage engine is designed for SSDs and will perform poorly on HDDs; however it can handle far more data than the alternative "memory" engine and is a better default choice for most deployments. (Note that you can change the storage backend on-the-fly for a given FoundationDB cluster using fdbcli.)
Furthermore, only 1 server process and 1 backup agent are started in the default configuration. See below for more on scaling to increase this.
FoundationDB stores all data for all server processes under
/var/lib/foundationdb
. You can override this using
services.foundationdb.dataDir
, e.g.
services.foundationdb.dataDir = "/data/fdb";
Similarly, logs are stored under /var/log/foundationdb
by default, and there is a corresponding
services.foundationdb.logDir
as well.
Scaling the number of server processes is quite easy; simply specify
services.foundationdb.serverProcesses
to be the number of
FoundationDB worker processes that should be started on the machine.
FoundationDB worker processes typically require 4GB of RAM per-process at minimum for good performance, so this option is set to 1 by default since the maximum amount of RAM is unknown. You're advised to abide by this restriction, so pick a number of processes so that each has 4GB or more.
A similar option exists in order to scale backup agent processes,
services.foundationdb.backupProcesses
. Backup agents are
not as performance/RAM sensitive, so feel free to experiment with the number
of available backup processes.
FoundationDB on NixOS works similarly to other Linux systems, so this section will be brief. Please refer to the full FoundationDB documentation for more on clustering.
FoundationDB organizes clusters using a set of coordinators, which are just specially-designated worker processes. By default, every installation of FoundationDB on NixOS will start as its own individual cluster, with a single coordinator: the first worker process on localhost.
Coordinators are specified globally using the /etc/foundationdb/fdb.cluster file, which all servers and client applications will use to find and join coordinators. Note that this file can not be managed by NixOS so easily: FoundationDB is designed so that it will rewrite the file at runtime for all clients and nodes when cluster coordinators change, with clients transparently handling this without intervention. It is fundamentally a mutable file, and you should not try to manage it in any way in NixOS.
When dealing with a cluster, there are two main things you want to do:
Add a node to the cluster for storage/compute.
Promote an ordinary worker to a coordinator.
A node must already be a member of the cluster in order to properly be promoted to a coordinator, so you must always add it first if you wish to promote it.
To add a machine to a FoundationDB cluster:
Choose one of the servers to start as the initial coordinator.
Copy the /etc/foundationdb/fdb.cluster file from this server to all the other servers. Restart FoundationDB on all of these other servers, so they join the cluster.
All of these servers are now connected and working together in the cluster, under the chosen coordinator.
At this point, you can add as many nodes as you want by just repeating the above steps. By default there will still be a single coordinator: you can use fdbcli to change this and add new coordinators.
As a convenience, FoundationDB can automatically assign coordinators based on the redundancy mode you wish to achieve for the cluster. Once all the nodes have been joined, simply set the replication policy, and then issue the coordinators auto command
For example, assuming we have 3 nodes available, we can enable double redundancy mode, then auto-select coordinators. For double redundancy, 3 coordinators is ideal: therefore FoundationDB will make every node a coordinator automatically:
fdbcli>
configure double ssdfdbcli>
coordinators auto
This will transparently update all the servers within seconds, and appropriately rewrite the fdb.cluster file, as well as informing all client processes to do the same.
By default, all clients must use the current fdb.cluster file to access a given FoundationDB cluster. This file is located by default in /etc/foundationdb/fdb.cluster on all machines with the FoundationDB service enabled, so you may copy the active one from your cluster to a new node in order to connect, if it is not part of the cluster.
By default, any user who can connect to a FoundationDB process with the correct cluster configuration can access anything. FoundationDB uses a pluggable design to transport security, and out of the box it supports a LibreSSL-based plugin for TLS support. This plugin not only does in-flight encryption, but also performs client authorization based on the given endpoint's certificate chain. For example, a FoundationDB server may be configured to only accept client connections over TLS, where the client TLS certificate is from organization Acme Co in the Research and Development unit.
Configuring TLS with FoundationDB is done using the
services.foundationdb.tls
options in order to control the
peer verification string, as well as the certificate and its private key.
Note that the certificate and its private key must be accessible to the FoundationDB user account that the server runs under. These files are also NOT managed by NixOS, as putting them into the store may reveal private information.
After you have a key and certificate file in place, it is not enough to simply set the NixOS module options -- you must also configure the fdb.cluster file to specify that a given set of coordinators use TLS. This is as simple as adding the suffix :tls to your cluster coordinator configuration, after the port number. For example, assuming you have a coordinator on localhost with the default configuration, simply specifying:
XXXXXX:XXXXXX@127.0.0.1:4500:tls
will configure all clients and server processes to use TLS from now on.
The usual rules for doing FoundationDB backups apply on NixOS as written in the FoundationDB manual. However, one important difference is the security profile for NixOS: by default, the foundationdb systemd unit uses Linux namespaces to restrict write access to the system, except for the log directory, data directory, and the /etc/foundationdb/ directory. This is enforced by default and cannot be disabled.
However, a side effect of this is that the fdbbackup command doesn't work properly for local filesystem backups: FoundationDB uses a server process alongside the database processes to perform backups and copy the backups to the filesystem. As a result, this process is put under the restricted namespaces above: the backup process can only write to a limited number of paths.
In order to allow flexible backup locations on local disks, the FoundationDB
NixOS module supports a
services.foundationdb.extraReadWritePaths
option. This
option takes a list of paths, and adds them to the systemd unit, allowing
the processes inside the service to write (and read) the specified
directories.
For example, to create backups in /opt/fdb-backups, first set up the paths in the module options:
services.foundationdb.extraReadWritePaths = [ "/opt/fdb-backups" ];
Restart the FoundationDB service, and it will now be able to write to this directory (even if it does not yet exist.) Note: this path must exist before restarting the unit. Otherwise, systemd will not include it in the private FoundationDB namespace (and it will not add it dynamically at runtime).
You can now perform a backup:
$
sudo -u foundationdb fdbbackup start -t default -d file:///opt/fdb-backups$
sudo -u foundationdb fdbbackup status -t default
The FoundationDB setup for NixOS should currently be considered beta. FoundationDB is not new software, but the NixOS compilation and integration has only undergone fairly basic testing of all the available functionality.
There is no way to specify individual parameters for individual fdbserver processes. Currently, all server processes inherit all the global fdbmonitor settings.
Ruby bindings are not currently installed.
Go bindings are not currently installed.
NixOS's FoundationDB module allows you to configure all of the most relevant configuration options for fdbmonitor, matching it quite closely. A complete list of options for the FoundationDB module may be found here. You should also read the FoundationDB documentation as well.
FoundationDB is a complex piece of software, and requires careful administration to properly use. Full documentation for administration can be found here: https://apple.github.io/foundationdb/.
Setting
security.hideProcessInformation
= true;
ensures that access to process information is restricted to the owning user. This implies, among other things, that command-line arguments remain private. Unless your deployment relies on unprivileged users being able to inspect the process information of other users, this option should be safe to enable.
Members of the proc
group are exempt from process
information hiding.
To allow a service foo
to run without process
information hiding, set
systemd.services.foo
.serviceConfig.SupplementaryGroups = [ "proc" ];
NixOS supports automatic domain validation & certificate retrieval and
renewal using the ACME protocol. This is currently only implemented by and
for Let's Encrypt. The alternative ACME client lego
is
used under the hood.
You need to have a running HTTP server for verification. The server must
have a webroot defined that can serve
.well-known/acme-challenge
. This directory must be
writeable by the user that will run the ACME client.
For instance, this generic snippet could be used for Nginx:
http { server { server_name _; listen 80; listen [::]:80; location /.well-known/acme-challenge { root /var/www/challenges; } location / { return 301 https://$host$request_uri; } } }
To enable ACME certificate retrieval & renewal for a certificate for
foo.example.com
, add the following in your
configuration.nix
:
security.acme.certs
."foo.example.com" = {
webroot = "/var/www/challenges";
email = "foo@example.com";
};
The private key key.pem
and certificate
fullchain.pem
will be put into
/var/lib/acme/foo.example.com
.
Refer to Appendix A, Configuration Options for all available configuration options for the security.acme module.
NixOS supports fetching ACME certificates for you by setting
enableACME
= true;
in a virtualHost config. We first create self-signed
placeholder certificates in place of the real ACME certs. The placeholder
certs are overwritten when the ACME certs arrive. For
foo.example.com
the config would look like.
services.nginx = { enable = true; virtualHosts = { "foo.example.com" = { forceSSL = true; enableACME = true; locations."/" = { root = "/var/www"; }; }; }; }
Table of Contents
oh-my-zsh
is a
framework to manage your ZSH
configuration including completion scripts for several CLI tools or custom
prompt themes.
The module uses the oh-my-zsh
package with all available
features. The initial setup using Nix expressions is fairly similar to the
configuration format of oh-my-zsh
.
{ programs.zsh.ohMyZsh = { enable = true; plugins = [ "git" "python" "man" ]; theme = "agnoster"; }; }
For a detailed explanation of these arguments please refer to the
oh-my-zsh
docs.
The expression generates the needed configuration and writes it into your
/etc/zshrc
.
Sometimes third-party or custom scripts such as a modified theme may be
needed. oh-my-zsh
provides the
ZSH_CUSTOM
environment variable for this which points to a directory with additional
scripts.
The module can do this as well:
{ programs.zsh.ohMyZsh.custom = "~/path/to/custom/scripts"; }
There are several extensions for oh-my-zsh
packaged in
nixpkgs
. One of them is
nix-zsh-completions
which bundles completion scripts and a plugin for
oh-my-zsh
.
Rather than using a single mutable path for ZSH_CUSTOM
,
it's also possible to generate this path from a list of Nix packages:
{ pkgs, ... }: { programs.zsh.ohMyZsh.customPkgs = with pkgs; [ pkgs.nix-zsh-completions # and even more... ]; }
Internally a single store path will be created using
buildEnv
. Please refer to the docs of
buildEnv
for further reference.
Please keep in mind that this is not compatible with
programs.zsh.ohMyZsh.custom
as it requires an immutable
store path while custom
shall remain mutable! An
evaluation failure will be thrown if both custom
and
customPkgs
are set.
If third-party customizations (e.g. new themes) are supposed to be added to
oh-my-zsh
there are several pitfalls to keep in mind:
To comply with the default structure of ZSH
the entire
output needs to be written to $out/share/zsh.
Completion scripts are supposed to be stored at
$out/share/zsh/site-functions
. This directory is part
of the
fpath
and the package should be compatible with pure ZSH
setups. The module will automatically link the contents of
site-functions
to completions directory in the proper
store path.
The plugins
directory needs the structure
pluginname/pluginname.plugin.zsh
as structured in the
upstream
repo.
A derivation for oh-my-zsh
may look like this:
{ stdenv, fetchFromGitHub }: stdenv.mkDerivation rec { name = "exemplary-zsh-customization-${version}"; version = "1.0.0"; src = fetchFromGitHub { # path to the upstream repository }; dontBuild = true; installPhase = '' mkdir -p $out/share/zsh/site-functions cp {themes,plugins} $out/share/zsh cp completions $out/share/zsh/site-functions ''; }
Source:
modules/programs/plotinus.nix
Upstream documentation: https://github.com/p-e-w/plotinus
Plotinus is a searchable command palette in every modern GTK application.
When in a GTK 3 application and Plotinus is enabled, you can press
Ctrl+Shift+P
to open the command palette. The command
palette provides a searchable list of of all menu items in the application.
To enable Plotinus, add the following to your
configuration.nix
:
programs.plotinus.enable
= true;
Table of Contents
Digital Bitbox is a hardware wallet and second-factor authenticator.
The digitalbitbox
programs module may be installed by
setting programs.digitalbitbox
to true
in a manner similar to
programs.digitalbitbox.enable
= true;
and bundles the digitalbitbox
package (see
Section 31.1, “Package”), which contains the
dbb-app
and dbb-cli
binaries, along
with the hardware module (see
Section 31.2, “Hardware”) which sets up the
necessary udev rules to access the device.
Enabling the digitalbitbox module is pretty much the easiest way to get a Digital Bitbox device working on your system.
For more information, see https://digitalbitbox.com/start_linux.
The binaries, dbb-app
(a GUI tool) and
dbb-cli
(a CLI tool), are available through the
digitalbitbox
package which could be installed as
follows:
environment.systemPackages
= [
pkgs.digitalbitbox
];
The digitalbitbox hardware package enables the udev rules for Digital Bitbox devices and may be installed as follows:
hardware.digitalbitbox.enable
= true;
In order to alter the udev rules, one may provide different values for the
udevRule51
and udevRule52
attributes
by means of overriding as follows:
programs.digitalbitbox = { enable = true; package = pkgs.digitalbitbox.override { udevRule51 = "something else"; }; };
Table of Contents
Input methods are an operating system component that allows any data, such as keyboard strokes or mouse movements, to be received as input. In this way users can enter characters and symbols not found on their input devices. Using an input method is obligatory for any language that has more graphemes than there are keys on the keyboard.
The following input methods are available in NixOS:
IBus: The intelligent input bus.
Fcitx: A customizable lightweight input method.
Nabi: A Korean input method based on XIM.
Uim: The universal input method, is a library with a XIM bridge.
IBus is an Intelligent Input Bus. It provides full featured and user friendly input method user interface.
The following snippet can be used to configure IBus:
i18n.inputMethod = { enabled = "ibus"; ibus.engines = with pkgs.ibus-engines; [ anthy hangul mozc ]; };
i18n.inputMethod.ibus.engines
is optional and can be used
to add extra IBus engines.
Available extra IBus engines are:
Anthy (ibus-engines.anthy
): Anthy is a system for
Japanese input method. It converts Hiragana text to Kana Kanji mixed text.
Hangul (ibus-engines.hangul
): Korean input method.
m17n (ibus-engines.m17n
): m17n is an input method that
uses input methods and corresponding icons in the m17n database.
mozc (ibus-engines.mozc
): A Japanese input method from
Google.
Table (ibus-engines.table
): An input method that load
tables of input methods.
table-others (ibus-engines.table-others
): Various
table-based input methods. To use this, and any other table-based input
methods, it must appear in the list of engines along with
table
. For example:
ibus.engines = with pkgs.ibus-engines; [ table table-others ];
To use any input method, the package must be added in the configuration, as
shown above, and also (after running nixos-rebuild
) the
input method must be added from IBus' preference dialog.
If IBus works in some applications but not others, a likely cause of this
is that IBus is depending on a different version of glib
to what the applications are depending on. This can be checked by running
nix-store -q --requisites <path> | grep glib
,
where <path>
is the path of either IBus or an
application in the Nix store. The glib
packages must
match exactly. If they do not, uninstalling and reinstalling the
application is a likely fix.
Fcitx is an input method framework with extension support. It has three built-in Input Method Engine, Pinyin, QuWei and Table-based input methods.
The following snippet can be used to configure Fcitx:
i18n.inputMethod = { enabled = "fcitx"; fcitx.engines = with pkgs.fcitx-engines; [ mozc hangul m17n ]; };
i18n.inputMethod.fcitx.engines
is optional and can be
used to add extra Fcitx engines.
Available extra Fcitx engines are:
Anthy (fcitx-engines.anthy
): Anthy is a system for
Japanese input method. It converts Hiragana text to Kana Kanji mixed text.
Chewing (fcitx-engines.chewing
): Chewing is an
intelligent Zhuyin input method. It is one of the most popular input
methods among Traditional Chinese Unix users.
Hangul (fcitx-engines.hangul
): Korean input method.
Unikey (fcitx-engines.unikey
): Vietnamese input method.
m17n (fcitx-engines.m17n
): m17n is an input method that
uses input methods and corresponding icons in the m17n database.
mozc (fcitx-engines.mozc
): A Japanese input method from
Google.
table-others (fcitx-engines.table-others
): Various
table-based input methods.
Nabi is an easy to use Korean X input method. It allows you to enter phonetic Korean characters (hangul) and pictographic Korean characters (hanja).
The following snippet can be used to configure Nabi:
i18n.inputMethod = { enabled = "nabi"; };
Uim (short for "universal input method") is a multilingual input method framework. Applications can use it through so-called bridges.
The following snippet can be used to configure uim:
i18n.inputMethod = { enabled = "uim"; };
Note: The i18n.inputMethod.uim.toolbar
option can be
used to choose uim toolbar.
Table of Contents
In some cases, it may be desirable to take advantage of commonly-used,
predefined configurations provided by nixpkgs, but different from those that
come as default. This is a role fulfilled by NixOS's Profiles, which come as
files living in <nixpkgs/nixos/modules/profiles>
.
That is to say, expected usage is to add them to the imports list of your
/etc/configuration.nix
as such:
imports = [ <nixpkgs/nixos/modules/profiles/profile-name.nix> ];
Even if some of these profiles seem only useful in the context of install media, many are actually intended to be used in real installs.
What follows is a brief explanation on the purpose and use-case for each profile. Detailing each option configured by each one is out of scope.
Enables all hardware supported by NixOS: i.e., all firmware is included, and all devices from which one may boot are enabled in the initrd. Its primary use is in the NixOS installation CDs.
The enabled kernel modules include support for SATA and PATA, SCSI
(partially), USB, Firewire (untested), Virtio (QEMU, KVM, etc.), VMware, and
Hyper-V. Additionally, hardware.enableAllFirmware
is
enabled, and the firmware for the ZyDAS ZD1211 chipset is specifically
installed.
Defines the software packages included in the "minimal" installation CD. It installs several utilities useful in a simple recovery or install media, such as a text-mode web browser, and tools for manipulating block devices, networking, hardware diagnostics, and filesystems (with their respective kernel modules).
This profile is used in installer images. It provides an editable configuration.nix that imports all the modules that were also used when creating the image in the first place. As a result it allows users to edit and rebuild the live-system.
On images where the installation media also becomes an installation target,
copying over configuration.nix
should be disabled by
setting installer.cloneConfig
to false
.
For example, this is done in sd-image-aarch64.nix
.
This profile just enables a demo
user, with password demo
, uid 1000
,
wheel
group and
autologin
in the SDDM display manager.
This is the profile from which the Docker images are generated. It prepares a
working system by importing the
Minimal and
Clone Config profiles, and
setting appropriate configuration options that are useful inside a container
context, like boot.isContainer
.
Defines a NixOS configuration with the Plasma 5 desktop. It's used by the graphical installation CD.
It sets services.xserver.enable
,
services.xserver.displayManager.sddm.enable
,
services.xserver.desktopManager.plasma5.enable
, and
services.xserver.libinput.enable
to true. It also
includes glxinfo and firefox in the system packages list.
A profile with most (vanilla) hardening options enabled by default, potentially at the cost of features and performance.
This includes a hardened kernel, and limiting the system information
available to processes through the /sys
and
/proc
filesystems. It also disables the User Namespaces
feature of the kernel, which stops Nix from being able to build anything
(this particular setting can be overriden via
security.allowUserNamespaces
). See the
profile source
for further detail on which settings are altered.
Common configuration for headless machines (e.g., Amazon EC2 instances).
Disables sound, vesa, serial consoles, emergency mode, grub splash images and configures the kernel to reboot automatically on panic.
Provides a basic configuration for installation devices like CDs. This enables redistributable firmware, includes the Clone Config profile and a copy of the Nixpkgs channel, so nixos-install works out of the box.
Documentation for Nixpkgs
and NixOS are
forcefully enabled (to override the
Minimal profile preference); the
NixOS manual is shown automatically on TTY 8, udisks is disabled.
Autologin is enabled as nixos
user, while passwordless
login as both root
and nixos
is possible.
Passwordless sudo is enabled too.
wpa_supplicant is
enabled, but configured to not autostart.
It is explained how to login, start the ssh server, and if available, how to start the display manager.
Several settings are tweaked so that the installer has a better chance of succeeding under low-memory environments.
This profile defines a small NixOS configuration. It does not contain any graphical stuff. It's a very short file that enables noXlibs, sets i18n.supportedLocales to only support the user-selected locale, disables packages' documentation , and disables sound.
This profile contains common configuration for virtual machines running under QEMU (using virtio).
It makes virtio modules available on the initrd, sets the system time from the hardware clock to work around a bug in qemu-kvm, and enables rngd.
The NixOS Kubernetes module is a collective term for a handful of individual submodules implementing the Kubernetes cluster components.
There are generally two ways of enabling Kubernetes on NixOS. One way is to enable and configure cluster components appropriately by hand:
services.kubernetes = { apiserver.enable = true; controllerManager.enable = true; scheduler.enable = true; addonManager.enable = true; proxy.enable = true; flannel.enable = true; };
Another way is to assign cluster roles ("master" and/or "node") to the host. This enables apiserver, controllerManager, scheduler, addonManager, kube-proxy and etcd:
services.kubernetes.roles
= [ "master" ];
While this will enable the kubelet and kube-proxy only:
services.kubernetes.roles
= [ "node" ];
Assigning both the master and node roles is usable if you want a single node Kubernetes cluster for dev or testing purposes:
services.kubernetes.roles
= [ "master" "node" ];
Note: Assigning either role will also default both
services.kubernetes.flannel.enable
and
services.kubernetes.easyCerts
to true. This sets up
flannel as CNI and activates automatic PKI bootstrapping.
As of kubernetes 1.10.X it has been deprecated to open non-tls-enabled ports
on kubernetes components. Thus, from NixOS 19.03 all plain HTTP ports have
been disabled by default. While opening insecure ports is still possible, it
is recommended not to bind these to other interfaces than loopback. To
re-enable the insecure port on the apiserver, see options:
services.kubernetes.apiserver.insecurePort
and
services.kubernetes.apiserver.insecureBindAddress
services.kubernetes.masterAddress
. The masterAddress
must be resolveable and routeable by all cluster nodes. In single node
clusters, this can be set to localhost
.
Role-based access control (RBAC) authorization mode is enabled by default. This means that anonymous requests to the apiserver secure port will expectedly cause a permission denied error. All cluster components must therefore be configured with x509 certificates for two-way tls communication. The x509 certificate subject section determines the roles and permissions granted by the apiserver to perform clusterwide or namespaced operations. See also: Using RBAC Authorization.
The NixOS kubernetes module provides an option for automatic certificate
bootstrapping and configuration,
services.kubernetes.easyCerts
. The PKI bootstrapping
process involves setting up a certificate authority (CA) daemon (cfssl) on
the kubernetes master node. cfssl generates a CA-cert for the cluster, and
uses the CA-cert for signing subordinate certs issued to each of the cluster
components. Subsequently, the certmgr daemon monitors active certificates and
renews them when needed. For single node Kubernetes clusters, setting
services.kubernetes.easyCerts
= true is sufficient and
no further action is required. For joining extra node machines to an existing
cluster on the other hand, establishing initial trust is mandatory.
To add new nodes to the cluster: On any (non-master) cluster node where
services.kubernetes.easyCerts
is enabled, the helper
script nixos-kubernetes-node-join
is available on PATH.
Given a token on stdin, it will copy the token to the kubernetes secrets
directory and restart the certmgr service. As requested certificates are
issued, the script will restart kubernetes cluster components as needed for
them to pick up new keypairs.
In order to interact with an RBAC-enabled cluster as an administrator, one
needs to have cluster-admin privileges. By default, when easyCerts is
enabled, a cluster-admin kubeconfig file is generated and linked into
/etc/kubernetes/cluster-admin.kubeconfig
as determined by
services.kubernetes.pki.etcClusterAdminKubeconfig
.
export KUBECONFIG=/etc/kubernetes/cluster-admin.kubeconfig
will make kubectl use this kubeconfig to access and authenticate the cluster.
The cluster-admin kubeconfig references an auto-generated keypair owned by
root. Thus, only root on the kubernetes master may obtain cluster-admin
rights by means of this file.
This chapter describes various aspects of managing a running NixOS system, such as how to use the systemd service manager.
In NixOS, all system services are started and monitored using the systemd
program. Systemd is the “init” process of the system (i.e. PID 1), the
parent of all other processes. It manages a set of so-called “units”,
which can be things like system services (programs), but also mount points,
swap files, devices, targets (groups of units) and more. Units can have
complex dependencies; for instance, one unit can require that another unit
must be successfully started before the first unit can be started. When the
system boots, it starts a unit named default.target
; the
dependencies of this unit cause all system services to be started, file
systems to be mounted, swap files to be activated, and so on.
The command systemctl is the main way to interact with systemd. Without any arguments, it shows the status of active units:
$
systemctl -.mount loaded active mounted / swapfile.swap loaded active active /swapfile sshd.service loaded active running SSH Daemon graphical.target loaded active active Graphical Interface...
You can ask for detailed status information about a unit, for instance, the PostgreSQL database service:
$
systemctl status postgresql.service
postgresql.service - PostgreSQL Server
Loaded: loaded (/nix/store/pn3q73mvh75gsrl8w7fdlfk3fq5qm5mw-unit/postgresql.service)
Active: active (running) since Mon, 2013-01-07 15:55:57 CET; 9h ago
Main PID: 2390 (postgres)
CGroup: name=systemd:/system/postgresql.service
├─2390 postgres
├─2418 postgres: writer process
├─2419 postgres: wal writer process
├─2420 postgres: autovacuum launcher process
├─2421 postgres: stats collector process
└─2498 postgres: zabbix zabbix [local] idle
Jan 07 15:55:55 hagbard postgres[2394]: [1-1] LOG: database system was shut down at 2013-01-07 15:55:05 CET
Jan 07 15:55:57 hagbard postgres[2390]: [1-1] LOG: database system is ready to accept connections
Jan 07 15:55:57 hagbard postgres[2420]: [1-1] LOG: autovacuum launcher started
Jan 07 15:55:57 hagbard systemd[1]: Started PostgreSQL Server.
Note that this shows the status of the unit (active and running), all the processes belonging to the service, as well as the most recent log messages from the service.
Units can be stopped, started or restarted:
# systemctl stop postgresql.service # systemctl start postgresql.service # systemctl restart postgresql.service
These operations are synchronous: they wait until the service has finished starting or stopping (or has failed). Starting a unit will cause the dependencies of that unit to be started as well (if necessary).
The system can be shut down (and automatically powered off) by doing:
# shutdown
This is equivalent to running systemctl poweroff.
To reboot the system, run
# reboot
which is equivalent to systemctl reboot. Alternatively,
you can quickly reboot the system using kexec
, which
bypasses the BIOS by directly loading the new kernel into memory:
# systemctl kexec
The machine can be suspended to RAM (if supported) using systemctl suspend, and suspended to disk using systemctl hibernate.
These commands can be run by any user who is logged in locally, i.e. on a virtual console or in X11; otherwise, the user is asked for authentication.
Systemd keeps track of all users who are logged into the system (e.g. on a virtual console or remotely via SSH). The command loginctl allows querying and manipulating user sessions. For instance, to list all user sessions:
$
loginctl
SESSION UID USER SEAT
c1 500 eelco seat0
c3 0 root seat0
c4 500 alice
This shows that two users are logged in locally, while another is logged in remotely. (“Seats” are essentially the combinations of displays and input devices attached to the system; usually, there is only one seat.) To get information about a session:
$
loginctl session-status c3
c3 - root (0)
Since: Tue, 2013-01-08 01:17:56 CET; 4min 42s ago
Leader: 2536 (login)
Seat: seat0; vc3
TTY: /dev/tty3
Service: login; type tty; class user
State: online
CGroup: name=systemd:/user/root/c3
├─ 2536 /nix/store/10mn4xip9n7y9bxqwnsx7xwx2v2g34xn-shadow-4.1.5.1/bin/login --
├─10339 -bash
└─10355 w3m nixos.org
This shows that the user is logged in on virtual console 3. It also lists the processes belonging to this session. Since systemd keeps track of this, you can terminate a session in a way that ensures that all the session’s processes are gone:
# loginctl terminate-session c3
To keep track of the processes in a running system, systemd uses control groups (cgroups). A control group is a set of processes used to allocate resources such as CPU, memory or I/O bandwidth. There can be multiple control group hierarchies, allowing each kind of resource to be managed independently.
The command systemd-cgls lists all control groups in the
systemd
hierarchy, which is what systemd uses to keep
track of the processes belonging to each service or user session:
$
systemd-cgls ├─user │ └─eelco │ └─c1 │ ├─ 2567 -:0 │ ├─ 2682 kdeinit4: kdeinit4 Running... │ ├─...
│ └─10851 sh -c less -R └─system ├─httpd.service │ ├─2444 httpd -f /nix/store/3pyacby5cpr55a03qwbnndizpciwq161-httpd.conf -DNO_DETACH │ └─...
├─dhcpcd.service │ └─2376 dhcpcd --config /nix/store/f8dif8dsi2yaa70n03xir8r653776ka6-dhcpcd.conf └─...
Similarly, systemd-cgls cpu shows the cgroups in the CPU
hierarchy, which allows per-cgroup CPU scheduling priorities. By default,
every systemd service gets its own CPU cgroup, while all user sessions are in
the top-level CPU cgroup. This ensures, for instance, that a thousand
run-away processes in the httpd.service
cgroup cannot
starve the CPU for one process in the postgresql.service
cgroup. (By contrast, it they were in the same cgroup, then the PostgreSQL
process would get 1/1001 of the cgroup’s CPU time.) You can limit a
service’s CPU share in configuration.nix
:
systemd.services.httpd.serviceConfig.CPUShares = 512;
By default, every cgroup has 1024 CPU shares, so this will halve the CPU
allocation of the httpd.service
cgroup.
There also is a memory
hierarchy that controls memory
allocation limits; by default, all processes are in the top-level cgroup, so
any service or session can exhaust all available memory. Per-cgroup memory
limits can be specified in configuration.nix
; for
instance, to limit httpd.service
to 512 MiB of RAM
(excluding swap):
systemd.services.httpd.serviceConfig.MemoryLimit = "512M";
The command systemd-cgtop shows a continuously updated list of all cgroups with their CPU and memory usage.
System-wide logging is provided by systemd’s journal,
which subsumes traditional logging daemons such as syslogd and klogd. Log
entries are kept in binary files in /var/log/journal/
.
The command journalctl
allows you to see the contents of
the journal. For example,
$
journalctl -b
shows all journal entries since the last reboot. (The output of journalctl is piped into less by default.) You can use various options and match operators to restrict output to messages of interest. For instance, to get all messages from PostgreSQL:
$
journalctl -u postgresql.service
-- Logs begin at Mon, 2013-01-07 13:28:01 CET, end at Tue, 2013-01-08 01:09:57 CET. --
...
Jan 07 15:44:14 hagbard postgres[2681]: [2-1] LOG: database system is shut down
-- Reboot --
Jan 07 15:45:10 hagbard postgres[2532]: [1-1] LOG: database system was shut down at 2013-01-07 15:44:14 CET
Jan 07 15:45:13 hagbard postgres[2500]: [1-1] LOG: database system is ready to accept connections
Or to get all messages since the last reboot that have at least a “critical” severity level:
$
journalctl -b -p crit
Dec 17 21:08:06 mandark sudo[3673]: pam_unix(sudo:auth): auth could not identify password for [alice]
Dec 29 01:30:22 mandark kernel[6131]: [1053513.909444] CPU6: Core temperature above threshold, cpu clock throttled (total events = 1)
The system journal is readable by root and by users in the
wheel
and systemd-journal
groups. All
users have a private journal that can be read using
journalctl.
Table of Contents
Nix has a purely functional model, meaning that packages are never upgraded
in place. Instead new versions of packages end up in a different location in
the Nix store (/nix/store
). You should periodically run
Nix’s garbage collector to remove old, unreferenced
packages. This is easy:
$
nix-collect-garbage
Alternatively, you can use a systemd unit that does the same in the background:
#
systemctl start nix-gc.service
You can tell NixOS in configuration.nix
to run this unit
automatically at certain points in time, for instance, every night at 03:15:
nix.gc.automatic
= true;nix.gc.dates
= "03:15";
The commands above do not remove garbage collector roots, such as old system configurations. Thus they do not remove the ability to roll back to previous configurations. The following command deletes old roots, removing the ability to roll back to them:
$
nix-collect-garbage -d
You can also do this for specific profiles, e.g.
$
nix-env -p /nix/var/nix/profiles/per-user/eelco/profile --delete-generations old
Note that NixOS system configurations are stored in the profile
/nix/var/nix/profiles/system
.
Another way to reclaim disk space (often as much as 40% of the size of the Nix store) is to run Nix’s store optimiser, which seeks out identical files in the store and replaces them with hard links to a single copy.
$
nix-store --optimise
Since this command needs to read the entire Nix store, it can take quite a while to finish.
If your /boot
partition runs out of space, after
clearing old profiles you must rebuild your system with
nixos-rebuild
to update the /boot
partition and clear space.
Table of Contents
NixOS allows you to easily run other NixOS instances as containers. Containers are a light-weight approach to virtualisation that runs software in the container at the same speed as in the host system. NixOS containers share the Nix store of the host, making container creation very efficient.
NixOS containers can be created in two ways: imperatively, using the command
nixos-container, and declaratively, by specifying them in
your configuration.nix
. The declarative approach implies
that containers get upgraded along with your host system when you run
nixos-rebuild, which is often not what you want. By
contrast, in the imperative approach, containers are configured and updated
independently from the host system.
We’ll cover imperative container management using
nixos-container first. Be aware that container management
is currently only possible as root
.
You create a container with identifier foo
as follows:
# nixos-container create foo
This creates the container’s root directory in
/var/lib/containers/foo
and a small configuration file
in /etc/containers/foo.conf
. It also builds the
container’s initial system configuration and stores it in
/nix/var/nix/profiles/per-container/foo/system
. You can
modify the initial configuration of the container on the command line. For
instance, to create a container that has sshd running,
with the given public key for root
:
# nixos-container create foo --config '
services.openssh.enable
= true;
users.users.root.openssh.authorizedKeys.keys = ["ssh-dss AAAAB3N…"];
'
By default the next free address in the 10.233.0.0/16
subnet will be chosen
as container IP. This behavior can be altered by setting --host-address
and
--local-address
:
# nixos-container create test --config-file test-container.nix \ --local-address 10.235.1.2 --host-address 10.235.1.1
Creating a container does not start it. To start the container, run:
# nixos-container start foo
This command will return as soon as the container has booted and has reached
multi-user.target
. On the host, the container runs within
a systemd unit called
container@
.
Thus, if something went wrong, you can get status info using
systemctl:
container-name
.service
# systemctl status container@foo
If the container has started successfully, you can log in as root using the root-login operation:
# nixos-container root-login foo [root@foo:~]#
Note that only root on the host can do this (since there is no authentication). You can also get a regular login prompt using the login operation, which is available to all users on the host:
# nixos-container login foo foo login: alice Password: ***
With nixos-container run, you can execute arbitrary commands in the container:
# nixos-container run foo -- uname -a Linux foo 3.4.82 #1-NixOS SMP Thu Mar 20 14:44:05 UTC 2014 x86_64 GNU/Linux
There are several ways to change the configuration of the container. First,
on the host, you can edit
/var/lib/container/
,
and run
name
/etc/nixos/configuration.nix
# nixos-container update foo
This will build and activate the new configuration. You can also specify a new configuration on the command line:
# nixos-container update foo --config 'services.httpd.enable
= true;services.httpd.adminAddr
= "foo@example.org";networking.firewall.allowedTCPPorts
= [ 80 ]; ' # curl http://$(nixos-container show-ip foo)/ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">…
However, note that this will overwrite the container’s
/etc/nixos/configuration.nix
.
Alternatively, you can change the configuration from within the container itself by running nixos-rebuild switch inside the container. Note that the container by default does not have a copy of the NixOS channel, so you should run nix-channel --update first.
Containers can be stopped and started using nixos-container
stop
and nixos-container start
, respectively, or
by using systemctl on the container’s service unit. To
destroy a container, including its file system, do
# nixos-container destroy foo
You can also specify containers and their configuration in the host’s
configuration.nix
. For example, the following specifies
that there shall be a container named database
running
PostgreSQL:
containers.database = { config = { config, pkgs, ... }: {services.postgresql.enable
= true;services.postgresql.package
= pkgs.postgresql_9_6; }; };
If you run nixos-rebuild switch
, the container will be
built. If the container was already running, it will be updated in place,
without rebooting. The container can be configured to start automatically by
setting containers.database.autoStart = true
in its
configuration.
By default, declarative containers share the network namespace of the host, meaning that they can listen on (privileged) ports. However, they cannot change the network configuration. You can give a container its own network as follows:
containers.database = { privateNetwork = true; hostAddress = "192.168.100.10"; localAddress = "192.168.100.11"; };
This gives the container a private virtual Ethernet interface with IP address
192.168.100.11
, which is hooked up to a virtual Ethernet
interface on the host with IP address 192.168.100.10
. (See
the next section for details on container networking.)
To disable the container, just remove it from
configuration.nix
and run nixos-rebuild
switch
. Note that this will not delete the root directory of the
container in /var/lib/containers
. Containers can be
destroyed using the imperative method: nixos-container destroy
foo
.
Declarative containers can be started and stopped using the corresponding
systemd service, e.g. systemctl start container@database
.
When you create a container using nixos-container create
,
it gets it own private IPv4 address in the range
10.233.0.0/16
. You can get the container’s IPv4 address
as follows:
#
nixos-container show-ip foo 10.233.4.2$
ping -c1 10.233.4.2 64 bytes from 10.233.4.2: icmp_seq=1 ttl=64 time=0.106 ms
Networking is implemented using a pair of virtual Ethernet devices. The
network interface in the container is called eth0
, while
the matching interface in the host is called
ve-
(e.g.,
container-name
ve-foo
). The container has its own network namespace and
the CAP_NET_ADMIN
capability, so it can perform arbitrary
network configuration such as setting up firewall rules, without affecting or
having access to the host’s network.
By default, containers cannot talk to the outside network. If you want that, you should set up Network Address Translation (NAT) rules on the host to rewrite container traffic to use your external IP address. This can be accomplished using the following configuration on the host:
networking.nat.enable
= true;networking.nat.internalInterfaces
= ["ve-+"];networking.nat.externalInterface
= "eth0";
where eth0
should be replaced with the desired external
interface. Note that ve-+
is a wildcard that matches all
container interfaces.
If you are using Network Manager, you need to explicitly prevent it from managing container interfaces:
networking.networkmanager.unmanaged = [ "interface-name:ve-*" ];
You may need to restart your system for the changes to take effect.
Table of Contents
This chapter describes solutions to common problems you might encounter when you manage your NixOS system.
If NixOS fails to boot, there are a number of kernel command line parameters
that may help you to identify or fix the issue. You can add these parameters
in the GRUB boot menu by pressing “e” to modify the selected boot entry
and editing the line starting with linux
. The following
are some useful kernel command line parameters that are recognised by the
NixOS boot scripts or by systemd:
boot.shell_on_fail
Start a root shell if something goes wrong in stage 1 of the boot process (the initial ramdisk). This is disabled by default because there is no authentication for the root shell.
boot.debug1
Start an interactive shell in stage 1 before anything useful has been
done. That is, no modules have been loaded and no file systems have been
mounted, except for /proc
and
/sys
.
boot.trace
Print every shell command executed by the stage 1 and 2 boot scripts.
single
Boot into rescue mode (a.k.a. single user mode). This will cause systemd
to start nothing but the unit rescue.target
, which
runs sulogin to prompt for the root password and start
a root login shell. Exiting the shell causes the system to continue with
the normal boot process.
systemd.log_level=debug systemd.log_target=console
Make systemd very verbose and send log messages to the console instead of the journal.
For more parameters recognised by systemd, see systemd(1).
If no login prompts or X11 login screens appear (e.g. due to hanging dependencies), you can press Alt+ArrowUp. If you’re lucky, this will start rescue mode (described above). (Also note that since most units have a 90-second timeout before systemd gives up on them, the agetty login prompts should appear eventually unless something is very wrong.)
You can enter rescue mode by running:
# systemctl rescue
This will eventually give you a single-user root shell. Systemd will stop (almost) all system services. To get out of maintenance mode, just exit from the rescue shell.
After running nixos-rebuild to switch to a new configuration, you may find that the new configuration doesn’t work very well. In that case, there are several ways to return to a previous configuration.
First, the GRUB boot manager allows you to boot into any previous configuration that hasn’t been garbage-collected. These configurations can be found under the GRUB submenu “NixOS - All configurations”. This is especially useful if the new configuration fails to boot. After the system has booted, you can make the selected configuration the default for subsequent boots:
# /run/current-system/bin/switch-to-configuration boot
Second, you can switch to the previous configuration in a running system:
# nixos-rebuild switch --rollback
This is equivalent to running:
# /nix/var/nix/profiles/system-N
-link/bin/switch-to-configuration switch
where N
is the number of the NixOS system
configuration. To get a list of the available configurations, do:
$
ls -l /nix/var/nix/profiles/system-*-link...
lrwxrwxrwx 1 root root 78 Aug 12 13:54 /nix/var/nix/profiles/system-268-link -> /nix/store/202b...-nixos-13.07pre4932_5a676e4-4be1055
After a system crash, it’s possible for files in the Nix store to become corrupted. (For instance, the Ext4 file system has the tendency to replace un-synced files with zero bytes.) NixOS tries hard to prevent this from happening: it performs a sync before switching to a new configuration, and Nix’s database is fully transactional. If corruption still occurs, you may be able to fix it automatically.
If the corruption is in a path in the closure of the NixOS system configuration, you can fix it by doing
#
nixos-rebuild switch --repair
This will cause Nix to check every path in the closure, and if its cryptographic hash differs from the hash recorded in Nix’s database, the path is rebuilt or redownloaded.
You can also scan the entire Nix store for corrupt paths:
#
nix-store --verify --check-contents --repair
Any corrupt paths will be redownloaded if they’re available in a binary cache; otherwise, they cannot be repaired.
Nix uses a so-called binary cache to optimise building a
package from source into downloading it as a pre-built binary. That is,
whenever a command like nixos-rebuild needs a path in the
Nix store, Nix will try to download that path from the Internet rather than
build it from source. The default binary cache is
https://cache.nixos.org/
. If this cache is unreachable, Nix
operations may take a long time due to HTTP connection timeouts. You can
disable the use of the binary cache by adding --option
use-binary-caches false
, e.g.
# nixos-rebuild switch --option use-binary-caches false
If you have an alternative binary cache at your disposal, you can use it instead:
# nixos-rebuild switch --option binary-caches http://my-cache.example.org/
This chapter describes how you can modify and extend NixOS.
By default, NixOS’s nixos-rebuild command uses the NixOS
and Nixpkgs sources provided by the nixos
channel (kept in
/nix/var/nix/profiles/per-user/root/channels/nixos
). To
modify NixOS, however, you should check out the latest sources from Git. This
is as follows:
$
git clone https://github.com/NixOS/nixpkgs$
cd nixpkgs$
git remote update origin
This will check out the latest Nixpkgs sources to
./nixpkgs
the NixOS sources to
./nixpkgs/nixos
. (The NixOS source tree lives in a
subdirectory of the Nixpkgs repository.) The
nixpkgs
repository has branches that correspond
to each Nixpkgs/NixOS channel (see Chapter 4, Upgrading NixOS for more
information about channels). Thus, the Git branch
origin/nixos-17.03
will contain the latest built and
tested version available in the nixos-17.03
channel.
It’s often inconvenient to develop directly on the master branch, since if somebody has just committed (say) a change to GCC, then the binary cache may not have caught up yet and you’ll have to rebuild everything from source. So you may want to create a local branch based on your current NixOS version:
$
nixos-version 17.09pre104379.6e0b727 (Hummingbird)$
git checkout -b local 6e0b727
Or, to base your local branch on the latest version available in a NixOS channel:
$
git remote update origin$
git checkout -b local origin/nixos-17.03
(Replace nixos-17.03
with the name of the channel you want
to use.) You can use git merge or git
rebase to keep your local branch in sync with the channel, e.g.
$
git remote update origin$
git merge origin/nixos-17.03
You can use git cherry-pick to copy commits from your local branch to the upstream branch.
If you want to rebuild your system using your (modified) sources, you need to
tell nixos-rebuild about them using the
-I
flag:
#
nixos-rebuild switch -I nixpkgs=/my/sources
/nixpkgs
If you want nix-env to use the expressions in
/my/sources
, use nix-env -f
/my/sources
/nixpkgs, or change the
default by adding a symlink in ~/.nix-defexpr
:
$
ln -s/my/sources
/nixpkgs ~/.nix-defexpr/nixpkgs
You may want to delete the symlink
~/.nix-defexpr/channels_root
to prevent root’s NixOS
channel from clashing with your own tree (this may break the
command-not-found utility though). If you want to go back to the default
state, you may just remove the ~/.nix-defexpr
directory
completely, log out and log in again and it should have been recreated with a
link to the root channels.
Table of Contents
NixOS has a modular system for declarative configuration. This system
combines multiple modules to produce the full system
configuration. One of the modules that constitute the configuration is
/etc/nixos/configuration.nix
. Most of the others live in
the
nixos/modules
subdirectory of the Nixpkgs tree.
Each NixOS module is a file that handles one logical aspect of the
configuration, such as a specific kind of hardware, a service, or network
settings. A module configuration does not have to handle everything from
scratch; it can use the functionality provided by other modules for its
implementation. Thus a module can declare options that
can be used by other modules, and conversely can define
options provided by other modules in its own implementation. For example, the
module
pam.nix
declares the option security.pam.services
that allows other
modules (e.g.
sshd.nix
)
to define PAM services; and it defines the option
environment.etc
(declared by
etc.nix
)
to cause files to be created in /etc/pam.d
.
In Chapter 5, Configuration Syntax, we saw the following structure of NixOS modules:
{ config, pkgs, ... }:
{ option definitions
}
This is actually an abbreviated form of module that only defines options, but does not declare any. The structure of full NixOS modules is shown in Example 44.1, “Structure of NixOS Modules”.
The meaning of each part is as follows.
This line makes the current Nix expression a function. The variable
| |
This list enumerates the paths to other NixOS modules that should be
included in the evaluation of the system configuration. A default set of
modules is defined in the file
| |
The attribute | |
The attribute |
Example 44.2, “NixOS Module for the “locate” Service” shows a module that handles the regular
update of the “locate” database, an index of all files in the file
system. This module declares two options that can be defined by other modules
(typically the user’s configuration.nix
):
services.locate.enable
(whether the database should be
updated) and services.locate.interval
(when the update
should be done). It implements its functionality by defining two options
declared by other modules: systemd.services
(the set of all
systemd services) and systemd.timers
(the list of commands
to be executed periodically by systemd).
Example 44.2. NixOS Module for the “locate” Service
{ config, lib, pkgs, ... }: with lib; let cfg = config.services.locate; in { options.services.locate = { enable = mkOption { type = types.bool; default = false; description = '' If enabled, NixOS will periodically update the database of files used by the locate command. ''; }; interval = mkOption { type = types.str; default = "02:15"; example = "hourly"; description = '' Update the locate database at this interval. Updates by default at 2:15 AM every day. The format is described in systemd.time(7). ''; }; # Other options omitted for documentation }; config = { systemd.services.update-locatedb = { description = "Update Locate Database"; path = [ pkgs.su ]; script = '' mkdir -m 0755 -p $(dirname ${toString cfg.output}) exec updatedb \ --localuser=${cfg.localuser} \ ${optionalString (!cfg.includeStore) "--prunepaths='/nix/store'"} \ --output=${toString cfg.output} ${concatStringsSep " " cfg.extraFlags} ''; }; systemd.timers.update-locatedb = mkIf cfg.enable { description = "Update timer for locate database"; partOf = [ "update-locatedb.service" ]; wantedBy = [ "timers.target" ]; timerConfig.OnCalendar = cfg.interval; }; }; }
An option declaration specifies the name, type and description of a NixOS configuration option. It is invalid to define an option that hasn’t been declared in any module. An option declaration generally looks like this:
options = {name
= mkOption { type =type specification
; default =default value
; example =example value
; description = "Description for use in the NixOS manual.
"; }; };
The attribute names within the name
attribute path
must be camel cased in general but should, as an exception, match the
package attribute name when referencing a Nixpkgs package. For
example, the option services.nix-serve.bindAddress
references the nix-serve
Nixpkgs package.
The function mkOption
accepts the following arguments.
type
The type of the option (see Section 44.2, “Options Types”). It may be omitted, but that’s not advisable since it may lead to errors that are hard to diagnose.
default
The default value used if no value is defined by any module. A default is not required; but if a default is not given, then users of the module will have to define the value of the option, otherwise an error will be thrown.
example
An example value that will be shown in the NixOS manual.
description
A textual description of the option, in DocBook format, that will be included in the NixOS manual.
Extensible option types is a feature that allow to extend certain types
declaration through multiple module files. This feature only work with a
restricted set of types, namely enum
and
submodules
and any composed forms of them.
Extensible option types can be used for enum
options that
affects multiple modules, or as an alternative to related
enable
options.
As an example, we will take the case of display managers. There is a central display manager module for generic display manager options and a module file per display manager backend (sddm, gdm ...).
There are two approach to this module structure:
Managing the display managers independently by adding an enable option to every display manager module backend. (NixOS)
Managing the display managers in the central module by adding an option to select which display manager backend to use.
Both approaches have problems.
Making backends independent can quickly become hard to manage. For display
managers, there can be only one enabled at a time, but the type system can
not enforce this restriction as there is no relation between each backend
enable
option. As a result, this restriction has to be
done explicitely by adding assertions in each display manager backend
module.
On the other hand, managing the display managers backends in the central module will require to change the central module option every time a new backend is added or removed.
By using extensible option types, it is possible to create a placeholder
option in the central module
(Example 44.3, “Extensible type placeholder in the service module”), and to extend
it in each backend module
(Example 44.4, “Extending services.xserver.displayManager.enable
in the gdm
module”,
Example 44.5, “Extending services.xserver.displayManager.enable
in the sddm
module”).
As a result, displayManager.enable
option values can be
added without changing the main service module file and the type system
automatically enforce that there can only be a single display manager
enabled.
Example 44.3. Extensible type placeholder in the service module
services.xserver.displayManager.enable = mkOption { description = "Display manager to use"; type = with types; nullOr (enum [ ]); };
Example 44.4. Extending services.xserver.displayManager.enable
in the gdm
module
services.xserver.displayManager.enable = mkOption { type = with types; nullOr (enum [ "gdm" ]); };
Example 44.5. Extending services.xserver.displayManager.enable
in the sddm
module
services.xserver.displayManager.enable = mkOption { type = with types; nullOr (enum [ "sddm" ]); };
The placeholder declaration is a standard mkOption
declaration, but it is important that extensible option declarations only
use the type
argument.
Extensible option types work with any of the composed variants of
enum
such as with types; nullOr (enum [ "foo"
"bar" ])
or with types; listOf (enum [ "foo" "bar"
])
.
Option types are a way to put constraints on the values a module option can take. Types are also responsible of how values are merged in case of multiple value definitions.
Basic types are the simplest available types in the module system. Basic types include multiple string types that mainly differ in how definition merging is handled.
types.attrs
A free-form attribute set.
types.bool
A boolean, its values can be true
or
false
.
types.path
A filesystem path, defined as anything that when coerced to a string
starts with a slash. Even if derivations can be considered as path, the
more specific types.package
should be preferred.
types.package
A derivation or a store path.
Integer-related types:
types.int
A signed integer.
types.ints.{s8, s16, s32}
Signed integers with a fixed length (8, 16 or 32 bits). They go from
−2n/2 to 2n/2−1 respectively (e.g. −128
to
127
for 8 bits).
types.ints.unsigned
An unsigned integer (that is >= 0).
types.ints.{u8, u16, u32}
Unsigned integers with a fixed length (8, 16 or 32 bits). They go from
0 to
2n−1 respectively (e.g. 0
to
255
for 8 bits).
types.ints.positive
A positive integer (that is > 0).
types.port
A port number. This type is an alias to
types.ints.u16
.
String-related types:
types.str
A string. Multiple definitions cannot be merged.
types.lines
A string. Multiple definitions are concatenated with a new line
"\n"
.
types.commas
A string. Multiple definitions are concatenated with a comma
","
.
types.envVar
A string. Multiple definitions are concatenated with a collon
":"
.
types.strMatching
A string matching a specific regular expression. Multiple definitions
cannot be merged. The regular expression is processed using
builtins.match
.
Value types are types that take a value parameter.
types.enum
l
One element of the list l
, e.g.
types.enum [ "left" "right" ]
. Multiple definitions
cannot be merged.
types.separatedString
sep
A string with a custom separator sep
, e.g.
types.separatedString "|"
.
types.ints.between
lowest
highest
An integer between lowest
and
highest
(both inclusive). Useful for creating
types like types.port
.
types.submodule
o
A set of sub options o
.
o
can be an attribute set, a function
returning an attribute set, or a path to a file containing such a value. Submodules are used in
composed types to create modular options. This is equivalent to
types.submoduleWith { modules = toList o; shorthandOnlyDefinesConfig = true; }
.
Submodules are detailed in
Section 44.2.4, “Submodule”.
types.submoduleWith
{
modules
,
specialArgs
? {},
shorthandOnlyDefinesConfig
? false }
Like types.submodule
, but more flexible and with better defaults.
It has parameters
modules
A list of modules to use by default for this submodule type. This gets combined
with all option definitions to build the final list of modules that will be included.
specialArgs
An attribute set of extra arguments to be passed to the module functions.
The option _module.args
should be used instead
for most arguments since it allows overriding. specialArgs
should only be
used for arguments that can't go through the module fixed-point, because of
infinite recursion or other problems. An example is overriding the
lib
argument, because lib
itself is used
to define _module.args
, which makes using
_module.args
to define it impossible.
shorthandOnlyDefinesConfig
Whether definitions of this type should default to the config
section of a module (see Example 44.1, “Structure of NixOS Modules”) if it is an attribute
set. Enabling this only has a benefit when the submodule defines an option named
config
or options
. In such a case it would
allow the option to be set with the-submodule.config = "value"
instead of requiring the-submodule.config.config = "value"
.
This is because only when modules don't set the
config
or options
keys, all keys are interpreted
as option definitions in the config
section. Enabling this option
implicitly puts all attributes in the config
section.
With this option enabled, defining a non-config
section requires
using a function: the-submodule = { ... }: { options = { ... }; }
.
Composed types are types that take a type as parameter. listOf
int
and either int str
are examples of composed
types.
types.listOf
t
A list of t
type, e.g. types.listOf
int
. Multiple definitions are merged with list concatenation.
types.attrsOf
t
An attribute set of where all the values are of
t
type. Multiple definitions result in the
joined attribute set.
types.lazyAttrsOf
for a lazy version.
types.lazyAttrsOf
t
An attribute set of where all the values are of
t
type. Multiple definitions result in the
joined attribute set. This is the lazy version of types.attrsOf
, allowing attributes to depend on each other.
foo
of this type and a definition
foo.attr = lib.mkIf false 10
, evaluating
foo ? attr
will return true
even though it should be false. Accessing the value will then throw
an error. For types t
that have an
emptyValue
defined, that value will be returned
instead of throwing an error. So if the type of foo.attr
was lazyAttrsOf (nullOr int)
, null
would be returned instead for the same mkIf false
definition.
types.loaOf
t
An attribute set or a list of t
type. Multiple
definitions are merged according to the value.
types.nullOr
t
null
or type t
. Multiple
definitions are merged according to type t
.
types.uniq
t
Ensures that type t
cannot be merged. It is
used to ensure option definitions are declared only once.
types.either
t1
t2
Type t1
or type t2
,
e.g. with types; either int str
. Multiple definitions
cannot be merged.
types.oneOf
[ t1
t2
... ]
Type t1
or type t2
and so forth,
e.g. with types; oneOf [ int str bool ]
. Multiple definitions
cannot be merged.
types.coercedTo
from
f
to
Type to
or type
from
which will be coerced to type
to
using function f
which takes an argument of type from
and
return a value of type to
. Can be used to
preserve backwards compatibility of an option if its type was changed.
submodule
is a very powerful type that defines a set of
sub-options that are handled like a separate module.
It takes a parameter o
, that should be a set, or
a function returning a set with an options
key defining
the sub-options. Submodule option definitions are type-checked accordingly
to the options
declarations. Of course, you can nest
submodule option definitons for even higher modularity.
The option set can be defined directly (Example 44.6, “Directly defined submodule”) or as reference (Example 44.7, “Submodule defined as a reference”).
Example 44.6. Directly defined submodule
options.mod = mkOption { description = "submodule example"; type = with types; submodule { options = { foo = mkOption { type = int; }; bar = mkOption { type = str; }; }; }; };
Example 44.7. Submodule defined as a reference
let modOptions = { options = { foo = mkOption { type = int; }; bar = mkOption { type = int; }; }; }; in options.mod = mkOption { description = "submodule example"; type = with types; submodule modOptions; };
The submodule
type is especially interesting when used
with composed types like attrsOf
or
listOf
. When composed with listOf
(Example 44.8, “Declaration of a list of submodules”),
submodule
allows multiple definitions of the submodule
option set (Example 44.9, “Definition of a list of submodules”).
Example 44.8. Declaration of a list of submodules
options.mod = mkOption { description = "submodule example"; type = with types; listOf (submodule { options = { foo = mkOption { type = int; }; bar = mkOption { type = str; }; }; }); };
Example 44.9. Definition of a list of submodules
config.mod = [ { foo = 1; bar = "one"; } { foo = 2; bar = "two"; } ];
When composed with attrsOf
(Example 44.10, “Declaration of attribute sets of submodules”),
submodule
allows multiple named definitions of the
submodule option set (Example 44.11, “Declaration of attribute sets of submodules”).
Example 44.10. Declaration of attribute sets of submodules
options.mod = mkOption { description = "submodule example"; type = with types; attrsOf (submodule { options = { foo = mkOption { type = int; }; bar = mkOption { type = str; }; }; }); };
Example 44.11. Declaration of attribute sets of submodules
config.mod.one = { foo = 1; bar = "one"; }; config.mod.two = { foo = 2; bar = "two"; };
Types are mainly characterized by their check
and
merge
functions.
check
The function to type check the value. Takes a value as parameter and
return a boolean. It is possible to extend a type check with the
addCheck
function
(Example 44.12, “Adding a type check”), or to fully
override the check function
(Example 44.13, “Overriding a type check”).
Example 44.12. Adding a type check
byte = mkOption { description = "An integer between 0 and 255."; type = types.addCheck types.int (x: x >= 0 && x <= 255); };
Example 44.13. Overriding a type check
nixThings = mkOption { description = "words that start with 'nix'"; type = types.str // { check = (x: lib.hasPrefix "nix" x) }; };
merge
Function to merge the options values when multiple values are set. The
function takes two parameters, loc
the option path as
a list of strings, and defs
the list of defined values
as a list. It is possible to override a type merge function for custom
needs.
Custom types can be created with the mkOptionType
function. As type creation includes some more complex topics such as
submodule handling, it is recommended to get familiar with
types.nix
code before creating a new type.
The only required parameter is name
.
name
A string representation of the type function name.
definition
Description of the type used in documentation. Give information of the type and any of its arguments.
check
A function to type check the definition value. Takes the definition value
as a parameter and returns a boolean indicating the type check result,
true
for success and false
for
failure.
merge
A function to merge multiple definitions values. Takes two parameters:
loc
The option path as a list of strings, e.g. ["boot" "loader
"grub" "enable"]
.
defs
The list of sets of defined value
and
file
where the value was defined, e.g. [ {
file = "/foo.nix"; value = 1; } { file = "/bar.nix"; value = 2 }
]
. The merge
function should return the
merged value or throw an error in case the values are impossible or
not meant to be merged.
getSubOptions
For composed types that can take a submodule as type parameter, this
function generate sub-options documentation. It takes the current option
prefix as a list and return the set of sub-options. Usually defined in a
recursive manner by adding a term to the prefix, e.g. prefix:
elemType.getSubOptions (prefix ++
[
where
"prefix"
])"prefix"
is the newly added prefix.
getSubModules
For composed types that can take a submodule as type parameter, this
function should return the type parameters submodules. If the type
parameter is called elemType
, the function should just
recursively look into submodules by returning
elemType.getSubModules;
.
substSubModules
For composed types that can take a submodule as type parameter, this
function can be used to substitute the parameter of a submodule type. It
takes a module as parameter and return the type with the submodule
options substituted. It is usually defined as a type function call with a
recursive call to substSubModules
, e.g for a type
composedType
that take an elemtype
type parameter, this function should be defined as m:
composedType (elemType.substSubModules m)
.
typeMerge
A function to merge multiple type declarations. Takes the type to merge
functor
as parameter. A null
return
value means that type cannot be merged.
f
The type to merge functor
.
Note: There is a generic defaultTypeMerge
that work
with most of value and composed types.
functor
An attribute set representing the type. It is used for type operations and has the following keys:
type
The type function.
wrapped
Holds the type parameter for composed types.
payload
Holds the value parameter for value types. The types that have a
payload
are the enum
,
separatedString
and submodule
types.
binOp
A binary operation that can merge the payloads of two same types. Defined as a function that take two payloads as parameters and return the payloads merged.
Option definitions are generally straight-forward bindings of values to option names, like
config = { services.httpd.enable = true; };
However, sometimes you need to wrap an option definition or set of option definitions in a property to achieve certain effects:
If a set of option definitions is conditional on the value of another
option, you may need to use mkIf
. Consider, for instance:
config = if config.services.httpd.enable then { environment.systemPackages = [...
];...
} else {};
This definition will cause Nix to fail with an “infinite recursion”
error. Why? Because the value of
config.services.httpd.enable
depends on the value being
constructed here. After all, you could also write the clearly circular and
contradictory:
config = if config.services.httpd.enable then { services.httpd.enable = false; } else { services.httpd.enable = true; };
The solution is to write:
config = mkIf config.services.httpd.enable { environment.systemPackages = [...
];...
};
The special function mkIf
causes the evaluation of the
conditional to be “pushed down” into the individual definitions, as if
you had written:
config = { environment.systemPackages = if config.services.httpd.enable then [...
] else [];...
};
A module can override the definitions of an option in other modules by
setting a priority. All option definitions that do not
have the lowest priority value are discarded. By default, option definitions
have priority 1000. You can specify an explicit priority by using
mkOverride
, e.g.
services.openssh.enable = mkOverride 10 false;
This definition causes all other definitions with priorities above 10 to be
discarded. The function mkForce
is equal to
mkOverride 50
.
In conjunction with mkIf
, it is sometimes useful for a
module to return multiple sets of option definitions, to be merged together
as if they were declared in separate modules. This can be done using
mkMerge
:
config = mkMerge [ # Unconditional stuff. { environment.systemPackages = [...
]; } # Conditional stuff. (mkIf config.services.bla.enable { environment.systemPackages = [...
]; }) ];
When configuration problems are detectable in a module, it is a good idea to write an assertion or warning. Doing so provides clear feedback to the user and prevents errors after the build.
Although Nix has the abort
and
builtins.trace
functions
to perform such tasks, they are not ideally suited for NixOS modules. Instead
of these functions, you can declare your warnings and assertions using the
NixOS module system.
This is an example of using warnings
.
{ config, lib, ... }: { config = lib.mkIf config.services.foo.enable { warnings = if config.services.foo.bar then [ ''You have enabled the bar feature of the foo service. This is known to cause some specific problems in certain situations. '' ] else []; } }
This example, extracted from the
syslogd
module shows how to use
assertions
. Since there can only be one active syslog
daemon at a time, an assertion is useful to prevent such a broken system
from being built.
{ config, lib, ... }: { config = lib.mkIf config.services.syslogd.enable { assertions = [ { assertion = !config.services.rsyslogd.enable; message = "rsyslogd conflicts with syslogd"; } ]; } }
Like Nix packages, NixOS modules can declare meta-attributes to provide extra
information. Module meta attributes are defined in the
meta.nix
special module.
meta
is a top level attribute like
options
and config
. Available
meta-attributes are maintainers
and
doc
.
Each of the meta-attributes must be defined at most once per module file.
{ config, lib, pkgs, ... }: { options = { ... }; config = { ... }; meta = { maintainers = with lib.maintainers; [ ericsagnes ]; doc = ./default.xml; }; }
| |
$ nix-build nixos/release.nix -A manual |
Sometimes NixOS modules need to be used in configuration but exist outside of Nixpkgs. These modules can be imported:
{ config, lib, pkgs, ... }: { imports = [ # Use a locally-available module definition in # ./example-module/default.nix ./example-module ]; services.exampleModule.enable = true; }
The environment variable NIXOS_EXTRA_MODULE_PATH
is an
absolute path to a NixOS module that is included alongside the Nixpkgs NixOS
modules. Like any NixOS module, this module can import additional modules:
# ./module-list/default.nix [ ./example-module1 ./example-module2 ]
# ./extra-module/default.nix { imports = import ./module-list.nix; }
# NIXOS_EXTRA_MODULE_PATH=/absolute/path/to/extra-module { config, lib, pkgs, ... }: { # No `imports` needed services.exampleModule1.enable = true; }
Modules that are imported can also be disabled. The option declarations, config implementation and the imports of a disabled module will be ignored, allowing another to take it's place. This can be used to import a set of modules from another channel while keeping the rest of the system on a stable release.
disabledModules
is a top level attribute like
imports
, options
and
config
. It contains a list of modules that will be
disabled. This can either be the full path to the module or a string with the
filename relative to the modules path (eg. <nixpkgs/nixos/modules> for
nixos).
This example will replace the existing postgresql module with the version defined in the nixos-unstable channel while keeping the rest of the modules and packages from the original nixos channel. This only overrides the module definition, this won't use postgresql from nixos-unstable unless explicitly configured to do so.
{ config, lib, pkgs, ... }: { disabledModules = [ "services/databases/postgresql.nix" ]; imports = [ # Use postgresql service from nixos-unstable channel. # sudo nix-channel --add http://nixos.org/channels/nixos-unstable nixos-unstable <nixos-unstable/nixos/modules/services/databases/postgresql.nix> ]; services.postgresql.enable = true; }
This example shows how to define a custom module as a replacement for an existing module. Importing this module will disable the original module without having to know it's implementation details.
{ config, lib, pkgs, ... }: with lib; let cfg = config.programs.man; in { disabledModules = [ "services/programs/man.nix" ]; options = { programs.man.enable = mkOption { type = types.bool; default = true; description = "Whether to enable manual pages."; }; }; config = mkIf cfg.enabled { warnings = [ "disabled manpages for production deployments." ]; }; }
With the command nix-build, you can build specific parts of your NixOS configuration. This is done as follows:
$
cd/path/to/nixpkgs/nixos
$
nix-build -A config.option
where option
is a NixOS option with type
“derivation” (i.e. something that can be built). Attributes of interest
include:
system.build.toplevel
The top-level option that builds the entire NixOS system. Everything else
in your configuration is indirectly pulled in by this option. This is
what nixos-rebuild builds and what
/run/current-system
points to afterwards.
A shortcut to build this is:
$
nix-build -A system
system.build.manual.manualHTML
The NixOS manual.
system.build.etc
A tree of symlinks that form the static parts of
/etc
.
system.build.initialRamdisk
,
system.build.kernel
The initial ramdisk and kernel of the system. This allows a quick way to
test whether the kernel and the initial ramdisk boot correctly, by using
QEMU’s -kernel
and -initrd
options:
$
nix-build -A config.system.build.initialRamdisk -o initrd$
nix-build -A config.system.build.kernel -o kernel$
qemu-system-x86_64 -kernel ./kernel/bzImage -initrd ./initrd/initrd -hda /dev/null
system.build.nixos-rebuild
,
system.build.nixos-install
,
system.build.nixos-generate-config
These build the corresponding NixOS commands.
systemd.units.unit-name
.unit
This builds the unit with the specified name. Note that since unit names
contain dots (e.g. httpd.service
), you need to put
them between quotes, like this:
$
nix-build -A 'config.systemd.units."httpd.service".unit'
You can also test individual units, without rebuilding the whole system,
by putting them in /run/systemd/system
:
$
cp $(nix-build -A 'config.systemd.units."httpd.service".unit')/httpd.service \ /run/systemd/system/tmp-httpd.service#
systemctl daemon-reload#
systemctl start tmp-httpd.service
Note that the unit must not have the same name as any unit in
/etc/systemd/system
since those take precedence over
/run/systemd/system
. That’s why the unit is
installed as tmp-httpd.service
here.
Table of Contents
As NixOS grows, so too does the need for a catalogue and explanation of its extensive functionality. Collecting pertinent information from disparate sources and presenting it in an accessible style would be a worthy contribution to the project.
The DocBook sources of the NixOS Manual are in the
nixos/doc/manual
subdirectory of the Nixpkgs repository.
You can quickly validate your edits with make:
$ cd /path/to/nixpkgs/nixos/doc/manual $ make
Once you are done making modifications to the manual, it's important to build it before committing. You can do that as follows:
nix-build nixos/release.nix -A manual.x86_64-linux
When this command successfully finishes, it will tell you where the manual
got generated. The HTML will be accessible through the
result
symlink at
./result/share/doc/nixos/index.html
.
For general information on how to write in DocBook, see DocBook 5: The Definitive Guide.
Emacs nXML Mode is very helpful for editing DocBook XML because it validates the document as you write, and precisely locates errors. To use it, see Section 23.3.3, “Editing DocBook 5 XML Documents”.
Pandoc can generate DocBook XML from a multitude of formats, which makes a good starting point.
Example 46.1. Pandoc invocation to convert GitHub-Flavoured MarkDown to DocBook 5 XML
pandoc -f markdown_github -t docbook5 docs.md -o my-section.md
Pandoc can also quickly convert a single section.xml
to
HTML, which is helpful when drafting.
Sometimes writing valid DocBook is simply too difficult. In this case, submit your documentation updates in a GitHub Issue and someone will handle the conversion to XML for you.
You can use an existing topic as a basis for the new topic or create a topic from scratch.
Keep the following guidelines in mind when you create and add a topic:
The NixOS
book
element is in nixos/doc/manual/manual.xml
. It
includes several
part
s
which are in subdirectories.
Store the topic file in the same directory as the part
to
which it belongs. If your topic is about configuring a NixOS module, then
the XML file can be stored alongside the module definition
nix
file.
If you include multiple words in the file name, separate the words with a
dash. For example: ipv6-config.xml
.
Make sure that the xml:id
value is unique. You can use
abbreviations if the ID is too long. For example:
nixos-config
.
Determine whether your topic is a chapter or a section. If you are unsure, open an existing topic file and check whether the main element is chapter or section.
Open the parent XML file and add an xi:include
element to
the list of chapters with the file name of the topic that you created. If
you created a section
, you add the file to the chapter
file. If you created a chapter
, you add the file to the
part
file.
If the topic is about configuring a NixOS module, it can be automatically
included in the manual by using the meta.doc
attribute.
See Section 44.5, “Meta Attributes” for an explanation.
Building a NixOS CD is as easy as configuring your own computer. The idea is
to use another module which will replace your
configuration.nix
to configure the system that would be
installed on the CD.
Default CD/DVD configurations are available inside
nixos/modules/installer/cd-dvd
.
$
git clone https://github.com/NixOS/nixpkgs.git$
cd nixpkgs/nixos$
nix-build -A config.system.build.isoImage -I nixos-config=modules/installer/cd-dvd/installation-cd-minimal.nix default.nix
Before burning your CD/DVD, you can check the content of the image by mounting anywhere like suggested by the following command:
#
mount -o loop -t iso9660 ./result/iso/cd.iso /mnt/iso
When you add some feature to NixOS, you should write a test for it. NixOS
tests are kept in the directory
nixos/tests
,
and are executed (using Nix) by a testing framework that automatically starts
one or more virtual machines containing the NixOS system(s) required for the
test.
A NixOS test is a Nix expression that has the following structure:
import ./make-test-python.nix { # Either the configuration of a single machine: machine = { config, pkgs, ... }: {configuration…
}; # Or a set of machines: nodes = {machine1
= { config, pkgs, ... }: {…
};machine2
= { config, pkgs, ... }: {…
}; … }; testScript = ''Python code…
''; }
The attribute testScript
is a bit of Python code that
executes the test (described below). During the test, it will start one or
more virtual machines, the configuration of which is described by the
attribute machine
(if you need only one machine in your
test) or by the attribute nodes
(if you need multiple
machines). For instance,
login.nix
only needs a single machine to test whether users can log in on the virtual
console, whether device ownership is correctly maintained when switching
between consoles, and so on. On the other hand,
nfs.nix
,
which tests NFS client and server functionality in the Linux kernel
(including whether locks are maintained across server crashes), requires
three machines: a server and two clients.
There are a few special NixOS configuration options for test VMs:
virtualisation.memorySize
The memory of the VM in megabytes.
virtualisation.vlans
The virtual networks to which the VM is connected. See
nat.nix
for an example.
virtualisation.writableStore
By default, the Nix store in the VM is not writable. If you enable this option, a writable union file system is mounted on top of the Nix store to make it appear writable. This is necessary for tests that run Nix operations that modify the store.
For more options, see the module
qemu-vm.nix
.
The test script is a sequence of Python statements that perform various
actions, such as starting VMs, executing commands in the VMs, and so on. Each
virtual machine is represented as an object stored in the variable
if this is also the
identifier of the machine in the declarative config.
If you didn't specify multiple machines using the name
nodes
attribute, it is just machine
.
The following example starts the machine, waits until it has finished booting,
then executes a command and checks that the output is more-or-less correct:
machine.start() machine.wait_for_unit("default.target") if not "Linux" in machine.succeed("uname"): raise Exception("Wrong OS")
The first line is actually unnecessary; machines are implicitly started when
you first execute an action on them (such as wait_for_unit
or succeed
). If you have multiple machines, you can speed
up the test by starting them in parallel:
start_all()
The following methods are available on machine objects:
start
Start the virtual machine. This method is asynchronous — it does not wait for the machine to finish booting.
shutdown
Shut down the machine, waiting for the VM to exit.
crash
Simulate a sudden power failure, by telling the VM to exit immediately.
block
Simulate unplugging the Ethernet cable that connects the machine to the other machines.
unblock
Undo the effect of block
.
screenshot
Take a picture of the display of the virtual machine, in PNG format. The screenshot is linked from the HTML log.
get_screen_text
Return a textual representation of what is currently visible on the machine's screen using optical character recognition.
enableOCR
to the test attribute
set.
send_monitor_command
Send a command to the QEMU monitor. This is rarely used, but allows doing stuff such as attaching virtual USB disks to a running machine.
send_keys
Simulate pressing keys on the virtual keyboard, e.g.,
send_keys("ctrl-alt-delete")
.
send_chars
Simulate typing a sequence of characters on the virtual keyboard, e.g.,
send_keys("foobar\n")
will type the string
foobar
followed by the Enter key.
execute
Execute a shell command, returning a list
(
.
status
,
stdout
)
succeed
Execute a shell command, raising an exception if the exit status is not zero, otherwise returning the standard output.
fail
Like succeed
, but raising an exception if the
command returns a zero status.
wait_until_succeeds
Repeat a shell command with 1-second intervals until it succeeds.
wait_until_fails
Repeat a shell command with 1-second intervals until it fails.
wait_for_unit
Wait until the specified systemd unit has reached the “active” state.
wait_for_file
Wait until the specified file exists.
wait_for_open_port
Wait until a process is listening on the given TCP port (on
localhost
, at least).
wait_for_closed_port
Wait until nobody is listening on the given TCP port.
wait_for_x
Wait until the X11 server is accepting connections.
wait_for_text
Wait until the supplied regular expressions matches the textual contents
of the screen by using optical character recognition (see
get_screen_text
).
enableOCR
to the test attribute
set.
wait_for_window
Wait until an X11 window has appeared whose name matches the given
regular expression, e.g., wait_for_window("Terminal")
.
copy_file_from_host
Copies a file from host to machine, e.g.,
copy_file_from_host("myfile", "/etc/my/important/file")
.
The first argument is the file on the host. The file needs to be accessible while building the nix derivation. The second argument is the location of the file on the machine.
systemctl
Runs systemctl
commands with optional support for
systemctl --user
machine.systemctl("list-jobs --no-pager") # runs `systemctl list-jobs --no-pager` machine.systemctl("list-jobs --no-pager", "any-user") # spawns a shell for `any-user` and runs `systemctl --user list-jobs --no-pager`
To test user units declared by systemd.user.services
the
optional user
argument can be used:
machine.start() machine.wait_for_x() machine.wait_for_unit("xautolock.service", "x-session-user")
This applies to systemctl
, get_unit_info
,
wait_for_unit
, start_job
and
stop_job
.
For faster dev cycles it's also possible to disable the code-linters (this shouldn't be commited though):
import ./make-test-python.nix { skipLint = true; machine = { config, pkgs, ... }: {configuration…
}; testScript = ''Python code…
''; }
You can run tests using nix-build. For example, to run the
test
login.nix
,
you just do:
$
nix-build '<nixpkgs/nixos/tests/login.nix>'
or, if you don’t want to rely on NIX_PATH
:
$
cd /my/nixpkgs/nixos/tests$
nix-build login.nix … running the VM test script machine: QEMU running (pid 8841) … 6 out of 6 tests succeeded
After building/downloading all required dependencies, this will perform a build that starts a QEMU/KVM virtual machine containing a NixOS system. The virtual machine mounts the Nix store of the host; this makes VM creation very fast, as no disk image needs to be created. Afterwards, you can view a pretty-printed log of the test:
$
firefox result/log.html
The test itself can be run interactively. This is particularly useful when developing or debugging a test:
$
nix-build nixos/tests/login.nix -A driver$
./result/bin/nixos-test-driver starting VDE switch for network 1>
You can then take any Python statement, e.g.
>
start_all()>
test_script()>
machine.succeed("touch /tmp/foo")>
print(machine.succeed("pwd")) # Show stdout of command
The function test_script executes the entire test script and drops you back into the test driver command line upon its completion. This allows you to inspect the state of the VMs after the test (e.g. to debug the test script).
To just start and experiment with the VMs, run:
$
nix-build nixos/tests/login.nix -A driver$
./result/bin/nixos-run-vms
The script nixos-run-vms starts the virtual machines defined by test.
The machine state is kept across VM restarts in
/tmp/vm-state-
machinename
.
Building, burning, and booting from an installation CD is rather tedious, so here is a quick way to see if the installer works properly:
#
mount -t tmpfs none /mnt#
nixos-generate-config --root /mnt$
nix-build '<nixpkgs/nixos>' -A config.system.build.nixos-install#
./result/bin/nixos-install
To start a login shell in the new NixOS installation in
/mnt
:
$
nix-build '<nixpkgs/nixos>' -A config.system.build.nixos-enter#
./result/bin/nixos-enter
Going through an example of releasing NixOS 17.09:
Send an email to the nix-devel mailinglist as a warning about upcoming beta "feature freeze" in a month.
Discuss with Eelco Dolstra and the community (via IRC, ML) about what will reach the deadline. Any issue or Pull Request targeting the release should be included in the release milestone.
git tag -a -s -m "Release 17.09-beta" 17.09-beta
&& git push origin 17.09-beta
From the master branch run git checkout -b
release-17.09
.
Make sure a channel is created at http://nixos.org/channels/.
Bump the system.defaultChannel
attribute in
nixos/modules/misc/version.nix
Update versionSuffix
in
nixos/release.nix
, use git log
--format=%an|wc -l
to get the commit count
echo -n "18.03" > .version
on master.
Create a new release notes file for the upcoming release + 1, in this
case rl-1803.xml
.
Create two Hydra jobsets: release-17.09 and release-17.09-small with
stableBranch
set to false.
Remove attributes that we know we will not be able to support, especially if there is a stable alternative. E.g. Check that our Linux kernels' projected end-of-life are after our release projected end-of-life
Edit changelog at
nixos/doc/manual/release-notes/rl-1709.xml
(double
check desktop versions are noted)
Get all new NixOS modules git diff
release-17.03..release-17.09 nixos/modules/module-list.nix|grep
^+
Note systemd, kernel, glibc and Nix upgrades.
Monitor the master branch for bugfixes and minor updates and cherry-pick them to the release branch.
Re-check that the release notes are complete.
Release Nix (currently only Eelco Dolstra can do that). Make sure fallback is updated.
Change stableBranch
to true
in Hydra and wait for
the channel to update.
git tag -s -a -m "Release 15.09" 15.09
Update "Chapter 4. Upgrading NixOS" section of the manual to match new stable release version.
Update the
NIXOS_SERIES
in the
nixos-homepage
repository.
Get number of commits for the release: git log
release-14.04..release-14.12 --format=%an|wc -l
Commits by contributor: git log release-14.04..release-14.12
--format=%an|sort|uniq -c|sort -rn
Create a new topic on the Discourse instance to announce the release with the above information. Best to check how previous email was formulated to see what needs to be included.
For each release there are two release managers. After each release the release manager having managed two releases steps down and the release management team of the last release appoints a new release manager.
This makes sure a release management team always consists of one release manager who already has managed one release and one release manager being introduced to their role, making it easier to pass on knowledge and experience.
Release managers for the current NixOS release are tracked by GitHub team
@NixOS/nixos-release-managers
.
A release manager's role and responsibilities are:
manage the release process
start discussions about features and changes for a given release
create a roadmap
release in cooperation with Eelco Dolstra
decide which bug fixes, features, etc... get backported after a release
Date | Event |
---|---|
2016-07-25 | Send email to nix-dev about upcoming branch-off |
2016-09-01 | release-16.09 branch and corresponding jobsets are created,
change freeze
|
2016-09-30 | NixOS 16.09 released |