"Make your configuration ‘modern and portable’." This guide walks you through migrating from a traditional
/etc/nixos/configuration.nixto Flakes.
Step 1: Create a project directory#
Create a dedicated configuration directory (such as ~/nixos-config). Do not make ad hoc changes directly inside /etc/nixos.
mkdir ~/nixos-config
cd ~/nixos-config
# 复制原有的硬件配置
cp /etc/nixos/hardware-configuration.nix .
# 复制原有的系统配置
cp /etc/nixos/configuration.nix .Step 2: Write flake.nix#
Create flake.nix in the project root.
{
description = "我的 2026 版 NixOS 配置";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs, ... }@inputs: {
nixosConfigurations.my-host = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
# 传递参数给子模块
specialArgs = { inherit inputs; };
modules = [
./configuration.nix
];
};
};
}Step 3: Adjust configuration.nix#
Because the Flake uses nixpkgs.lib.nixosSystem, you may need to adjust the top-level arguments in your existing configuration.nix:
# 修改前:
# { config, pkgs, ... }:
# 修改后:
{ config, pkgs, inputs, ... }: {
imports = [
./hardware-configuration.nix
];
# 启用 Flakes 和新的 Nix CLI
nix.settings.experimental-features = [ "nix-command" "flakes" ];
# 其他配置项...
system.stateVersion = "24.11"; # 示例初装版本;迁移时保留原值
}Step 4: Build and apply#
Note: In Flake mode, when a Flake is read from a local Git working tree, the files it references must be tracked by Git (you can git add new files first). Explicit path: sources behave differently. Inspect the staged contents first to avoid including private keys or unrelated files.
git init
git add flake.nix configuration.nix hardware-configuration.nix
nix flake check --no-build
nixos-rebuild dry-build --flake .#my-host
nixos-rebuild build --flake .#my-host
# 检查构建结果、恢复路径与变更后,手动激活:
sudo nixos-rebuild switch --flake .#my-host.: Refers to the current directory.#my-host: Matches the name defined inoutputs.nixosConfigurations.
Benefits of migrating#
- No dependence on a global Channel: The system version is determined entirely by
flake.lock. - Easy to back up: Simply push this directory to GitHub.
- Modular configuration: You can easily split the configuration into files such as
desktop.nixanduser.nix, then reference them inconfiguration.nixunderimports.
Checks after activation#
A successful build proves only that the build stage works. After activation, check the current system generation, service status, and desktop behavior before proceeding with Home Manager integration.
References & further reading
Adapted from technical notes. Examples use generic names.
Continue along a reading path
Flakes: project and dependency management
- 01Flake structure: inputs and outputs
- 02flake.lock and reproducibility
- 03Flake Utils and project templates
- 04External Flake references and collaboration
- 05Migrating NixOS configuration to Flakes
- 06A tutorial on Flake projects and dependency management
- 07How Flake updates work
- 08Rolling back and manually editing flake.lock