DEV Community

Shubhang Sharma
Shubhang Sharma

Posted on

Nixos the better way of system management !

Nixos Logo

Introduction

In the fast-paced world of cloud computing and virtual machine deployment, how many times have you found yourself setting up a new machine from scratch? The process can be tedious and error-prone: installing Ubuntu, downloading dependencies, configuring settings, and inevitably troubleshooting unexpected errors. It's a time-consuming cycle that can leave even the most patient developers frustrated.
But what if there was a better way? Enter NixOS, a open source Linux distribution that's changing the game in system configuration and management. In this comprehensive guide, we'll explore the world of NixOS, its underlying package manager Nix, and how it can transform your approach to system administration and development environments.

What is Nix ?

Nix is a purely functional package manager. But what does that mean? In the world of functional programming, we treat everything as immutable values - once created, they never change. Nix applies this principle to package management.

When Nix builds a package, it stores it in a unique subdirectory under /nix/store. This directory has a name that includes a cryptographic hash of all the package's dependencies and configuration options. For example:

/nix/store/b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z-firefox-33.1/
Enter fullscreen mode Exit fullscreen mode

This approach ensures that each package is isolated and its dependencies are explicitly defined. It's a departure from traditional package managers, where installing or updating software can have unforeseen consequences on other parts of the system.

Key Features of Nix

  1. Multiple Versions and Variants: With Nix, you can have multiple versions or variants of a package installed simultaneously. This is a game-changer for developers who need to work with different versions of libraries or tools for various projects.

  2. Atomic Upgrades and Rollbacks: Package installation and upgrades are atomic operations. This means they either complete successfully or leave the system unchanged. If an upgrade goes wrong, you can easily roll back to the previous version.

  3. Reproducible Builds: Nix's approach ensures that builds are reproducible. Given the same inputs, Nix will always produce the same output, making it easier to recreate development environments and debug issues.

  4. Multi-User Support: Nix allows non-privileged users to securely install software. Each user can have their own "profile" with a unique set of packages, without interfering with other users' setups.

  5. Garbage Collection: Nix includes a garbage collector that can safely delete unused packages, helping to keep your system clean and efficient.

  6. Source and Binary Distribution: While Nix can build packages from source, it also supports binary caches. This means you can quickly install pre-built binaries instead of compiling everything from scratch.

Now that we understand Nix, let's explore NixOS, a Linux distribution that extends Nix principles to the entire operating system.

The Nix Expression Language

At the heart of Nix is its own domain-specific language for defining packages. This Nix expression language is purely functional and allows for powerful and flexible package definitions.

What is NixOS?

NixOS is a free and opensource Linux distribution based on the Nix package manager. It takes the concepts of reproducibility, declarative configuration, and reliable upgrades from Nix and applies them to the entire system configuration.
In NixOS, everything from the kernel and system services to user applications is managed by Nix. This means your entire system configuration is defined in Nix expressions, typically in a single file: /etc/nixos/configuration.nix.

A Brief History of NixOS

Its journey began in 2003 when Eelco Dolstra started Nix as a research project. The goal was to address the complexities and inconsistencies in traditional package management systems.
As Nix matured, the idea of applying its principles to an entire operating system took shape, leading to the birth of NixOS. In 2015, the NixOS Foundation was established to support the ongoing development and promotion of both Nix and NixOS.

Key Features of NixOS

  1. Declarative System Configuration: Instead of imperatively issuing commands to change your system, you declare the desired state of your system in a configuration file. NixOS takes care of making it happen.

  2. Reliable Upgrades: Because the entire system configuration is built from a Nix expression, upgrading your system is as reliable as doing a fresh install. There's no accumulation of cruft or leftover files from previous configurations.

  3. Atomic Upgrades: System upgrades are atomic. If an upgrade is interrupted (e.g., by a power failure), your system will still boot into either the old or the new configuration, never an inconsistent mix of the two.

  4. Easy Rollbacks: If a new configuration doesn't work as expected, you can easily roll back to a previous known-good configuration. This even applies to the kernel and bootloader!

  5. Reproducible System Configurations: You can replicate your exact system configuration on another machine by simply copying your configuration file. This is invaluable for setting up development environments or deploying consistent server configurations.

  6. Safe Testing of Changes: NixOS provides tools to safely test system changes before applying them permanently.

