nixos-btw
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNixOS BTW: NixOS, Nix, and Flakes Administration
NixOS BTW: NixOS、Nix与Flakes管理
Administer NixOS without falling back into imperative distro muscle memory. NixOS is
declarative, functional, and atomic: the system is a value computed from a configuration,
every change becomes a new immutable generation in , and rollbacks are a
bootloader entry away. This skill keeps that model intact, then layers in the practical
stack: channels vs flakes, vs CLI, home-manager, nix-darwin, store
hygiene, overlays, module writing, secrets, and the Determinate Nix and Lix lanes.
/nix/storenixos-rebuildnixThe places NixOS breaks are NixOS-shaped: channel drift, flake input staleness, garbage
collection that nukes a needed derivation, overlays fighting, poisoning the
user profile, hardware modules missing, or people treating
like a normal Linux config file.
nix-env -i/etc/nixos/configuration.nixWhy people run it. Atomic upgrades and rollbacks, bit-for-bit reproducible systems,
disposable dev shells, fleet-wide configuration without a separate config-management tool,
and a single language for a workstation, a server, a container image, a NixOS VM, and a
macOS laptop via nix-darwin.
Versions worth pinning (verified April 2026):
Pin versions only when they shape compatibility or troubleshooting. For ordinary package
work, trust the live channel or flake lock over a stale table.
| Component | Version or date | Why it matters |
|---|---|---|
| NixOS stable | 25.11 "Xantusia" (Nov 2025) | current stable, maintained until 2026-06-30 |
| NixOS upcoming | 26.05 "Yarara" (May 2026) | next release; do not target yet for production |
| Nix (CLI / daemon) | 2.33 (Dec 2025) | stable upstream; 2.32 introduced skip-substitutable-downloads |
| default in 25.11 | Python rewrite of nixos-rebuild, default for new installs |
| home-manager | release-25.11 (Nov 2025) | matches NixOS 25.11; unstable tracks nixos-unstable |
| nix-darwin | tracks nixpkgs 25.11 and master | active macOS module system (Intel + Apple Silicon) |
| Determinate Nix | downstream, flakes-on by default | validated distribution; parallel eval, lazy trees |
| Lix | fork of Nix | compatibility-focused fork; Meson build, improved errors |
| Kernel default for 25.11 | Linux 6.12 LTS | default |
无需依赖命令式发行版的操作习惯来管理NixOS。NixOS是声明式、函数式且原子化的:系统是由配置计算出的一个值,每一次变更都会在中生成一个新的不可变世代,回滚操作只需选择启动项即可完成。本技能遵循这一模型,并涵盖实用技术栈:channels与flakes对比、与 CLI对比、home-manager、nix-darwin、存储卫生(store hygiene)、覆盖层、模块编写、密钥管理,以及Determinate Nix和Lix分支。
/nix/storenixos-rebuildnixNixOS的常见问题都带有其自身特性:channel漂移、flake输入过时、垃圾回收误删所需的派生文件、覆盖层冲突、污染用户配置文件、硬件模块缺失,或是用户将当作普通Linux配置文件处理。
nix-env -i/etc/nixos/configuration.nix人们使用NixOS的原因:原子化升级与回滚、完全可复现的系统、可丢弃的开发环境、无需额外配置管理工具即可实现全集群配置,以及使用单一语言就能管理工作站、服务器、容器镜像、NixOS虚拟机,甚至通过nix-darwin管理macOS笔记本。
值得固定的版本(2026年4月验证):
仅当版本会影响兼容性或故障排查时才固定版本。对于普通包管理工作,优先使用实时channel或flake锁文件,而非过时的版本表。
| 组件 | 版本或日期 | 重要性说明 |
|---|---|---|
| NixOS稳定版 | 25.11 "Xantusia"(2025年11月) | 当前稳定版,维护至2026年6月30日 |
| NixOS预发布版 | 26.05 "Yarara"(2026年5月) | 下一个版本;暂不推荐用于生产环境 |
| Nix(CLI / 守护进程) | 2.33(2025年12月) | 稳定上游版本;2.32版本引入skip-substitutable-downloads特性 |
| 25.11默认版本 | nixos-rebuild的Python重写版本,为新安装系统的默认选择 |
| home-manager | release-25.11(2025年11月) | 与NixOS 25.11匹配;unstable分支跟踪nixos-unstable |
| nix-darwin | 跟踪nixpkgs 25.11及master分支 | 活跃的macOS模块系统(支持Intel + Apple Silicon) |
| Determinate Nix | 下游发行版,默认启用flakes | 经过验证的发行版;支持并行求值、延迟树 |
| Lix | Nix的分支版本 | 兼容性优先的分支;采用Meson构建,错误提示更完善 |
| 25.11默认内核 | Linux 6.12 LTS | 默认 |
When to use
使用场景
- NixOS system administration: , modules, options, imports, and
configuration.nixworkflow/etc/nixos - Flake work: ,
flake.nix, inputs, outputs,flake.lock,nix flake updatenix flake check - flow:
nixos-rebuild,switch,test,boot,dry-activate, and rollbackbuild-vm - Channels, pinning, and input management: ,
nix-channel,nix registry,npins, flake inputsniv - home-manager (standalone, NixOS module, or nix-darwin module) for user-level declarative config
- nix-darwin on macOS: declarative system config, Homebrew integration, LaunchDaemons
- Nix store and derivations: ,
nix-store, GC roots,nix store, optimise-storenix-collect-garbage - Dev environments: ,
nix-shell,nix develop,shell.nix, direnv withdefault.nixnix-direnv - Overlays, overrides, and package customisation: overlays, ,
overrideAttrs, pin patchesoverride - Writing NixOS modules: options, config, assertions, conditionals, imports, ,
mkMergemkForce - Secrets management: sops-nix, agenix, nix-sops, ragenix, activation-time decryption
- Declarative disks and filesystems: disko, btrfs layouts, LUKS, ZFS, impermanence patterns
- Remote installs and imaging: nixos-anywhere, ,
nixos-install, SD images, ISO imagesnixos-generate - Hardware enablement: nixos-hardware profiles, firmware, kernel choice, GPU drivers
- Unfree and insecure packages: ,
allowUnfree,permittedInsecurePackagesNIXPKGS_ALLOW_* - Boot and generations: systemd-boot vs GRUB, kernel selection, , boot entries
nix-env --list-generations - Garbage collection strategy: retention, GC roots, , auto-optimise-store
nix.gc.automatic - Determinate Nix lane: Determinate installer, flakes-on-by-default, enterprise backports
- Lix lane: fork-specific behavior, coexistence, and migration notes
- Integration with Docker, Kubernetes, and CI: , image outputs, cachix, attic
nix build
- NixOS系统管理:、模块、选项、导入及
configuration.nix工作流/etc/nixos - Flakes相关工作:、
flake.nix、输入、输出、flake.lock、nix flake updatenix flake check - 流程:
nixos-rebuild、switch、test、boot、dry-activate及回滚操作build-vm - Channels、版本固定与输入管理:、
nix-channel、nix registry、npins、flake输入niv - home-manager(独立模式、NixOS模块或nix-darwin模块):用于用户级声明式配置
- macOS上的nix-darwin:声明式系统配置、Homebrew集成、LaunchDaemons管理
- Nix存储与派生:、
nix-store、GC根、nix store、optimise-storenix-collect-garbage - 开发环境:、
nix-shell、nix develop、shell.nix、搭配default.nix的direnvnix-direnv - 覆盖层、覆盖与包定制:overlays、、
overrideAttrs、固定补丁override - NixOS模块编写:选项、配置、断言、条件判断、导入、、
mkMergemkForce - 密钥管理:sops-nix、agenix、nix-sops、ragenix、激活时解密
- 声明式磁盘与文件系统:disko、btrfs布局、LUKS、ZFS、无状态模式(impermanence)
- 远程安装与镜像制作:nixos-anywhere、、
nixos-install、SD镜像、ISO镜像nixos-generate - 硬件支持:nixos-hardware配置文件、固件、内核选择、GPU驱动
- 非自由与不安全包:、
allowUnfree、permittedInsecurePackagesNIXPKGS_ALLOW_* - 启动与世代:systemd-boot vs GRUB、内核选择、、启动项
nix-env --list-generations - 垃圾回收策略:保留规则、GC根、、auto-optimise-store
nix.gc.automatic - Determinate Nix分支:Determinate安装器、默认启用flakes、企业级回溯补丁
- Lix分支:分支特有行为、共存与迁移说明
- 与Docker、Kubernetes及CI集成:、镜像输出、cachix、attic
nix build
When NOT to use
不适用场景
- Arch or CachyOS administration - use arch-btw
- Debian, Ubuntu, Mint, or Pop!_OS administration - use debian-ubuntu
- Fedora, RHEL, CentOS Stream, Rocky, or Alma administration - use rhel-fedora
- Kali Linux and offensive-tool distros - use kali-linux
- Shell syntax, quoting, or portability outside Nix expressions - use command-prompt
- Docker, Podman, image builds, or container runtime issues - use docker
- Kubernetes cluster or manifest work - use kubernetes
- Fleet-wide non-Nix Linux configuration via playbooks - use ansible
- Terraform or OpenTofu infrastructure code - use terraform
- Offensive or privesc testing - use lockpick
- Defensive hardening and vuln review - use security-audit
- OPNsense or pfSense appliance work - use firewall-appliance
- Arch或CachyOS管理 - 使用arch-btw
- Debian、Ubuntu、Mint或Pop!_OS管理 - 使用debian-ubuntu
- Fedora、RHEL、CentOS Stream、Rocky或Alma管理 - 使用rhel-fedora
- Kali Linux及渗透测试发行版 - 使用kali-linux
- Nix表达式之外的Shell语法、引号或可移植性问题 - 使用command-prompt
- Docker、Podman、镜像构建或容器运行时问题 - 使用docker
- Kubernetes集群或清单工作 - 使用kubernetes
- 通过Playbook进行非Nix Linux集群配置 - 使用ansible
- Terraform或OpenTofu基础设施代码 - 使用terraform
- 渗透提权测试 - 使用lockpick
- 防御加固与漏洞审查 - 使用security-audit
- OPNsense或pfSense设备管理 - 使用firewall-appliance
AI Self-Check
AI自检
Before returning NixOS or Nix commands, verify:
- Lane identified: NixOS install, Nix on non-NixOS Linux, Nix on macOS (nix-darwin or plain Nix), WSL, Determinate Nix, or Lix. Advice diverges fast.
- Channels vs flakes decided: confirm which the user has before prescribing ,
nix-channel, ornixos-rebuild --flake. Mixing without intent creates channel-lock drift.nix flake update - Flake status is current: flakes remain nominally experimental on upstream Nix but are enabled by default on Determinate Nix; recommend enabling where the user is already using flakes.
experimental-features = nix-command flakes - is not the answer: installing into the per-user profile hides state from
nix-env -iand breaks reproducibility. Use declarativeconfiguration.nix,environment.systemPackages, or an ad-hochome.packagesinstead.nix shell - No partial upgrade advice: on flakes-based systems, do not bump a single input without running after; on channels, do not change only
nixos-rebuild --flakewithout updating dependent channels too.nixos - Rebuild verb is intentional: ,
switch,test,boot,dry-activate, andbuild-vmdiffer.builddoes not persist the boot entry;testdoes not activate now;bootdoes both.switch - Known-good generation preserved: never remove the last known-good generation, and never on a system that just booted a new generation without verifying the new one survives a reboot.
nix-collect-garbage -d - GC roots respected: dev shells, direnv caches, and CI artifacts often hold GC roots. Do not recommend aggressive GC without checking first.
nix-store --gc --print-roots - Unfree / insecure gates named explicitly: set or
nixpkgs.config.allowUnfree = true;, and list insecure packages underallowUnfreePredicate. Do not default topermittedInsecurePackagesas the permanent answer.NIXPKGS_ALLOW_UNFREE=1 - Hardware module present: for fresh installs, must be regenerated with
hardware-configuration.nixand not hand-edited for filesystem UUIDs. For laptops, check nixos-hardware profile.nixos-generate-config - Kernel and initrd coherence: , initrd modules, filesystems, and bootloader agree. Do not casually swap kernels on a system with ZFS, NVIDIA, or custom out-of-tree modules.
boot.kernelPackages - Module fields real: options named in advice exist in the version of nixpkgs the user has. graveyards drift between 23.11, 24.05, 24.11, 25.05, and 25.11 - verify against the
optionstag the user pinned.nixpkgs - Secrets not put in the store: anything under ,
./secret.age, or similar must be decrypted at activation time by sops-nix or agenix, not embedded directly in a Nix string that ends up world-readable in./sops.yaml./nix/store - disko / impermanence claims match the install: declarative disk layouts change the recovery story. Confirm partition, filesystem, and subvolume layout before prescribing rollback or wipe steps.
- home-manager mode identified: standalone, NixOS module, or nix-darwin module. vs
home-manager switchvsnixos-rebuild switchis not interchangeable.darwin-rebuild switch - Overlay placement sane: overlays belong in (NixOS) or as a flake input overlay. Do not recommend global
nixpkgs.overlayson a flakes system where that path is often ignored.~/.config/nixpkgs/overlays.nix - Determinate / Lix advice scoped: Determinate's and Lix's CLI diverge from upstream in subtle places. Name the lane before suggesting daemon or CLI flags.
determinate-nixd - Diagnostic errors are not silenced: do not hide useful output with when the error text is the evidence. Use
2>/dev/nullwhen gathering.2>&1 || true - Version pins justified: if a pinned is suggested, explain why; do not change
system.stateVersionon an existing system casually - it controls migration semantics.stateVersion
在返回NixOS或Nix命令前,请验证:
- 已确定分支:NixOS安装、非NixOS Linux上的Nix、macOS上的Nix(nix-darwin或纯Nix)、WSL、Determinate Nix或Lix。不同分支的建议差异很大。
- 已确定Channels与Flakes选择:在推荐、
nix-channel或nixos-rebuild --flake前,确认用户当前使用的是哪种方式。无意混用会导致channel锁定漂移。nix flake update - Flakes状态为当前版本:上游Nix中Flakes仍名义上处于实验阶段,但Determinate Nix默认启用;若用户已在使用Flakes,建议启用。
experimental-features = nix-command flakes - 并非解决方案:安装到用户配置文件会使状态脱离
nix-env -i的管理,破坏可复现性。应使用声明式的configuration.nix、environment.systemPackages或临时的home.packages替代。nix shell - 无部分升级建议:基于Flakes的系统中,更新单个输入后必须运行;基于Channels的系统中,不能仅更新
nixos-rebuild --flake而不更新依赖的Channels。nixos - Rebuild动词选择正确:、
switch、test、boot、dry-activate和build-vm功能不同。build不会持久化启动项;test不会立即激活;boot则同时完成两者。switch - 保留已知可用的世代:切勿删除最后一个已知可用的世代,且在新世代刚启动后,未验证其能正常重启前,切勿执行。
nix-collect-garbage -d - 尊重GC根:开发环境、direnv缓存和CI制品通常持有GC根。在推荐激进的垃圾回收前,需先检查。
nix-store --gc --print-roots - 明确指定非自由/不安全包的开关:设置或
nixpkgs.config.allowUnfree = true;,并在allowUnfreePredicate下列出不安全包。切勿将permittedInsecurePackages作为永久解决方案。NIXPKGS_ALLOW_UNFREE=1 - 硬件模块已存在:对于新安装,必须使用重新生成
nixos-generate-config,且不得手动编辑文件系统UUID。对于笔记本电脑,需检查nixos-hardware配置文件。hardware-configuration.nix - 内核与initrd一致:、initrd模块、文件系统和启动加载器需保持一致。对于使用ZFS、NVIDIA或自定义树外模块的系统,切勿随意更换内核。
boot.kernelPackages - 模块字段真实存在:建议中提到的选项必须存在于用户所使用的nixpkgs版本中。23.11、24.05、24.11、25.05和25.11版本间的选项废弃情况不同,需根据用户固定的标签进行验证。
nixpkgs - 密钥未存入存储:、
./secret.age等文件中的内容必须由sops-nix或agenix在激活时解密,不得直接嵌入到Nix字符串中,否则会在./sops.yaml中变为全局可读。/nix/store - disko/无状态模式与安装匹配:声明式磁盘布局会改变恢复流程。在推荐回滚或擦除步骤前,需确认分区、文件系统和子卷布局。
- 已确定home-manager模式:独立模式、NixOS模块或nix-darwin模块。、
home-manager switch和nixos-rebuild switch不可互换。darwin-rebuild switch - 覆盖层放置合理:覆盖层应位于(NixOS)或作为flake输入覆盖层。对于Flakes系统,不建议使用全局
nixpkgs.overlays,因为该路径通常会被忽略。~/.config/nixpkgs/overlays.nix - Determinate/Lix建议已限定范围:Determinate的和Lix的CLI与上游Nix存在细微差异。在建议守护进程或CLI标志前,需明确分支。
determinate-nixd - 诊断错误未被屏蔽:当错误文本是关键证据时,切勿使用隐藏有用输出。收集信息时可使用
2>/dev/null。2>&1 || true - 版本固定有合理理由:若建议固定,需解释原因;切勿随意更改现有系统的
system.stateVersion,它控制着迁移语义。stateVersion
Workflow
工作流程
Step 1: Identify the Nix lane first
步骤1:先确定Nix分支
| Lane | Default stance | What changes |
|---|---|---|
| NixOS installed (stable 25.11) | configuration.nix or flake.nix drives everything | full system is Nix-managed; rollbacks via bootloader |
| NixOS unstable / 26.05 pre-release | treat as rolling-ish | expect breakage; verify options still exist |
| Nix on non-NixOS Linux | user-level only | host distro still owns services and boot; no |
| nix-darwin on macOS | declarative macOS config | |
| Plain Nix on macOS (no darwin) | package manager only | |
| WSL2 with NixOS | full NixOS in WSL | boot and init differ; host owns kernel |
| Determinate Nix | flakes on by default, daemon differs | |
| Lix | upstream-compatible fork | CLI mostly matches; internals, error messages, and Meson build diverge |
| 分支 | 默认立场 | 差异点 |
|---|---|---|
| 已安装NixOS(稳定版25.11) | configuration.nix或flake.nix驱动所有操作 | 整个系统由Nix管理;通过启动加载器回滚 |
| NixOS不稳定版 / 26.05预发布版 | 视为滚动更新 | 可能出现故障;需验证选项是否仍存在 |
| 非NixOS Linux上的Nix | 仅用户级管理 | 宿主发行版仍控制服务和启动;无 |
| macOS上的nix-darwin | 声明式macOS配置 | 使用 |
| macOS上的纯Nix(无darwin) | 仅作为包管理器 | 使用 |
| WSL2中的NixOS | WSL中的完整NixOS | 启动和初始化方式不同;宿主控制内核 |
| Determinate Nix | 默认启用flakes,守护进程不同 | 使用 |
| Lix | 与上游兼容的分支 | CLI基本匹配;内部实现、错误提示和Meson构建存在差异 |
Step 2: Gather current system state
步骤2:收集当前系统状态
Start narrow. Widen only when the failing layer is still unclear.
Baseline checks for every NixOS or Nix case:
bash
undefined从窄范围开始,仅当故障层仍不明确时才扩大范围。
所有NixOS或Nix场景的基线检查:
bash
undefinedIdentify OS and Nix lane
识别操作系统和Nix分支
cat /etc/os-release 2>&1 || true
nix --version
command -v nixos-version >/dev/null 2>&1 && nixos-version
command -v darwin-version >/dev/null 2>&1 && darwin-version
command -v determinate-nixd >/dev/null 2>&1 && determinate-nixd status
uname -a
cat /etc/os-release 2>&1 || true
nix --version
command -v nixos-version >/dev/null 2>&1 && nixos-version
command -v darwin-version >/dev/null 2>&1 && darwin-version
command -v determinate-nixd >/dev/null 2>&1 && determinate-nixd status
uname -a
Nix config and features
Nix配置和特性
nix config show 2>&1 | grep -E 'experimental-features|extra-experimental|substituters|trusted-users' || true
cat /etc/nix/nix.conf 2>&1 || true
nix config show 2>&1 | grep -E 'experimental-features|extra-experimental|substituters|trusted-users' || true
cat /etc/nix/nix.conf 2>&1 || true
NixOS-specific
NixOS特定检查
[[ -d /etc/nixos ]] && ls /etc/nixos
[[ -f /etc/nixos/flake.nix ]] && echo "flakes system" || echo "channels system (or flake elsewhere)"
command -v nix-channel >/dev/null 2>&1 && nix-channel --list 2>&1 || true
command -v nixos-rebuild >/dev/null 2>&1 && nixos-rebuild --help 2>&1 | head -5
[[ -d /etc/nixos ]] && ls /etc/nixos
[[ -f /etc/nixos/flake.nix ]] && echo "flakes系统" || echo "channels系统(或flake位于其他位置)"
command -v nix-channel >/dev/null 2>&1 && nix-channel --list 2>&1 || true
command -v nixos-rebuild >/dev/null 2>&1 && nixos-rebuild --help 2>&1 | head -5
Generations and boot
世代和启动
command -v nix-env >/dev/null 2>&1 && nix-env --list-generations -p /nix/var/nix/profiles/system 2>&1 | tail -5 || true
[[ -d /boot/loader/entries ]] && ls /boot/loader/entries 2>&1 | tail -10
command -v bootctl >/dev/null 2>&1 && bootctl status 2>&1 | head -20 || true
command -v nix-env >/dev/null 2>&1 && nix-env --list-generations -p /nix/var/nix/profiles/system 2>&1 | tail -5 || true
[[ -d /boot/loader/entries ]] && ls /boot/loader/entries 2>&1 | tail -10
command -v bootctl >/dev/null 2>&1 && bootctl status 2>&1 | head -20 || true
Store health and GC state
存储健康和GC状态
df -h /nix/store
du -sh /nix/store 2>&1 || true
nix-store --gc --print-roots 2>&1 | wc -l
Add subsystem probes only when the task needs them:
```bashdf -h /nix/store
du -sh /nix/store 2>&1 || true
nix-store --gc --print-roots 2>&1 | wc -l
仅当任务需要时才添加子系统探测:
```bashhome-manager
home-manager
command -v home-manager >/dev/null 2>&1 && home-manager generations | head -5
command -v home-manager >/dev/null 2>&1 && home-manager generations | head -5
flake state
flake状态
[[ -f flake.nix ]] && nix flake metadata 2>&1 | head -20
[[ -f flake.lock ]] && nix flake check --no-build 2>&1 || true
[[ -f flake.nix ]] && nix flake metadata 2>&1 | head -20
[[ -f flake.lock ]] && nix flake check --no-build 2>&1 || true
services and logs (NixOS)
服务和日志(NixOS)
systemctl --failed 2>&1 || true
journalctl -b -p warning..alert 2>&1 | tail -30 || true
systemctl --failed 2>&1 || true
journalctl -b -p warning..alert 2>&1 | tail -30 || true
hardware (NixOS)
硬件(NixOS)
lspci -k 2>&1 | grep -Ei 'vga|3d|display|network' || true
journalctl -b 2>&1 | grep -Ei 'nvrm|nvidia|amdgpu|i915|xe|drm|firmware' || true
undefinedlspci -k 2>&1 | grep -Ei 'vga|3d|display|network' || true
journalctl -b 2>&1 | grep -Ei 'nvrm|nvidia|amdgpu|i915|xe|drm|firmware' || true
undefinedStep 3: Load only the relevant reference
步骤3:仅加载相关参考文档
| Task type | Reference |
|---|---|
configuration.nix, modules, options, assertions, | |
flakes, inputs, lockfile, | |
| |
| home-manager (standalone, NixOS module, nix-darwin module) | |
overlays, | |
Nix store, | |
dev shells, | |
| disko, impermanence, nixos-anywhere, SD/ISO images, nixos-generators | |
| hardware, firmware, kernels, nixos-hardware, GPU drivers, Wayland desktop | |
| secrets: sops-nix, agenix, activation decryption, keyrings | |
| Determinate Nix, Lix, lane-specific behavior, migration notes | |
| recurring NixOS and Nix footguns, edge cases, upgrade breakage | |
Do not load every reference by default. Pick the one that matches the failure mode.
| 任务类型 | 参考文档 |
|---|---|
configuration.nix、模块、选项、断言、 | |
flakes、输入、锁文件、 | |
| |
| home-manager(独立模式、NixOS模块、nix-darwin模块) | |
覆盖层、 | |
Nix存储、 | |
开发环境、 | |
| disko、无状态模式、nixos-anywhere、SD/ISO镜像、nixos-generators | |
| 硬件、固件、内核、nixos-hardware、GPU驱动、Wayland桌面 | |
| 密钥:sops-nix、agenix、激活时解密、密钥环 | |
| Determinate Nix、Lix、分支特有行为、迁移说明 | |
| NixOS和Nix常见陷阱、边缘情况、升级故障 | |
默认不要加载所有参考文档,选择与故障模式匹配的文档即可。
Step 3.5: Stay here or hand off
步骤3.5:继续处理或移交
| Request shape | Route |
|---|---|
| NixOS install, module, flake, rebuild, rollback, store, overlay, disko, secrets | stay in nixos-btw |
Build a Docker or OCI image from Nix ( | stay here for the Nix build, hand to docker for runtime |
Deploy a NixOS box into K8s ( | start here, hand to kubernetes for the cluster side |
| Review Nix-produced container for OWASP / supply chain issues | stay for the Nix build; use security-audit for the audit |
Write a bash one-liner or zsh function that wraps | use command-prompt |
| 请求类型 | 处理方式 |
|---|---|
| NixOS安装、模块、flake、rebuild、回滚、存储、覆盖层、disko、密钥 | 留在nixos-btw处理 |
从Nix构建Docker或OCI镜像( | 在此处理Nix构建部分,移交docker处理运行时问题 |
将NixOS部署到K8s( | 在此启动处理,移交kubernetes处理集群端问题 |
| 审查Nix生成的容器是否存在OWASP/供应链问题 | 在此处理Nix构建部分,使用security-audit进行审查 |
编写包装 | 使用command-prompt |
Step 4: Change one layer at a time
步骤4:一次仅修改一层
- Fix flake or channel state before blaming .
nixos-rebuild - Run before
nixos-rebuild dry-activate --flake .#hostwhen the risk is nonzero.switch - Prefer over
testwhen the change might break login;switchdoes not persist the boot entry, so a reboot returns to a known-good generation.test - Fix option-name drift before blaming module logic: and
nix repl -f '<nixpkgs/nixos>' -I ...beat guessing.:p config.services.foo - On home-manager, run separately if it is standalone; otherwise
home-manager switchpicks it up when it is wired as a module.nixos-rebuild switch - Avoid touching . It anchors migration semantics.
system.stateVersion - Keep overlays composable: scope to , not mutating
final: prev: { ... }in-place.pkgs - Validate before GC: before deleting.
nix-store --gc --print-roots | grep <path>
- 在排查问题前,先修复flake或channel状态。
nixos-rebuild - 当存在风险时,先运行,再执行
nixos-rebuild dry-activate --flake .#host。switch - 当变更可能导致登录失败时,优先使用而非
test;switch不会持久化启动项,因此重启后会回到已知可用的世代。test - 在排查模块逻辑问题前,先修复选项名称漂移:使用和
nix repl -f '<nixpkgs/nixos>' -I ...,而非猜测。:p config.services.foo - 对于home-manager,若为独立模式,需单独运行;若作为模块集成,则
home-manager switch会自动处理。nixos-rebuild switch - 避免修改,它锚定了迁移语义。
system.stateVersion - 保持覆盖层的可组合性:限定在范围内,而非原地修改
final: prev: { ... }。pkgs - 在垃圾回收前验证:删除前使用检查。
nix-store --gc --print-roots | grep <path>
Step 5: Validate before closing
步骤5:完成前验证
bash
undefinedbash
undefinedSystem state
系统状态
nixos-version 2>&1 || true
nix-env --list-generations -p /nix/var/nix/profiles/system | tail -5
systemctl --failed 2>&1 || true
nixos-version 2>&1 || true
nix-env --list-generations -p /nix/var/nix/profiles/system | tail -5
systemctl --failed 2>&1 || true
Flake sanity
Flake完整性
[[ -f flake.nix ]] && nix flake check --no-build
[[ -f flake.nix ]] && nix flake check --no-build
Store sanity
存储完整性
nix-store --verify --check-contents 2>&1 | tail -20
df -h /nix/store
Reboot only when the boot path is understood and at least one known-good generation remains.
---nix-store --verify --check-contents 2>&1 | tail -20
df -h /nix/store
仅当启动路径明确且至少保留一个已知可用世代时,才进行重启。
---Troubleshooting Pattern
故障排查模式
Keep triage cross-layer and boring:
- Confirm the Nix lane (NixOS vs Nix-on-host, flakes vs channels, Determinate vs upstream vs Lix).
- Identify the failing layer: input state, evaluation, build, activation, or runtime service.
- Pull the right logs before changing config.
- Change one layer at a time and retest.
- Prefer rollback to reinstall. Generations are the whole point.
Core log sweep on NixOS:
bash
journalctl -b -p warning..alert
journalctl --user -b
dmesg --level=err,warn
journalctl -u nix-daemon -b
journalctl -u nixos-rebuild -b 2>&1 || trueBuild and eval failures are loudest in the rebuild output itself; pipe through
and, for opaque errors, :
--show-trace--print-build-logsbash
nixos-rebuild switch --flake .#host --show-trace --print-build-logs 2>&1 | tail -200When a problem looks "flake-only," compare one clean baseline:
- delete and re-lock, or
flake.lock - roll one input back to its previous rev via , or
nix flake lock --override-input - build the same output on another machine with the same to isolate hardware vs config.
flake.lock
保持跨层分类排查,避免复杂假设:
- 确认Nix分支(NixOS vs 宿主系统上的Nix、flakes vs channels、Determinate vs 上游 vs Lix)。
- 识别故障层:输入状态、求值、构建、激活或运行时服务。
- 在修改配置前收集正确的日志。
- 一次仅修改一层并重新测试。
- 优先回滚而非重新安装,世代特性正是NixOS的核心优势。
NixOS核心日志排查:
bash
journalctl -b -p warning..alert
journalctl --user -b
dmesg --level=err,warn
journalctl -u nix-daemon -b
journalctl -u nixos-rebuild -b 2>&1 || true构建和求值失败的信息会在rebuild输出中明确显示;可通过查看详细跟踪,对于模糊错误,使用查看构建日志:
--show-trace--print-build-logsbash
nixos-rebuild switch --flake .#host --show-trace --print-build-logs 2>&1 | tail -200当问题看起来是“仅Flakes相关”时,对比干净的基线:
- 删除并重新锁定,或
flake.lock - 通过将某个输入回滚到之前的版本,或
nix flake lock --override-input - 在另一台机器上使用相同的构建相同输出,以隔离硬件或配置问题。
flake.lock
Default Decisions
默认决策
- Declarative first. ,
nix-env -i, and one-offnix profile installtweaks are escape hatches, not workflows. If it survives across rebuilds, it belongs in the config.nixpkgs.config - Flakes when the user already has them. Do not migrate users off channels mid-troubleshoot. Do not migrate users onto flakes without naming tradeoffs (still experimental upstream, lockfile commits become a habit, registry overrides differ).
- Generations are the rollback. Before debugging, confirm the previous generation boots. That is cheaper than chasing ghosts.
- Store hygiene is boring and scheduled. Enable and
nix.gc.automaticrather than manual sweeps.nix.settings.auto-optimise-store = true; - home-manager has three modes. Standalone, NixOS module, nix-darwin module. Pick one per host and stay there.
- nix-darwin is opinionated. macOS system settings, LaunchDaemons, and Homebrew coexistence are what it owns. Do not treat it like NixOS with a different kernel.
- Disko and impermanence are declarative recovery. They shine on fresh installs and nixos-anywhere deploys; retrofitting them onto a live system is a different, harder problem.
- Secrets never go in the store. Use sops-nix or agenix with activation-time decryption.
- Pick Determinate or Lix intentionally. Both are fine; both add behavior that diverges from upstream Nix in small but real ways. Name the lane.
- Kernel changes are cross-layer. ZFS, NVIDIA, hardened kernel, and custom initrd modules all interact. Do not swap casually.
boot.kernelPackages
- 优先声明式:、
nix-env -i和一次性nix profile install调整是应急方案,而非常规工作流。若变更需在rebuild后保留,则应纳入配置文件。nixpkgs.config - 用户已使用Flakes时优先Flakes:故障排查过程中不要将用户从channels迁移到Flakes。若要迁移到Flakes,需说明权衡(上游仍处于实验阶段、锁文件需提交到版本库、注册表覆盖方式不同)。
- 世代是回滚的核心:调试前确认上一个世代可正常启动,这比排查问题更高效。
- 存储卫生需定期自动化:启用和
nix.gc.automatic,而非手动清理。nix.settings.auto-optimise-store = true; - home-manager有三种模式:独立模式、NixOS模块、nix-darwin模块。每台主机选择一种模式并保持一致。
- nix-darwin具有强主见:它负责macOS系统设置、LaunchDaemons和Homebrew共存。不要将其当作换了内核的NixOS。
- Disko和无状态模式是声明式恢复方案:它们在新安装和nixos-anywhere部署中表现出色;将其改造到现有系统是更复杂的问题。
- 密钥永远不要存入存储:使用sops-nix或agenix进行激活时解密。
- 有意选择Determinate或Lix:两者都可行;但都与上游Nix存在细微但实际的行为差异。需明确分支。
- 内核变更涉及多层:ZFS、NVIDIA、加固内核和自定义initrd模块相互影响。切勿随意更换。
boot.kernelPackages
Quick Triage Checklist
快速排查清单
| Symptom | First checks |
|---|---|
| |
| Build fails mid-derivation | |
| Boot drops to emergency shell | previous generation from bootloader menu, check |
| Flake input won't update | |
System is huge, | |
| user profile vs system config; move to |
| home-manager drift vs NixOS | standalone vs module mode, which one owns the file, |
| Unfree package refuses to build | |
| Secrets in a module show up world-readable | moved to sops-nix/agenix and re-deploy; rotate the exposed secrets |
| ZFS or NVIDIA breaks after kernel bump | |
| nix-darwin change did not apply | |
| Nothing makes sense | check gotchas reference - channel vs flake mixing, stale lock, overlay collisions, GC of an active dev shell |
| 症状 | 首次检查项 |
|---|---|
| |
| 构建中途失败 | |
| 启动进入紧急shell | 从启动加载器菜单选择上一个世代、检查 |
| Flake输入无法更新 | |
系统过大, | |
| 用户配置文件 vs 系统配置;迁移到 |
| home-manager与NixOS配置漂移 | 独立模式 vs 模块模式、谁拥有文件、 |
| 非自由包无法构建 | |
| 模块中的密钥全局可读 | 迁移到sops-nix/agenix并重新部署;轮换暴露的密钥 |
| 内核升级后ZFS或NVIDIA故障 | |
| nix-darwin变更未生效 | 使用 |
| 问题无法解释 | 查看陷阱参考文档 - channels与flakes混用、锁文件过时、覆盖层冲突、活跃开发环境被GC回收 |
Reference Files
参考文件
- -
references/configuration-and-modules.md, modules, options, assertions,/etc/nixos/configuration.nixandmkMerge, NixOS module systemmkForce - - flakes,
references/flakes-and-channels.mdanatomy, inputs and outputs,flake.nix,flake.lockverbs, channels vs flakes vs npinsnix flake - -
references/rebuild-generations-and-rollback.mdverbs, generations,nixos-rebuild, bootloader entries, rollback flownix-env --list-generations - - home-manager (standalone, NixOS module, nix-darwin module), nix-darwin system configuration on macOS
references/home-manager-and-darwin.md - - overlays,
references/overlays-packaging-and-overrides.md,overrideAttrs,override, writing derivations, patching upstreamcallPackage - - Nix store,
references/store-gc-and-builders.mdvsnix-store, GC roots,nix store, optimise-store, remote builders, Cachix and atticnix-collect-garbage - -
references/dev-shells-and-direnv.md,nix-shell,nix develop,shell.nix, flake dev shells,default.nix, per-project envnix-direnv - - disko partitioning, impermanence, nixos-anywhere, SD/ISO images with nixos-generators
references/disko-impermanence-and-imaging.md - - nixos-hardware, kernel selection, firmware, GPU drivers, Wayland and X11, display managers
references/hardware-desktop-and-kernel.md - - sops-nix, agenix, activation-time decryption, age key management, avoiding store-world-readable secrets
references/secrets-sops-and-agenix.md - - Determinate Nix (enterprise lane, daemon differences, flakes-on-by-default), Lix (compat-focused fork), coexistence
references/determinate-lix-and-lanes.md - - recurring NixOS and Nix failure patterns and edge cases
references/gotchas-and-special-situations.md
- -
references/configuration-and-modules.md、模块、选项、断言、/etc/nixos/configuration.nix和mkMerge、NixOS模块系统mkForce - - flakes、
references/flakes-and-channels.md结构、输入与输出、flake.nix、flake.lock命令、channels vs flakes vs npinsnix flake - -
references/rebuild-generations-and-rollback.md命令、世代、nixos-rebuild、启动加载器项、回滚流程nix-env --list-generations - - home-manager(独立模式、NixOS模块、nix-darwin模块)、macOS上的nix-darwin系统配置
references/home-manager-and-darwin.md - - 覆盖层、
references/overlays-packaging-and-overrides.md、overrideAttrs、override、编写派生、上游补丁callPackage - - Nix存储、
references/store-gc-and-builders.mdvsnix-store、GC根、nix store、optimise-store、远程构建器、Cachix和atticnix-collect-garbage - -
references/dev-shells-and-direnv.md、nix-shell、nix develop、shell.nix、flake开发环境、default.nix、项目级环境nix-direnv - - disko分区、无状态模式、nixos-anywhere、使用nixos-generators制作SD/ISO镜像
references/disko-impermanence-and-imaging.md - - nixos-hardware、内核选择、固件、GPU驱动、Wayland和X11、显示管理器
references/hardware-desktop-and-kernel.md - - sops-nix、agenix、激活时解密、age密钥管理、避免存储中全局可读的密钥
references/secrets-sops-and-agenix.md - - Determinate Nix(企业分支、守护进程差异、默认启用flakes)、Lix(兼容性优先分支)、共存
references/determinate-lix-and-lanes.md - - NixOS和Nix常见故障模式与边缘情况
references/gotchas-and-special-situations.md
Related Skills
相关技能
- arch-btw - Arch and CachyOS administration. Use it when the host is Arch-family and Nix is a side tool, not the system.
- debian-ubuntu - Debian-family administration. Use it when Nix runs on Debian/Ubuntu as a user-level package manager only.
- rhel-fedora - RHEL-family administration. Use it when Nix runs on Fedora/RHEL as a user-level package manager only.
- kali-linux - Kali distro workflow. Use it for Kali, not for Nix inside Kali.
- command-prompt - shell syntax, aliases, and one-liners outside Nix expressions.
- docker - container runtime and image concerns. This skill builds images with ; docker runs them.
dockerTools - kubernetes - cluster workloads once the build output leaves Nix.
- ansible - fleet config management when Nix is not the chosen tool for the job.
- terraform - IaC for cloud resources that host NixOS VMs; this skill owns the guest.
- security-audit - defensive review of a Nix-built artifact.
- update-docs - sync docs after substantial module or flake restructuring.
- arch-btw - Arch和CachyOS管理。当宿主为Arch系列且Nix仅作为辅助工具而非系统时使用。
- debian-ubuntu - Debian系列管理。当Nix仅作为用户级包管理器在Debian/Ubuntu上运行时使用。
- rhel-fedora - RHEL系列管理。当Nix仅作为用户级包管理器在Fedora/RHEL上运行时使用。
- kali-linux - Kali发行版工作流。用于Kali系统,而非Kali内部的Nix。
- command-prompt - Nix表达式之外的Shell语法、别名和单行命令。
- docker - 容器运行时和镜像相关问题。本技能使用构建镜像;docker负责运行镜像。
dockerTools - kubernetes - 构建输出离开Nix后的集群工作负载。
- ansible - 当Nix未被选为集群配置管理工具时使用。
- terraform - 托管NixOS虚拟机的云基础设施IaC;本技能负责虚拟机内部配置。
- security-audit - 对Nix生成的制品进行防御性审查。
- update-docs - 大量模块或flake重构后同步文档。
Rules
规则
- Identify the Nix lane before prescribing commands. NixOS vs Nix-on-host, channels vs flakes, Determinate vs upstream vs Lix, standalone vs module home-manager - all change the answer.
- Declarative beats imperative. If the fix is , reach for
nix-env -i,environment.systemPackages, orhome.packagesinstead. Hidden profile state is a footgun.nix shell - Know the rebuild verb. ,
switch,test,boot,dry-activate, andbuild-vmare not interchangeable.builddoes not persist across reboot;testdoes not activate now.boot - Preserve a known-good generation. Never GC aggressively right after a rebuild. Boot the new generation twice before pruning.
- Flakes are intentional. Enable where the user already uses them; do not push migration during troubleshooting.
nix-command flakes - GC roots are real state. Dev shells, direnv caches, and CI pins hold them. Check before mass deletion.
- Secrets never in the store. Use sops-nix or agenix with activation-time decryption; anything else ends up world-readable in .
/nix/store - Module options must exist in the user's nixpkgs tag. 23.11/24.05/24.11/25.05/25.11 drift is real; confirm with or the options search before recommending.
nix repl - Overlays compose, not mutate. scope. Do not recommend global profile-level overlays on flake systems.
final: prev: { ... } - Kernel and initrd agree. Do not flip on ZFS, NVIDIA, or custom-module systems without a fallback.
boot.kernelPackages - Do not touch casually. It controls migration semantics and is not a "version bump" field.
system.stateVersion - Disko and impermanence are install-time decisions. Retrofit is a different, harder conversation.
- home-manager mode is sticky. Pick standalone, NixOS module, or darwin module per host and stay there.
- Determinate and Lix diverge at the edges. Name the lane before suggesting daemon or CLI flags.
- Reach for common Nix failure patterns before exotic explanations. Channel/flake mixing, stale lock, overlay collision, option drift, GC of an active dev shell, and unfree/insecure gates explain a large share of the chaos.
- 在推荐命令前确定Nix分支:NixOS vs 宿主系统上的Nix、channels vs flakes、Determinate vs 上游 vs Lix、独立模式 vs 模块模式home-manager - 这些都会改变解决方案。
- 声明式优于命令式:若解决方案是,则优先选择
nix-env -i、environment.systemPackages或home.packages。隐藏的配置文件状态是陷阱。nix shell - 了解Rebuild动词的区别:、
switch、test、boot、dry-activate和build-vm不可互换。build不会跨重启持久化;test不会立即激活。boot - 保留已知可用的世代:重建后切勿立即进行激进的GC。在修剪前需启动新世代两次确认正常。
- Flakes需有意使用:在用户已使用Flakes的情况下启用;故障排查期间不要推动迁移。
nix-command flakes - GC根是真实状态:开发环境、direnv缓存和CI固定持有GC根。批量删除前需检查。
- 密钥永远不要存入存储:使用sops-nix或agenix进行激活时解密;其他方式都会导致密钥在中全局可读。
/nix/store - 模块选项必须存在于用户的nixpkgs标签中:23.11/24.05/24.11/25.05/25.11版本间的选项漂移真实存在;推荐前需通过或选项搜索确认。
nix repl - 覆盖层应组合而非修改:使用范围。对于Flakes系统,不推荐全局配置文件级覆盖层。
final: prev: { ... } - 内核与initrd需一致:对于使用ZFS、NVIDIA或自定义模块的系统,更换时需有回退方案。
boot.kernelPackages - 切勿随意修改:它控制迁移语义,并非“版本升级”字段。
system.stateVersion - Disko和无状态模式是安装时决策:改造到现有系统是更复杂的话题。
- home-manager模式需保持一致:每台主机选择独立模式、NixOS模块或darwin模块并保持不变。
- Determinate和Lix在细节上存在差异:推荐守护进程或CLI标志前需明确分支。
- 优先考虑常见Nix故障模式而非特殊解释:Channels/Flakes混用、锁文件过时、覆盖层冲突、选项漂移、活跃开发环境被GC回收、非自由/不安全包开关未设置,这些解释了大部分问题。