NixOS
NixOS es una distribución de Linux basada en el gestor de paquetes y sistema de construcción Nix. Admite la gestión declarativa de la configuración de todo el sistema, así como actualizaciones y reversiones atómicas, aunque también puede admitir la gestión imperativa de paquetes y usuarios. En NixOS, todos los componentes de la distribución; incluido el kernel, los paquetes instalados y los archivos de configuración del sistema; son construidos por Nix a partir de funciones puras llamadas expresiones Nix.
Dado que Nix utiliza caché de binarios, esto proporciona un equilibrio único entre el enfoque orientado a binarios utilizado por distribuciones como Debian y el enfoque orientado al código fuente utilizado por distribuciones como Gentoo. Los binarios pueden utilizarse para componentes estándar, y los paquetes y módulos personalizados pueden utilizarse automáticamente cuando no hay disponible un binario precompilado.
Las versiones estables de NixOS se publican dos veces al año (alrededor de finales de mayo y finales de noviembre). NixOS fue creado por Eelco Dolstra y Armijn Hemel, y publicado inicialmente en 2003. Es desarrollado y mantenido por la comunidad bajo la supervisión de la Fundación NixOS.
Instalación
Para obtener una guía de instalación completa, consulta el capítulo de instalación del manual de NixOS. Esta wiki también incluye guías alternativas o complementarias, como NixOS como escritorio.
La mayoría de los usuarios instalarán NixOS mediante una de las imágenes ISO. Hay disponibles variantes ISO "gráfica" y "mínima" para cada arquitectura compatible; las imágenes "gráficas" son adecuadas para usuarios que planean instalar un entorno de escritorio, mientras que las imágenes "mínimas" son adecuadas para usuarios que desean instalar NixOS como servidor o prefieren una imagen ISO más pequeña.
Las imágenes ISO son imágenes híbridas que pueden grabarse en medios ópticos o copiarse directamente a una unidad USB y arrancarse tal cual. Consulta la guía de instalación para obtener más detalles.
Además de las imágenes ISO, la página de descarga ofrece varios métodos alternativos para instalar NixOS. Estos incluyen:
- Dispositivos virtuales en formato OVA (compatibles con VirtualBox);
- AMI de Amazon EC2;
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.
Arquitecturas del sistema
NixOS ofrece soporte integrado para la mayoría de dispositivos x86_64 y dispositivos ARM64 genéricos.
Arquitecturas 32-bit x86
El soporte para arquitecturas x86 de 32 bits (es decir, i686) ha ido disminuyendo. Aunque la mayoría de los paquetes todavía deberían compilarse y ejecutarse, su disponibilidad en caché se ha reducido considerablemente[1]. La ISO de x86 de 32 bits ya no se ofrece como una imagen preconstruida, pero todavía puede generarse manualmente.
Arquitecturas 64-bit x86
La mayoria de los dispositivos x86_64 deberian ejecutar NixOS sin ningun problema.
Arquitecturas 32-bit ARM
- Main article: NixOS on ARM
NixOS no tiene soporte oficial para dispositivos ARM32 (por ejemplo, armv6 y armv7l); sin embargo, para algunos de estos dispositivos puede existir soporte por parte de la comunidad.
Arquitecturas ARM de 64 bits
- Main article: NixOS on ARM
Siempre que un dispositivo sea compatible con el proceso de arranque genérico de systemd, NixOS debería funcionar sin configuración adicional. Sin embargo, algunos dispositivos específicos con cargadores de arranque propietarios pueden presentar problemas al ejecutarlo.
Arquitecturas MIPS
- Main article: NixOS on MIPS
En el pasado hubo soporte limitado para arquitecturas MIPS en NixOS, y aún pueden encontrarse vestigios de ese soporte en Nixpkgs. Sin embargo, actualmente no existe soporte oficial.
Arquitecturas RISC-V
- Main article: RISC-V
NixOS no ofrece soporte oficial para dispositivos RISC-V. Sin embargo, algunos dispositivos pueden contar con soporte de la comunidad.
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:
{
imports = [
./basic-webserver.nix
./blog.nix
];
}
{
services.nginx.enable = true;
services.nginx.virtualHosts."example.com" = {
root = "/var/www/example.com";
};
}
{
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
- NixOS modules, a library for modular Nix expressions which powers the declarative configuration of NixOS.
- NixOS VM tests, a library for creating reproducible infrastructure tests, based on Nixpkgs, NixOS, QEMU and Perl.
- NixOS & Flakes Book (Ryan4yin, 2023) - 🛠️ ❤️ An unofficial NixOS & Flakes book for beginners.
