創建 NixOS Live CD
Appearance
起因
從已安裝的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
The resulting image can be found in result:
$ ls result/iso/
nixos-24.05.20240721.63d37cc-x86_64-linux.iso
測試鏡像
To inspect the contents of the ISO image:
$ mkdir mnt
$ sudo mount -o loop result/iso/nixos-*.iso mnt
$ ls mnt
boot EFI isolinux nix-store.squashfs version.txt
$ umount mnt
To boot the ISO image in an emulator:
$ 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 地址
Static IP addresses can be set in the image itself. This can be useful for VPS installation.
{
...
networking = {
usePredictableInterfaceNames = false;
interfaces.eth0.ipv4.addresses = [{
address = "64.137.201.46";
prefixLength = 24;
}];
defaultGateway = "64.137.201.1";
nameservers = [ "8.8.8.8" ];
};
...
}
更快速的構建
The build process is slow because of compression.
Here are some timings for nix-build:
| squashfsCompression | Time | Size |
|---|---|---|
lz4 |
100s | 59% |
gzip -Xcompression-level 1 |
105s | 52% |
gzip |
210s | 49% |
xz -Xdict-size 100% (default) |
450s | 43% |
See also: mksquashfs benchmarks
If you don't care about file size, you can use a faster compression
by adding this to your iso.nix:
{
isoImage.squashfsCompression = "gzip -Xcompression-level 1";
}