Skip to content

Instantly share code, notes, and snippets.

@ForumPlayer
Forked from gdamjan/README.md
Created July 14, 2022 18:14
Show Gist options
  • Save ForumPlayer/6f15b7644f8bddfca304f46c7c30a7a1 to your computer and use it in GitHub Desktop.
Save ForumPlayer/6f15b7644f8bddfca304f46c7c30a7a1 to your computer and use it in GitHub Desktop.
Install a NixOS for a systemd-nspawn container … from podman

Install

Run a nix container with podman, with the container destination mounted as /mnt:

DEST=~/containers/nixos
mkdir -p $DEST/{dev,proc,etc/nixos}

podman run -v $DEST:/mnt -it --rm --cap-add SYS_ADMIN docker.io/nixos/nix:latest

Note: you can use docker run --privileged … instead of podman run …)

Setup the channel for nixos-22.05

nix-channel --add https://nixos.org/channels/nixos-22.05 nixpkgs
nix-channel --update
nix-channel --list

Install the nixos install tools:

nix-env -f '<nixpkgs>' -iA nixos-install-tools util-linux

Copy the configuration.nix file and run the installation:

cat > /mnt/etc/nixos/configuration.nix
…see below…
<Ctrl-D>

# workaround for error: while setting up the build environment: mounting /proc: Operation not permitted «
mount --bind /proc/ /mnt/proc
mount --bind /dev/ /mnt/dev

nixos-install --root /mnt

Boot

Let's "boot" the container:

sudo systemd-nspawn --boot --network-veth --directory $DEST
…

# poweroff

System updates:

nixos-rebuild boot --upgrade

Release upgrade:

nix-channel --add https://nixos.org/channels/nixos-22.05 nixos
nix-channel --update
nixos-rebuild boot --upgrade

machinectl

Move the container directory to /var/lib/machines/nixos. Make the following file:

# /etc/systemd/nspawn/nixos.nspawn
[Exec]
Boot=yes
ResolvConf=off
# LinkJournal=try-guest

[Network]
Bridge=bridge0

Then run machinectl start nixos to run it, or machinectl enable nixos to make it run on boot. Use machinectl shell nixos to enter the container. I my use-case I bridge the container with my LAN so it's ssh accessible from any local computer.

# /etc/nixos/configuration.nix
#
# Edit this configuration file to define what should be installed on
# your system. Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running ‘nixos-help’).
{ config, pkgs, ... }:
{
imports = [];
boot.isContainer = true;
boot.loader.initScript.enable = true;
time.timeZone = "Europe/Skopje";
networking.hostName = ""; # empty
networking.useDHCP = false;
networking.useNetworkd = true;
networking.useHostResolvConf = false;
networking.firewall.enable = false;
# default password is "root", create with `openssl passwd -6 root`
security.initialRootPassword = "$6$V1JB3DXzfkBBjaxL$V4ymu8BxUdDKwDqRMsy4bu4tyocBglz6qtuyonMbi.HweoKbcgLr.W57A62SPqi6CzEGWtER9vskXHAqoHpr4/";
environment.systemPackages = with pkgs; [
vim
wget
];
# services.sshd.enable = true;
system.stateVersion = "22.05";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment