OFFSET偏移
← All articlesOFFSET / FIELD NOTESNO. 087

NixOS configuration organization, maintenance, and troubleshooting

Retain a complete working checklist for version control, module organization, update backups, secure development, and failure recovery.

English translation · Code and commands follow the Chinese original.

IN THESE READING PATHSNix commands and long-term maintenance ↗
About 4 min readStart reading

1. Version management#

Version scope: the original notes use examples centered on NixOS 24.05, Python 3.11, Node 20, and similar versions. Historical pins are retained below for context; 24.05 should not be treated as a currently security-supported branch. When migrating, choose inputs that are still supported and assess changes to the pinned source and options.

Pinning the Nixpkgs version

Avoid configuration drift and ensure reproducibility:

# 使用 flake.nix(推荐)
{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
  };
  # ...
}

# 固定 commit 可在 flake input 中指定具体修订,并提交 flake.lock。
# autoUpgrade 是自动应用更新的独立选择,不是固定版本的方法。
{
  system.autoUpgrade = {
    enable = true;
    flake = "/etc/nixos";
    flags = [ "--update-input" "nixpkgs" ]; # 兼容旧 CLI;核对本机版本
    allowReboot = false;
  };
}

Enabling Flakes

{ pkgs, ... }: {
# 在 configuration.nix 中添加
nix = {
  package = pkgs.nixVersions.stable;
  extraOptions = ''
    experimental-features = nix-command flakes
  '';
};
}

2. Configuration organization#

Recommended directory structure

~/.config/nixos/
├── flake.nix              # Flake 入口
├── flake.lock             # 锁定文件
├── hosts/
│   ├── desktop/           # 桌面主机
│   │   └── default.nix
│   └── server/            # 服务器主机
│       └── default.nix
├── modules/
│   ├── common/            # 通用模块
│   ├── desktop/           # 桌面环境
│   ├── development/       # 开发环境
│   └── services/          # 服务配置
└── pkgs/                  # 自定义包

A modular configuration example

# modules/desktop/gnome.nix
{ config, lib, pkgs, ... }:

{
  options.my.desktop.gnome.enable = lib.mkEnableOption "GNOME desktop";
  
  config = lib.mkIf config.my.desktop.gnome.enable {
    services.xserver.enable = true;
    services.displayManager.gdm.enable = true;
    services.desktopManager.gnome.enable = true;
    
    environment.systemPackages = with pkgs; [
      gnome-tweaks
      gnomeExtensions.dash-to-dock
    ];
  };
}

3. Routine maintenance#

System updates

# 更新 Flake 锁定
nix flake update

# 先做求值与构建检查
nix flake check --no-build
nixos-rebuild build --flake .#workstation
# 确認目标并准备好回滚后,再实际激活
sudo nixos-rebuild switch --flake .#workstation

# 或者直接更新 channel
sudo nix-channel --update
sudo nixos-rebuild switch --upgrade

Disk cleanup

# 先检查历史;-d 删除找到的所有旧世代,不会保留最近三代
nix-env --profile /nix/var/nix/profiles/system --list-generations
# 如确认只保留各 profile 当前世代,才考虑:
# sudo nix-collect-garbage -d

# 删除特定版本之前的所有版本
sudo nix-collect-garbage --delete-older-than 30d

# 优化存储(去重)
nix store optimise

Backup strategy

{ pkgs, ... }: {
# 在 configuration.nix 中启用自动备份
services.borgbackup.jobs.homeBackup = {
  paths = [ "/home" ];
  exclude = [ "*/Downloads" "*/.cache" ];
  repo = "/backup/borg";
  compression = "auto,zstd";
  startAt = "daily";
};
}

4. Security recommendations#

{
  # 启用防火墙
  networking.firewall.enable = true;
  
  # SSH 安全
  services.openssh = {
    enable = true;
    settings = {
      PermitRootLogin = "no";
      PasswordAuthentication = false;
      KbdInteractiveAuthentication = false;
    };
  };
  
  # 自动安全更新
  system.autoUpgrade = {
    enable = true;
    allowReboot = false;
  };
  
  # Fail2ban
  services.fail2ban = {
    enable = true;
    maxretry = 3;
  };
}

