Jump to content

NixOS: Difference between revisions

From NixOS Wiki
imported>Ixxie
No edit summary
DoggoBit (talk | contribs)
m add navbox
 
(87 intermediate revisions by 36 users not shown)
Line 1: Line 1:
{{Expansion|This article is incomplete.}}
{{Navbox Nix}}
{{Expansion|reason=It needs to be an easy introduction, because its one of the first articles new users read here. Thats why it needs to be simplified a bit and more complex topics should be moved to other articles.}}


[https://nixos.org/ NixOS] is a Linux distribution based on the [[Nix Package Manager]]. It supports reproducible and declarative system-wide configuration management as well as atomic upgrades and rollbacks. Alongside this declarative operation mode, NixOS supports imperative package and user management. In NixOS, all components of the distribution - including the kernel, system packages and configuration files - are built by [[Nix Package Manager|Nix]] from purely functional [[Nix Expression Language|Nix Expressions]]. Since Nix supports binary caching, this provides a convenient compromise between source-based and binary approaches, allowing the use of a binaries for standard components and custom built packages and modules when needed. Stable NixOS releases are delivered biannually, with the latest stable version being 17.03. NixOS was created by Eelco Dolstra and Armijn Hemel, and initially released in 2003. It is community developed and maintained under the stewardship of the [https://nixos.org/nixos/foundation.html NixOS Foundation].
[https://nixos.org/ NixOS] is a Linux distribution based on the [[Nix]] package manager and build system. It supports [https://en.wikipedia.org/wiki/Declarative_programming declarative] system-wide [https://en.wikipedia.org/wiki/Configuration_management configuration management] as well as [https://en.wikipedia.org/wiki/Atomicity_(database_systems) atomic] upgrades and rollbacks, although it can additionally support [https://en.wikipedia.org/wiki/Imperative_programming imperative] package and user management. In NixOS, all components of the distribution — including the [https://en.wikipedia.org/wiki/Linux_kernel kernel], installed [https://en.wikipedia.org/wiki/Package_manager packages] and system configuration files — are built by [[Nix]] from [[Wikipedia:Pure function|pure functions]] called [[Nix Expression Language|Nix expressions]].


== Usage ==
Since Nix uses [https://en.wikipedia.org/wiki/Executable binary] caching, this provides a unique compromise between the binary-oriented approach used by distributions such as Debian and the [https://en.wikipedia.org/wiki/Source_code source]-oriented approach used by distributions such as Gentoo. Binaries can be used for standard components, and custom-built packages and modules can be used automatically when a pre-built binary is not available.
 
Stable NixOS releases are delivered twice a year (around the end of May and the end of November). NixOS was created by [https://edolstra.github.io/ Eelco Dolstra] and [https://en.wikipedia.org/wiki/Armijn_Hemel Armijn Hemel], and initially released in 2003. It is community developed and maintained under the stewardship of the [[Nix_Community#NixOS_Foundation|NixOS Foundation]].
 
== Installation ==
 
For a full installation guide, see the [https://nixos.org/nixos/manual/index.html#ch-installation Installation chapter of the NixOS manual]. This wiki also includes alternative or supplemental guides, such as [[NixOS as a desktop]].
 
Most users will install NixOS via [https://nixos.org/download/#nixos-iso one of the ISO images.] Both "graphical" and "minimal" ISO variants are available for each supported architecture; the "graphical" images are suitable for users intending to install a desktop environment, and the "minimal" images are suitable for users intending to install NixOS in a server role or desiring a smaller ISO image. The ISO images are hybrid images which can be burnt to optical media or copied raw to a USB drive and booted as-is. See the installation guide for details.
 
In addition to the ISO images, the [https://nixos.org/download/#nixos-iso download page] provides a number of alternative methods for installing NixOS. These include:
 
* Virtual appliances in OVA format (compatible with VirtualBox);
* Amazon EC2 AMIs;
 
Additionally, many existing Linux installations can be converted into NixOS installations using [https://github.com/elitak/nixos-infect nixos-infect] or [https://github.com/jeaye/nixos-in-place nixos-in-place]; this is particularly useful for installing NixOS on hosting providers which do not natively support NixOS.


=== Installation ===
=== System architectures ===
NixOS provides out of the box support for most x86_64 devices, and generic ARM64 devices.


For a full installation guide using the ISOs - including steps for installing with USB stick and on UEFI systems - see the [https://nixos.org/nixos/manual/index.html#ch-installation installation chapter of the manual].
==== 32-bit x86 architectures ====
Support for 32-bit x86 architectures (i.e. <code>i686</code>) has been declining. While most packages should still compile and run, their cache availability is significantly reduced<ref>https://discourse.nixos.org/t/limited-cache-availability-for-i686-32-bits-x86-architecture/37626</ref>. The 32-bit x86 ISO is no longer offered as a ready-built image, but it may still be built manually.


In addition to graphical and minimal 64bit and 32bit ISOs, the [https://nixos.org/nixos/download.html NixOS download page] provides a variety of formats for installing NixOS. These include virtual appliances in OVA format (compatible with Virtual Box), Amazon EC2 AMIs and Microsoft Azure BLOBs. Additionally, one can convert a variety of existing Linux installations into NixOS using [https://github.com/elitak/nixos-infect nixos-infect] and [https://github.com/jeaye/nixos-in-place nixos-in-place]; this is particularly useful for installing NixOS on hosting providers such as Digital Ocean, which have no NixOS images available out-of-the-box. For instructions on installing NixOS on various ARM boards, see [[NixOS on ARM]].
==== 64-bit x86 architectures ====
Most <code>x86_64</code> devices should run NixOS without issues.


=== Declarative Configuration ===
==== 32-bit ARM architectures ====
{{Main|NixOS on ARM}}
NixOS isn't officially supported on ARM32 devices (e.g. <code>armv6</code> and <code>armv7l</code>), however, for some of these devices, there may be community support.


One of NixOS's most distinguishing features is the ability to ''declaratively configure'' the whole system. This is done by specifying a configuration file which defines which packages are installed on the system, which services to run and various other settings and options. This file is normally called <code>configuration.nix</code> and is found by default at <code>/etc/nixos</code>, although another location can be set using the environment variable <code>NIX_PATH</code>. The system configuration is then built with the command <code>nixos-rebuild</code>. The following is an example of a <code>configuration.nix</code> file:
==== 64-bit ARM architectures ====
{{Main|NixOS on ARM}}
As long as a device supports the generic systemd boot process, NixOS should run out of the box. However, specific devices with proprietary bootloaders may have issues running it.


<syntaxhighlight lang="nix">
==== MIPS architectures ====
{ config, pkgs, ... }:
{{Main|NixOS on MIPS}}
There used to be limited support for MIPS architectures in NixOS, and remnants of this support may still be found in Nixpkgs. However, there is no official support.


{
== Usage ==
    # Import other configuration modules
    # (hardware-configuration.nix is autogenerated upon installation)
    # paths in nix expressions are always relative the file which defines them
    imports =
        [
            ./hardware-configuration.nix
            ./my-dev-tools.nix
            ./my-desktop-env.nix
            ./etc.nix
        ];


    # Name your host machine
=== Declarative Configuration ===
    networking.hostName = "mymachine";


    # Set your time zone.
One of NixOS's defining features is its declarative configuration model, where the entire system state — including installed packages, system services, and settings — is described in configuration files. The primary file is typically located at <code>/etc/nixos/configuration.nix</code>.
    time.timeZone = "Europe/Utrecht";


    # Enter keyboard layout
Changes to the configuration are applied atomically using <code>nixos-rebuild switch</code>, ensuring reproducibility and the ability to roll back to previous states. Most users track their configuration files in a version control system, enabling consistent and portable system setups. These shortcomings are often rectified after-the-fact if at all by configuration management solutions such as Puppet, Ansible or Chef. These tools reconcile system configuration with a description of the expected state. However, these tools are not integrated into the operating system design and are simply layered on top, and OS configuration may still vary where an aspect of OS configuration has not been specified in the description of expected state.  
    services.xserver.layout = "us";
    services.xserver.xkbVariant = "altgr-intl";


    # Define user accounts
Unlike conventional distributions, where system configuration is often scattered across manually edited files, NixOS integrates configuration management directly into the operating system. This eliminates configuration drift and makes NixOS particularly well-suited for automated, reproducible deployments.
    users.users =
        {
            myuser =
            {
                home = "/home/myuser";
                extraGroups = [ "wheel" "networkmanager" ];
                isNormalUser = true;
                uid = 1000;
            };
        };
   
    # Install some packages
    environment.systemPackages =
            with pkgs;
            [
                ddate
                testdisk
                zsh
            ];
    # Enable the OpenSSH daemon
    services.openssh.enable = true;
   
}
</syntaxhighlight>


For inspiration, a variety of NixOS configuration files made by community members can be found in the [[Configuration Collection]].
For more details and examples on NixOS configurations, see [[NixOS system configuration]].


=== Imperative Operations ===
=== Imperative Operations ===


====  User Environment Management ====
While NixOS is typically configured declaratively as much as possible, these are a few domains where imperative operations are still necessary; these include user environment management and channel management.


In addition to declarative system configuration, NixOS offers imperative commands to manage ''user specific'' package management. These operations are managed by the <code>nix-env</code> command line tool. The following is a summary of some common operations that can be performed with it:
====  User Environments ====


''Common <code>nix-env</code> Commands:''
In addition to declarative system configuration, NixOS users can utilize Nix's imperative <code>nix-env</code> command to install packages at the user level, without changing the system state. See the [[Nix#User Environments| user environments section of the Nix article]] for more information.
{| class="wikitable"
|Searching for packages
|<code>nix-env -qaP '.*packagename.*'</code>
|-
|Installing a package
|<code>nix-env -i packagename</code>
|-
|List installed packages
|<code>nix-env -q</code>
|-
|Uninstall packages
|<code>nix-env -e packagename</code>
|-
|Upgrade packages
|<code>nix-env -u</code>
|}


==== Channels ====
==== Channels ====


Nix ''channels'' are mechanisms for distributing Nix expressions alongside the associated binaries for them. Official Nix channels are automatically updated once a certain tests are passed in Nixpkgs' Hydra instance. It is also possible to create one's own Nix channels, but here we focus the official channels. A full list of the available official channels is available at [https://nixos.org/channels/ https://nixos.org/channels/], but they can be classified into three main types.
In the [[Nix ecosystem]], [[Channel branches|channels]] are a mechanism for distributing collections of [[Nixpkgs|Nix packages]] and [[NixOS]] module definitions. A channel represents a curated, versioned set of package definitions and system configurations, typically corresponding to a particular release or the latest available development state.


''Channel Types:''
When using channels, your system or [[User Environment|user environment]] pulls package definitions and options from a URL pointing to a specific snapshot of the Nix Packages collection (Nixpkgs) and associated NixOS modules.
{|  class="wikitable"
|Stable
|''nixos-17.03''
|These receive conservative updates for fixing bugs and security vulnerabilities.
|-
|Unstable
|''nixos-unstable''
| Corresponds to the main development branch of Nixpkgs, delivering the latest tested updates.
|-
|Small
|''nixos-17.03-small'', ''nixos-unstable-small''
| Identical to their normal namesakes, but containing fewer binaries. This means they update faster but require more to be built from source.
|}


NixOS will use the root's channels to update the system wide configuration, and user-specific channels to manage the user environment; this means that you must <code>sudo</code> commands intended to manage the channel your <code>configuration.nix</code> should use. The following are common commands to manage channels on NixOS:
For more information on using and configuring nix channels, refer to [[channel branches]].


{|  class="wikitable"
== Internals ==
|Listing current channels
|<code>nix-channel --list</code>
|-
| Adding a primary channel
|<code><nowiki>nix-channel --add https://nixos.org/channels/channel-name nixos</nowiki></code>
|-
| Adding other channels
|<code><nowiki>nix-channel --add https://some.channel/url my-alias</nowiki></code>
|-
| Remove a channel
|<code>nix-channel --remove channel-alias</code>
|-
| Updating a channel
|<code>nix-channel --update channel-alias</code>
|-
| Updating all channels
|<code>nix-channel --update</code>
|}


Note that after updating channels, one still has to rebuild with <code>nixos-rebuild switch</code>, but one can also run <code>nixos-rebuild switch --upgrade</code> to update channels and rebuild.
=== Comparison with traditional Linux Distributions ===


== Internals ==
''Main Article: [[Nix vs. Linux Standard Base]]''
 
The main difference between NixOS and other Linux distributions is that NixOS does not follow the [https://en.wikipedia.org/wiki/Linux_Standard_Base Linux Standard Base] file system structure. On LSB-compliant systems software is stored under <code>/{,usr}/{bin,lib,share}</code> and configuration is generally stored in <code>/etc</code>. Software binaries are available in the user environment if they are placed in one of the LSB's <code>/bin</code> directories. When a program references dynamic libraries it will search for the required libraries in the LSB folders (<code>/lib</code>, <code>/usr/lib</code>).
 
In NixOS however <code>/lib</code> and <code>/usr/lib</code> do not exist. Instead all system libraries, binaries, kernels, firmware and configuration files are placed in the [[Nix#Nix store|Nix store]]. The files and directories in <code>/nix/store</code> are named by hashes of the information describing the built data. All of the files and directories placed in the Nix store are immutable. <code>/bin</code> and <code>/usr/bin</code> are almost absent: they contain only <code>/bin/sh</code> and <code>/usr/bin/env</code> respectively, to provide minimal compatibility with existing scripts using shebang lines. User-level environments are implemented using a large number of symbolic links to all required packages and auxiliary files. These environments are called [[Nix#Profiles|profiles]] and are stored in <code>/nix/var/nix/profiles</code>, each user having their own profiles. Structuring the system in this way is how NixOS obtains its key advantages over conventional Linux distributions, such as atomicity and rollback support.
 
=== Usage of the Nix store ===
 
A lot of confusion for newcomers arises from the fact that configuration is stored in the read-only <code>/nix/store</code> tree along with all the installed packages. This fact makes it impossible to manually edit system configuration; all configuration changes must be performed by editing the <code>/etc/nixos/configuration.nix</code> file and executing <code>nixos-rebuild switch</code>. NixOS provides the [[NixOS_modules|module system]] for editing all required configurations. Users should first use [https://search.nixos.org/options the option search tool] to check if the option they need exists before attempting to manually add files or configuration via low-level NixOS features like activation scripts.
 
The system purity makes it possible to keep system configuration in a central place, without the need to edit multiple files. This configuration can be distributed or version controlled as desired. It also provides for determinism; if you provide the same inputs, the same version of Nixpkgs and the same <code>/etc/nixos/configuration.nix</code> you will get the exact same system state.
 
=== Modules ===
 
The [[NixOS modules|NixOS module system]] as defined in  [[Nixpkgs]] provides the means necessary to customize the configuration of the OS. It is used to enable and customize services such as nginx, enable firmware and customize the kernel.
 
All module configuration is generally performed by adding options to <code>/etc/nixos/configuration.nix</code>. Most of the examples in the wiki show how this file can be used to configure the OS.
 
The NixOS module system implements a typing system which allows typechecking of option settings. It also enables options defined in multiple places to be merged automatically. This allows you to spread your configuration over multiple files, and the options you set across all of those files will be merged together:
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{
  imports = [
    ./basic-webserver.nix
    ./blog.nix
  ];
}
</nowiki>}}
{{file|/etc/nixos/basic-webserver.nix|nix|<nowiki>
{
  services.nginx.enable = true;
  services.nginx.virtualHosts."example.com" = {
    root = "/var/www/example.com";
  };
}
</nowiki>}}
{{file|/etc/nixos/blog.nix|nix|<nowiki>
{
  services.nginx.virtualHosts."blog.example.com" = {
    root = "/var/www/blog.example.com";
  };
}
</nowiki>}}
 
See the [https://nixos.org/nixos/manual/index.html#sec-writing-modules Modules section of the NixOS Manual] for more details.
 
=== Generations ===
 
Every time the system state is rebuilt using <code>nixos-rebuild switch</code>, a new generation is created. You can revert to the previous generation at any time, which is useful if a configuration change (or system update) turns out to be detrimental.
 
You can roll back via:


=== Nix Store ===
<syntaxHighlight lang=shell>
$ nix-env --rollback              # roll back a user environment
$ nixos-rebuild switch --rollback  # roll back a system environment
</syntaxHighlight>


Nix parses ''Nix expressions'' written in the [[Nix Expression Language]]; these are pure functions taking dependencies as arguments and producing ''derivation'' specifying a reproducible build environment for the package. The package is then built the ''Nix store'', receiving a unique address specified by a cryptographic hash of the build's dependency graph followed by the package name and version, for example <code>/nix/store/nawl092prjblbhvv16kxxbk6j9gkgcqm-git-2.14.1</code>. This allows Nix to simultaneously install different versions of the same package, and even different builds of the same version, for example variants built with different compilers.
NixOS also places entries for previous generations in the bootloader menu, so as a last resort you can always revert to a previous configuration by rebooting. To set the currently booted generation as the default run


=== Profiles ===
<syntaxHighlight lang=shell>
$ /run/current-system/bin/switch-to-configuration boot
</syntaxHighlight>


== Development ==
Because NixOS keeps previous generations of system state available in case rollback is desired, old package versions aren't deleted from your system immediately after an update. You can delete old generations manually:


=== GitHub ===
<syntaxHighlight lang=shell>
# delete generations older than 30 days
$ nix-collect-garbage --delete-older-than 30d


# delete ALL previous generations - you can no longer rollback after running this
$ nix-collect-garbage -d                     
</syntaxHighlight>


=== Hydra ===
List generations:
<syntaxHighlight lang=shell>
# as root
$ nix-env --list-generations --profile /nix/var/nix/profiles/system
</syntaxHighlight>


== History ==
Switch generations:
<syntaxHighlight lang=shell>
# as root switch to generation 204
$ nix-env --profile /nix/var/nix/profiles/system --switch-generation 204
</syntaxHighlight>


== See also ==
delete broken generation(s):
<syntaxHighlight lang=shell>
# as root delete broken generations 205 and 206
$ nix-env --profile /nix/var/nix/profiles/system --delete-generations 205 206
</syntaxHighlight>


* [[NixOS Modules]]
You can configure automatic garbage collection by setting the [https://search.nixos.org/options?query=nix.gc nix.gc] options in <code>/etc/nixos/configuration.nix</code>. This is recommended, as it keeps the size of the Nix store down.


== See also ==


* [[NixOS modules]], a library for modular [[Overview of the Nix Expression Language#Expressions|Nix expressions]] which powers [[#Declarative Configuration|the declarative configuration of NixOS]].
* [[NixOS VM tests]], a library for creating reproducible infrastructure tests, based on [[Nixpkgs]], [[NixOS]], QEMU and Perl.
* [https://github.com/ryan4yin/nixos-and-flakes-book NixOS & Flakes Book] (Ryan4yin, 2023) - 🛠️ ❤️ An unofficial NixOS & Flakes book for beginners.


[[Category:Discussion]]
[[Category:Pedias]]
[[Category:NixOS]]
[[Category:NixOS]]
[[Category:Incomplete]]
[[Category:Nix]]

Latest revision as of 13:30, 19 June 2025

Introduction to Nix

Tools and applications

☶︎
This article or section needs to be expanded. It needs to be an easy introduction, because its one of the first articles new users read here. Thats why it needs to be simplified a bit and more complex topics should be moved to other articles. Further information may be found in the related discussion page. Please consult the pedia article metapage for guidelines on contributing.

NixOS is a Linux distribution based on the Nix package manager and build system. It supports declarative system-wide configuration management as well as atomic upgrades and rollbacks, although it can additionally support imperative package and user management. In NixOS, all components of the distribution — including the kernel, installed packages and system configuration files — are built by Nix from pure functions called Nix expressions.

Since Nix uses binary caching, this provides a unique compromise between the binary-oriented approach used by distributions such as Debian and the source-oriented approach used by distributions such as Gentoo. Binaries can be used for standard components, and custom-built packages and modules can be used automatically when a pre-built binary is not available.

Stable NixOS releases are delivered twice a year (around the end of May and the end of November). NixOS was created by Eelco Dolstra and Armijn Hemel, and initially released in 2003. It is community developed and maintained under the stewardship of the NixOS Foundation.

Installation

For a full installation guide, see the Installation chapter of the NixOS manual. This wiki also includes alternative or supplemental guides, such as NixOS as a desktop.

Most users will install NixOS via one of the ISO images. Both "graphical" and "minimal" ISO variants are available for each supported architecture; the "graphical" images are suitable for users intending to install a desktop environment, and the "minimal" images are suitable for users intending to install NixOS in a server role or desiring a smaller ISO image. The ISO images are hybrid images which can be burnt to optical media or copied raw to a USB drive and booted as-is. See the installation guide for details.

In addition to the ISO images, the download page provides a number of alternative methods for installing NixOS. These include:

  • Virtual appliances in OVA format (compatible with VirtualBox);
  • Amazon EC2 AMIs;

Additionally, many existing Linux installations can be converted into NixOS installations using nixos-infect or nixos-in-place; this is particularly useful for installing NixOS on hosting providers which do not natively support NixOS.

System architectures

NixOS provides out of the box support for most x86_64 devices, and generic ARM64 devices.

32-bit x86 architectures

Support for 32-bit x86 architectures (i.e. i686) has been declining. While most packages should still compile and run, their cache availability is significantly reduced[1]. The 32-bit x86 ISO is no longer offered as a ready-built image, but it may still be built manually.

64-bit x86 architectures

Most x86_64 devices should run NixOS without issues.

32-bit ARM architectures

Main article: NixOS on ARM

NixOS isn't officially supported on ARM32 devices (e.g. armv6 and armv7l), however, for some of these devices, there may be community support.

64-bit ARM architectures

Main article: NixOS on ARM

As long as a device supports the generic systemd boot process, NixOS should run out of the box. However, specific devices with proprietary bootloaders may have issues running it.

MIPS architectures

Main article: NixOS on MIPS

There used to be limited support for MIPS architectures in NixOS, and remnants of this support may still be found in Nixpkgs. However, there is no official support.

Usage

Declarative Configuration

One of NixOS's defining features is its declarative configuration model, where the entire system state — including installed packages, system services, and settings — is described in configuration files. The primary file is typically located at /etc/nixos/configuration.nix.

Changes to the configuration are applied atomically using nixos-rebuild switch, ensuring reproducibility and the ability to roll back to previous states. Most users track their configuration files in a version control system, enabling consistent and portable system setups. These shortcomings are often rectified after-the-fact if at all by configuration management solutions such as Puppet, Ansible or Chef. These tools reconcile system configuration with a description of the expected state. However, these tools are not integrated into the operating system design and are simply layered on top, and OS configuration may still vary where an aspect of OS configuration has not been specified in the description of expected state.

Unlike conventional distributions, where system configuration is often scattered across manually edited files, NixOS integrates configuration management directly into the operating system. This eliminates configuration drift and makes NixOS particularly well-suited for automated, reproducible deployments.

For more details and examples on NixOS configurations, see NixOS system configuration.

Imperative Operations

While NixOS is typically configured declaratively as much as possible, these are a few domains where imperative operations are still necessary; these include user environment management and channel management.

User Environments

In addition to declarative system configuration, NixOS users can utilize Nix's imperative nix-env command to install packages at the user level, without changing the system state. See the user environments section of the Nix article for more information.

Channels

In the Nix ecosystem, channels are a mechanism for distributing collections of Nix packages and NixOS module definitions. A channel represents a curated, versioned set of package definitions and system configurations, typically corresponding to a particular release or the latest available development state.

When using channels, your system or user environment pulls package definitions and options from a URL pointing to a specific snapshot of the Nix Packages collection (Nixpkgs) and associated NixOS modules.

For more information on using and configuring nix channels, refer to channel branches.

Internals

Comparison with traditional Linux Distributions

Main Article: Nix vs. Linux Standard Base

The main difference between NixOS and other Linux distributions is that NixOS does not follow the Linux Standard Base file system structure. On LSB-compliant systems software is stored under /{,usr}/{bin,lib,share} and configuration is generally stored in /etc. Software binaries are available in the user environment if they are placed in one of the LSB's /bin directories. When a program references dynamic libraries it will search for the required libraries in the LSB folders (/lib, /usr/lib).

In NixOS however /lib and /usr/lib do not exist. Instead all system libraries, binaries, kernels, firmware and configuration files are placed in the Nix store. The files and directories in /nix/store are named by hashes of the information describing the built data. All of the files and directories placed in the Nix store are immutable. /bin and /usr/bin are almost absent: they contain only /bin/sh and /usr/bin/env respectively, to provide minimal compatibility with existing scripts using shebang lines. User-level environments are implemented using a large number of symbolic links to all required packages and auxiliary files. These environments are called profiles and are stored in /nix/var/nix/profiles, each user having their own profiles. Structuring the system in this way is how NixOS obtains its key advantages over conventional Linux distributions, such as atomicity and rollback support.

Usage of the Nix store

A lot of confusion for newcomers arises from the fact that configuration is stored in the read-only /nix/store tree along with all the installed packages. This fact makes it impossible to manually edit system configuration; all configuration changes must be performed by editing the /etc/nixos/configuration.nix file and executing nixos-rebuild switch. NixOS provides the module system for editing all required configurations. Users should first use the option search tool to check if the option they need exists before attempting to manually add files or configuration via low-level NixOS features like activation scripts.

The system purity makes it possible to keep system configuration in a central place, without the need to edit multiple files. This configuration can be distributed or version controlled as desired. It also provides for determinism; if you provide the same inputs, the same version of Nixpkgs and the same /etc/nixos/configuration.nix you will get the exact same system state.

Modules

The NixOS module system as defined in Nixpkgs provides the means necessary to customize the configuration of the OS. It is used to enable and customize services such as nginx, enable firmware and customize the kernel.

All module configuration is generally performed by adding options to /etc/nixos/configuration.nix. Most of the examples in the wiki show how this file can be used to configure the OS.

The NixOS module system implements a typing system which allows typechecking of option settings. It also enables options defined in multiple places to be merged automatically. This allows you to spread your configuration over multiple files, and the options you set across all of those files will be merged together:

❄︎ /etc/nixos/configuration.nix
{
  imports = [
    ./basic-webserver.nix
    ./blog.nix
  ];
}
❄︎ /etc/nixos/basic-webserver.nix
{
  services.nginx.enable = true;
  services.nginx.virtualHosts."example.com" = {
    root = "/var/www/example.com";
  };
}
❄︎ /etc/nixos/blog.nix
{
  services.nginx.virtualHosts."blog.example.com" = {
    root = "/var/www/blog.example.com";
  };
}

See the Modules section of the NixOS Manual for more details.

Generations

Every time the system state is rebuilt using nixos-rebuild switch, a new generation is created. You can revert to the previous generation at any time, which is useful if a configuration change (or system update) turns out to be detrimental.

You can roll back via:

$ nix-env --rollback               # roll back a user environment
$ nixos-rebuild switch --rollback  # roll back a system environment

NixOS also places entries for previous generations in the bootloader menu, so as a last resort you can always revert to a previous configuration by rebooting. To set the currently booted generation as the default run

$ /run/current-system/bin/switch-to-configuration boot

Because NixOS keeps previous generations of system state available in case rollback is desired, old package versions aren't deleted from your system immediately after an update. You can delete old generations manually:

# delete generations older than 30 days
$ nix-collect-garbage --delete-older-than 30d

# delete ALL previous generations - you can no longer rollback after running this
$ nix-collect-garbage -d

List generations:

# as root
$ nix-env --list-generations --profile /nix/var/nix/profiles/system

Switch generations:

# as root switch to generation 204
$ nix-env --profile /nix/var/nix/profiles/system --switch-generation 204

delete broken generation(s):

# as root delete broken generations 205 and 206 
$ nix-env --profile /nix/var/nix/profiles/system --delete-generations 205 206

You can configure automatic garbage collection by setting the nix.gc options in /etc/nixos/configuration.nix. This is recommended, as it keeps the size of the Nix store down.

See also