Jump to content

創建 NixOS Live CD

From Official NixOS Wiki
Revision as of 19:31, 9 July 2026 by Covalode (talk | contribs) (Created page with "压缩使得构建过程变得缓慢。")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

起因

從已安裝的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%

如果你並不在意文件大小,可以在你的iso.nix中添加如下內容以使用更快的壓縮方式:

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

另見