5. Development environments#

Using direnv

{ pkgs, ... }: {
# 启用 direnv
programs.direnv = {
  enable = true;
  enableZshIntegration = true;
  nix-direnv.enable = true;
};
}

Project-specific development environments

# shell.nix
{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
  packages = with pkgs; [
    nodejs_20
    yarn
    git
  ];
  
  shellHook = ''
    echo "Node.js development environment loaded!"
    node --version
  '';
}

6. Performance optimization#

{
  # 只启用 Btrfs 支持;压缩还需在目标 fileSystems 挂载选项设置 compress=zstd
  boot.supportedFilesystems = [ "btrfs" ];
  
  # 垃圾回收设置
  nix.gc = {
    automatic = true;
    dates = "weekly";
    options = "--delete-older-than 30d";
  };
  
  # 自动优化
  nix.settings.auto-optimise-store = true;
  
  # 使用缓存
  nix.settings.substituters = [
    "https://cache.nixos.org"
    "https://nix-community.cachix.org"
  ];
  # 从缓存服务的官方页面核验对应签名公钥,再写入 trusted-public-keys。
  # 不复制未经核验或已过期的示例密钥。
}

7. Troubleshooting#

Unable to boot because of a configuration error

# 进入前一个版本
在启动菜单中选择之前的版本

# 或者从 Live USB 修复
# 先用 lsblk / blkid 核对实际根分区与文件系统
# /dev/disk/by-label/ROOT 是占位,按实际布局选择并挂载引导等其他分区
sudo mount /dev/disk/by-label/ROOT /mnt
sudo nixos-enter
# 修复配置
sudo nixos-rebuild switch

Clearing swap

Disable swap only after confirming that free memory can accommodate the swapped-out pages and that no critical workloads are running. Otherwise, you may run out of memory. This is not a general-purpose performance fix.

sudo swapoff -a
sudo swapon -a

Viewing system logs

# 查看启动日志
journalctl -b

# 查看特定服务日志
journalctl -u sshd

# 实时日志
journalctl -f

8. Recommended tools#

{ pkgs, ... }: {
environment.systemPackages = with pkgs; [
  # 系统管理
  fastfetch     # 系统信息;原笔记 neofetch 已停止维护
  htop          # 进程管理
  btop          # 系统监控
  iotop         # IO 监控
  
  # 网络工具
  nmap          # 端口扫描
  nettools      # netstat 等
  iperf3        # 网络测速
  
  # 文件管理
  fd            # 快速文件查找
  ripgrep       # 快速文本搜索
  fzf           # 模糊查找
  bat           # 增强版 cat
  eza           # 增强版 ls;原 exa 示例的延续项目
  
  # 开发工具
  git
  vim
  wget
  curl
  jq            # JSON 处理
];
}

9. Learning resources#

The limits of reproducibility, updates, and backups

flake.lock pins inputs; automatic updates deliberately change the inputs and system state. allowReboot = false only restricts automatic reboots, not the application of service changes. A Borg configuration also requires checking repository initialization, permissions, encryption, and recovery drills. System rollback is not a substitute for backing up /home data.

References & further reading

  1. NixOS manual ↗
  2. Nix GC options ↗
  3. Nixpkgs ↗

Adapted from technical notes. Examples use generic names.

Continue along a reading path

Nix commands and long-term maintenance

  1. 01A NixOS learning roadmap: foundations, Flakes, user configuration, and beyond
  2. 02Nix commands explained: builds, environments, profiles, and systems
  3. 03nh: a unified workflow for Nix systems, users, and cleanup
  4. 04Garbage collection, store optimization, and rollback generations
  5. 05NixOS configuration organization, maintenance, and troubleshooting
CONTINUE READING / NEXT ARTICLENix development environments: languages, databases, and full-stack examples

Retain complete configurations for Python, Node, Rust, Go, Java, C/C++, Haskell, databases, and Justfile.