Installation

• Download the iso file.

• You can download to the physical hardware by flashing the iso on a pendrive and then booting it up or just booting it up on virtual machine which i will prefer for beginners.

After downloading nixos to your machine you can follow from here.

• Navigate to the directory /etc/nixos.

• There will be two files in this directory

configuration.nix  hardware-configuration.nix
Enter fullscreen mode Exit fullscreen mode

• configuration.nix for nixos configuration and hardware-configuration.nix for hardware configuration of your machine.

• Now open the configuration.nix in your text editor of choice it will look something like this

# Edit this configuration file to define what should be installed on
# your system.  Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running 'nixos-help').

{ config, pkgs, ... }:

{
  imports =
    [ # Include the results of the hardware scan.
    ./hardware-configuration.nix
    ];

  # Bootloader.
  boot.loader.grub.enable = true;
  boot.loader.grub.device = "/dev/sda";
  boot.loader.grub.useOSProber = true;

  networking.hostName = "nixos"; # Define your hostname.
  # networking.wireless.enable = true;  # Enables wireless support via wpa_supplicant.

  # Configure network proxy if necessary
  # networking.proxy.default = "http://user:password@proxy:port/";
  # networking.proxy.noProxy = "127.0.0.1,localhost,internal.domain";

  # Enable networking
  networking.networkmanager.enable = true;

  # Setup Zsh
  programs.zsh.enable = true;
  users.defaultUserShell = pkgs.zsh;

  # Set your time zone.
  time.timeZone = "Asia/Kolkata";

  # Select internationalisation properties.
  i18n.defaultLocale = "en_IN";

  i18n.extraLocaleSettings = {
    LC_ADDRESS = "en_IN";
    LC_IDENTIFICATION = "en_IN";
    LC_MEASUREMENT = "en_IN";
    LC_MONETARY = "en_IN";
    LC_NAME = "en_IN";
    LC_NUMERIC = "en_IN";
    LC_PAPER = "en_IN";
    LC_TELEPHONE = "en_IN";
    LC_TIME = "en_IN";
  };

  # Configure keymap in X11
  services.xserver.xkb = {
    layout = "us";
    variant = "";
  };

  # Define a user account. Don't forget to set a password with 'passwd'.
  users.users.shubhang = {
    isNormalUser = true;
    description = "shubhang";
    extraGroups = [ "networkmanager" "wheel" "docker" ];
    packages = with pkgs; [];
  };

  # Allow unfree packages
  nixpkgs.config.allowUnfree = true;

  # List packages installed in system profile. To search, run:
  # $ nix search wget
  environment.systemPackages = with pkgs; [
    vim
    wget
    ffmpeg
  ];

  environment = {
    sessionVariables = {
      LD_LIBRARY_PATH = "${pkgs.stdenv.cc.cc.lib}/lib";
    };
  };

  # Some programs need SUID wrappers, can be configured further or are
  # started in user sessions.
  # programs.mtr.enable = true;
  # programs.gnupg.agent = {
  #   enable = true;
  #   enableSSHSupport = true;
  # };

  # List services that you want to enable:

  # Enable the OpenSSH daemon.
  services.openssh = {
    enable = true;
    settings = {
      PermitRootLogin = "prohibit-password";
    };
  };    

  # Docker Setup
  virtualisation.docker.enable = true;
  virtualisation.docker.rootless = {
    enable = true;
    setSocketVariable = true;
  };

  # Open ports in the firewall.
  #networking.firewall.allowedTCPPorts = [ 80 22 9443 8080 443 9090 9999 5000 ];
  # networking.firewall.allowedUDPPorts = [ ... ];
  # Or disable the firewall altogether.
  networking.firewall.enable = false;

  # This value determines the NixOS release from which the default
  # settings for stateful data, like file locations and database versions
  # on your system were taken. It's perfectly fine and recommended to leave
  # this value at the release version of the first install of this system.
  # Before changing this value read the documentation for this option
  # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
  system.stateVersion = "24.05"; # Did you read the comment?
}
Enter fullscreen mode Exit fullscreen mode

