Skip to content

Instantly share code, notes, and snippets.

@derekmahar
Last active August 6, 2024 04:43
Show Gist options
  • Save derekmahar/e1654fc78c1047aa1feb938c9df3af19 to your computer and use it in GitHub Desktop.
Save derekmahar/e1654fc78c1047aa1feb938c9df3af19 to your computer and use it in GitHub Desktop.
How to Install Nix in an LXD Container

How to Install Nix in an LXD Container

Steps to install the Nix package manager inside an Ubuntu 20.04 LXD container using the images:ubuntu/focal image:

  1. On the LXD host, create an Ubuntu 20.04 container:
    lxc init images:ubuntu/focal container1
    
  2. On the LXD host, enable nested security on the container:
    lxc config set container1 security.nesting true
    
  3. Start the container:
    lxc start container1
    
  4. Inside the container, install packages curl, gnupg2, man, rsync, and xz-utils:
    lxc exec container1 -- apt install --yes curl gnupg2 man-db rsync xz-utils
    
  5. Inside the container, install Nix as user ubuntu because root may not perform a single-user Nix installation:
    lxc exec $container -- sudo --user ubuntu --login sh -c "curl --location --silent https://nixos.org/nix/install | sh"
    
#!/bin/sh
# Installs the Nix package manager (https://nixos.org/nix/) inside an LXD
# container.
#set -o xtrace
image=images:ubuntu/focal
if [ "$#" -eq 1 ]
then
container=$1
# Create a container from the given image and assign it the name from the
# script argument.
lxc init $image $container > /dev/null
else
# Create a container from the given image and extract the random container
# name that LXD assigns.
container=`lxc init $image | grep "Instance name" | sed 's/^.* \(.*\)$/\1/'`
fi
echo "Created container $container."
# Enable nested security on the container.
# See https://github.com/NixOS/nix/issues/2649#issuecomment-518045796.
lxc config set $container security.nesting true
# Start the container.
lxc start $container
# Inside the container, install packages curl, gnupg2, man, rsync, and xz-utils.
lxc exec $container -- apt install --yes curl gnupg2 man-db rsync xz-utils
# Inside the container, install the Nix package manager as user "ubuntu".
# (see https://discuss.linuxcontainers.org/t/useful-lxc-command-aliases/2547/4)
# because root may not perform a single-user Nix installation
# (see https://github.com/NixOS/nix/issues/1559).
lxc exec $container -- sudo --user ubuntu --login sh -c "curl --location --silent https://nixos.org/nix/install | sh"
# Stop the container.
lxc stop $container
@derekmahar
Copy link
Author

I added package xz-utils to the list of packages that the installation script installs inside the container.

@almereyda
Copy link

Very well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment