Nix(包管理器)

Revision as of 12:11, 26 September 2025 by Loxodoromy (talk | contribs)

Nix是一个包管理器和构建系统,它解析由Nix表达式语言 (一种惰性求值的纯函数式语言) 指定的可复现的构建指令。Nix表达式是纯函数[1],它接受依赖作为参数,并为该软件包生成一个指定可复现构建环境的derivation。Nix把构建结果存储在由整个依赖树的哈希值指定的唯一地址,从而创建一个不可变的包存储 (即nix store),使得原子升级、回滚、同时安装同一软件包的不同版本成为可能,从根本上消除了依赖地狱

Introduction to Nix

Tools and applications

⤧︎
Disambiguation: 本条目介绍的是Nix包管理器。请勿与Nix生态系统Nix(语言)Nix(命令)混淆。

用法

安装

NixOS上,Nix已经被自动安装。

在其他Linux发行版或macOS上,你可以按照Nix手册中的安装部分来安装Nix。

Nix命令

Nix命令Nix参考手册中有详细说明,分为主要命令、工具命令和实验性命令。在2.0版本(发布于2018年2月)之前,命令有所不同。

配置

在NixOS上,Nix可通过nix选项配置。

独立的Nix通过nix.conf(通常在/etc/nix/下)配置。可用选项的细节在Nix参考手册中

Home Manager为单一用户管理声明式环境,也可用于配置Nix。对于系统级配置,可在Linux上使用System Manager,在macOS上使用nix-darwin。

内部细节

Nix存储(Nix store)

↱︎
This section is a candidate for splitting off into a separate article. Nix存储在概念上足够独立,有必要单独成文。 For more information, consult the related discussion page.

Nix构建得到的包放在只读的Nix存储,正常情况下在/nix/store。每个包被赋予唯一地址,该地址由加密哈希值后跟包名称和版本指定,比如/nix/store/nawl092prjblbhvv16kxxbk6j9gkgcqm-git-2.14.1。前缀哈希值来自对构建过程中所有输入的哈希,包括源文件、整个依赖树、编译器标志等。这让Nix能同时安装同一个包的不同版本,甚至同一版本的不同构建,比如不同编译器构建的变体。在添加、移除或更新包时,不会从存储中移除任何包,而是在配置文件(profiles)里添加、移除或修改指向这些包的符号链接。

清理Nix存储

有关清理Nix存储的信息,参考 NixOS手册:章节 - 清理Nix存储

Nix存储损坏

有关修复损坏的Nix存储的信息,参考 NixOS手册:章节 - Nix存储损坏

有效的Nix存储名称

Main article: 有效的Nix存储名称

配置文件(Profiles)

为了搭建一致的用户或系统环境,Nix将Nix存储的条目符号链接到配置文件。这是Nix允许回滚功能的前端:由于存储不可变,先前版本的配置文件被保留,恢复到更早的状态只需要改变符号链接到先前的配置文件。更精确地说,Nix将二进制文件符号链接到Nix存储中表示用户环境的条目。然后这些用户环境被符号链接到/nix/var/nix/profiles里被标记的配置文件,后者又被符号链接到该用户的~/.nix-profile

Sandboxing

When sandbox builds are enabled, Nix will setup an isolated environment for each build process. It is used to remove further hidden dependencies set by the build environment to improve reproducibility. This includes access to the network during the build outside of fetch* functions and files outside the Nix store. Depending on the operating system access to other resources are blocked as well (ex. inter process communication is isolated on Linux); see nix.conf section in the Nix manual for details.

Sandboxing is enabled by default on Linux, and disabled by default on macOS. In pull requests for Nixpkgs people are asked to test builds with sandboxing enabled (see Tested using sandboxing in the pull request template) because in official Hydra builds sandboxing is also used.

To configure Nix for sandboxing, set sandbox = true in /etc/nix/nix.conf; to configure NixOS for sandboxing set nix.useSandbox = true; in configuration.nix. The nix.useSandbox option is true by default since NixOS 17.09.

Alternative Interpreters

There is an ongoing effort to reimplement Nix, from the ground up, in Rust.

There is also a community-led fork of Nix 2.18 named Lix, focused on correctness, usability, and growth. While it has also ported some components of Nix to Rust, it is not a ground-up rewrite like Tvix.

Earlier attempts can be found on riir-nix

Notes

  1. 值在计算过程中不会改变。当输入不变时,函数总是得到相同的输出。