You can see and understand how easy and readable everything is.

• You can setup zsh by

programs.zsh.enable = true;
users.defaultUserShell = pkgs.zsh;
Enter fullscreen mode Exit fullscreen mode

• You can change your timezone by editing

time.timeZone = "Asia/Kolkata";
Enter fullscreen mode Exit fullscreen mode

• You can also edit your locales keyboard layout users and their groups packages and much more from this config !

• You can just add packages you want to the environment.systemPackages like this

environment.systemPackages = with pkgs; [
  vim
  wget
  ffmpeg
  python3
];
Enter fullscreen mode Exit fullscreen mode

• You can also setup docker and ssh like this

# Enable the OpenSSH daemon.
services.openssh = {
  enable = true;
  settings = {
    PermitRootLogin = "prohibit-password";
  };
};

# Enable the Docker daemon
virtualisation.docker.enable = true;
virtualisation.docker.rootless = {
  enable = true;
  setSocketVariable = true;
};
Enter fullscreen mode Exit fullscreen mode

• You can do anything you want to your system by just changing the configuration.nix and will be same for every nix system that have that configuration.nix file !

After you made changes to your nixos you can recompile the configuration.nix by running

sudo nixos-rebuild switch
Enter fullscreen mode Exit fullscreen mode

This command does several things:

  1. It evaluates your configuration file.
  2. It builds all necessary packages and configuration files.
  3. It creates a new system generation.
  4. It updates the bootloader to include the new generation.
  5. It activates the new configuration.

System Generations

Every time you rebuild your system, NixOS creates a new "generation". A generation is a complete snapshot of your system configuration. This is what enables NixOS's powerful rollback capabilities.

You can list all available generations with:

sudo nix-env --list-generations --profile /nix/var/nix/profiles/system
Enter fullscreen mode Exit fullscreen mode

And roll back to a previous generation with:

sudo nixos-rebuild switch --rollback
Enter fullscreen mode Exit fullscreen mode

NixOS in the Cloud

NixOS shines in cloud environments. Its declarative configuration model makes it easy to provision and manage cloud instances. Many cloud providers, including Amazon EC2, Google Cloud Platform, and DigitalOcean, offer NixOS images.

Moreover, NixOS works well with infrastructure-as-code tools like Terraform, allowing you to version control not just your application code, but your entire infrastructure configuration.

NixOS for Developers

For developers, NixOS offers several compelling features:

  1. Reproducible Development Environments: With nix-shell, you can create isolated development environments for your projects, ensuring all developers have the same set of tools and libraries.

  2. Easy Testing of System Changes: The nixos-rebuild build-vm command allows you to test system changes in a virtual machine before applying them to your actual system.

  3. Declarative Docker Images: You can use Nix to build reproducible Docker images, ensuring consistency between your development and production environments.

Challenges and Considerations

While NixOS offers many advantages, it's important to be aware of some challenges:

  1. Learning Curve: The Nix expression language and the NixOS way of doing things can take some time to learn, especially for those used to traditional Linux distributions.

  2. Community Size: While growing, the NixOS community is smaller than those of more mainstream distributions, which can sometimes mean less community support and fewer packages.

  3. Resource Usage: The Nix store can consume significant disk space, as it keeps multiple versions of packages.

  4. Customization Complexity: While NixOS is highly customizable, making deep system changes can sometimes require more effort than in traditional distributions.

Conclusion

NixOS represents a paradigm shift in how we approach system configuration and package management. Its principles of reproducibility, declarative configuration, and reliable upgrades offer solutions to many long-standing problems in system administration and software development.

While it comes with a learning curve, the benefits of NixOS can be substantial, especially for developers, system administrators, and organizations dealing with complex, multi-environment deployments.

As we move towards more automated, reproducible, and version-controlled infrastructure, tools like NixOS are becoming increasingly relevant. Whether you're managing a fleet of servers, developing complex software, or just want more control and reliability in your personal computing environment, NixOS is definitely worth exploring.

Welcome to the world of NixOS!

Additional Docs

Nix Manual
Nixos Manual
Nix Packages Manual
Nixos Thesis

by Shubhang.

Top comments (0)