Jump to content

创建 NixOS Live CD

From Official NixOS Wiki
Revision as of 18:52, 9 July 2026 by Covalode (talk | contribs)

起因

从已安装的NixOS系统中创建一个自定义的 NixOS Live CD 有许多优势:

  • 确保可信度
  • 无需访问互联网
  • 很容易向镜像中添加自己的包和配置

构建

创建iso.nix文件,并使用nix-build命令来构建最小化的NixOS安装镜像。如下示例中预装了Neovim

{ config, pkgs, ... }:
{
  imports = [
    <nixpkgs/nixos/modules/installer/cd-dvd/installation-cd-minimal.nix>

    # Provide an initial copy of the NixOS channel so that the user
    # doesn't need to run "nix-channel --update" first.
    <nixpkgs/nixos/modules/installer/cd-dvd/channel.nix>
  ];
  environment.systemPackages = [ pkgs.neovim ];
}

通过以下命令构建镜像:

nix-build '<nixpkgs/nixos>' -A config.system.build.isoImage -I nixos-config=iso.nix

另外,也可以使用Flakes来生成ISO安装镜像。示例中使用nixos-24.05作为nixpkgs源。

❄︎ flake.nix
{
  description = "Minimal NixOS installation media";
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
  outputs = { self, nixpkgs }: {
    packages.x86_64-linux.default = self.nixosConfigurations.exampleIso.config.system.build.isoImage;
    nixosConfigurations = {
      exampleIso = nixpkgs.lib.nixosSystem {
        system = "x86_64-linux";
        modules = [
          ({ pkgs, modulesPath, ... }: {
            imports = [ (modulesPath + "/installer/cd-dvd/installation-cd-minimal.nix") ];
            environment.systemPackages = [ pkgs.neovim ];
          })
        ];
      };
    };
  };
}

用以下命令生成iso镜像:

# nix build path:$PWD

生成的镜像文件可以在result中找到

$ ls result/iso/
nixos-24.05.20240721.63d37cc-x86_64-linux.iso

测试镜像

查看ISO镜像中的内容:

$ mkdir mnt
$ sudo mount -o loop result/iso/nixos-*.iso mnt
$ ls mnt
boot  EFI  isolinux  nix-store.squashfs  version.txt
$ umount mnt

在模拟器中启动镜像:

$ nix-shell -p qemu
$ qemu-system-x86_64 -enable-kvm -m 256 -cdrom result/iso/nixos-*.iso

SSH

在你的 iso.nix 中添加:

{
  ...
  # Enable SSH in the boot process.
  systemd.services.sshd.wantedBy = pkgs.lib.mkForce [ "multi-user.target" ];
  users.users.root.openssh.authorizedKeys.keys = [
    "ssh-ed25519 AaAeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee username@host"
  ];
  ...
}

静态 IP 地址

你可以直接在镜像中设置好静态IP地址。这对于在VPS上进行安装可能会很有帮助。

{
  ...
  networking = {
    usePredictableInterfaceNames = false;
    interfaces.eth0.ipv4.addresses = [{
      address = "64.137.201.46";
      prefixLength = 24;
    }];
    defaultGateway = "64.137.201.1";
    nameservers = [ "8.8.8.8" ];
  };
  ...
}

更快速的构建

构建过程缓慢的原因是压缩。

以下是nix-build使用的一些压缩方式的用时测试结果:

压缩测试结果
squashfsCompression 用时 大小
lz4 100s 59%
gzip -Xcompression-level 1 105s 52%
gzip 210s 49%
xz -Xdict-size 100% (default) 450s 43%

如果你并不在意文件大小,可以在你的ios.nix中添加如下内容以使用更快的压缩方式:

{
  isoImage.squashfsCompression = "gzip -Xcompression-level 1";
}

另见