JustToThePoint English Website Version
JustToThePoint en español
Colaborate with us

NixOS VI. Distrobox, Docker, GPG, Synching

It ain’t about how hard you can hit. Its about how hard you can get hit, and how much you can take, and keep moving forward, Rocky Balboa

Introduction to NixOS

NixOS is a unique, innovative, and powerful Linux distribution that leverages the Nix package manager. Unlike traditional Linux distributions that update packages and system configurations in-place, NixOS uses a purely functional and declarative approach to define the system state, reducing the risk of system breakage.

NixOS is a Linux distribution that uses the Nix package manager to handle packages and system configuration in a purely functional manner. This approach ensures that builds are reproducible and that the system state can be reliably replicated or rolled back.

  1. Immutable Design: It uses a configuration file (usually /etc/nixos/configuration.nix) to define the entire system state, including installed packages, services, and system settings. This makes the system “immutable” in the sense that you don’t manually modify system files. Instead, you declare what you want, and NixOS builds the system from that declaration.
  2. Atomic Updates: When you run nixos-rebuild switch, the system builds a new generation of the environment. If the build is successful, you can switch to this new environment atomically. This means that either the entire update is applied, or nothing changes at all, preventing partial updates that could leave the system in an inconsistent state: sudo nixos-rebuild switch, build and switch to the new generation. If anything goes wrong, you can easily roll back to a previous generation: sudo nix-env ‐‐rollback This rollback is seamless because each generation is stored separately.

    sudo nix-env ‐‐rollback is a command used to revert your system to the previous configuration. It’s a powerful tool for undoing unintended changes or recovering from failed package installations. Before rolling back, consider if there’s a more targeted solution, like uninstalling specific packages or reverting configuration files.

  3. Purely Functional System Configuration: NixOS uses a functional paradigm for configuration. This means that changes are expressed as pure functions from a configuration to a system state, ensuring reproducible builds and easy rollback.

NixOS

Distrobox

Distrobox is a tool that allows you to seamlessly run containers on your host system, either using Docker or Podman. It integrates tightly applications from inside the container so that they appear as if they are natively installed on your host. This is particularly helpful if you want to leverage software from different distributions (Arch, Ubuntu, Mint, etc.) without altering and contaminating your primary NixOS environment.

Step 1. Installing Docker. Distrobox relies on either Docker or Podman as the backend to manage containers, hence we are going to enable Docker, sudo vim /etc/nixos/configuration.nix:

  virtualisation = {
  	docker = {
    		enable = true; # Enable the Docker daemon on NixOS ...
        # so you can pull images, run containers, and manage Docker from your NixOS system.
  	};
  	oci-containers.backend = "docker"; # Set Docker as the default container backend
  };

Step 2. Add Your User to the Docker Group:

By default, Docker requires root privileges. Adding your user to the docker group allows you to run Docker commands without sudo.

  users.users.nmaximo7 = {
    isNormalUser = true;
    description = "nmaximo7";
    extraGroups = [ "networkmanager" "wheel" "docker"];
	···
  };

extraGroups = [ “docker” ] makes nmaximo7 a member of the docker group. After rebuilding and logging out/in, nmaximo7 can run docker commands without needing root permissions.

Step 3. Installing Distrobox

environment.systemPackages = with pkgs; [
    docker
    mesa # When running graphical apps in Distrobox, you should first install mesa, an open source 3D graphis library.
    distrobox # Add Distrobox to Your Configuration
];

Step 4. Rebuild Your System: sudo nixos-rebuild switch

Troubleshooting: groups $USER checks your user’s groups to ensure you are in the docker group; users and groups are used for access control (your user should be in the “docker” group); restart the service (sudo systemctl restart docker); adjust the Docker socket permissions (sudo chmod 666 /var/run/docker.socks).

Step 5. Creating and using a container with distrobox.

distrobox-create --name archlinux --image archlinux:latest
# Create an Arch Linux Container via Distrobox
# --name archlinux: assigns a name to the container for easy reference and management.
# --image archlinux:latest: it pulls the latest Arch Linux image from Docker Hub.

distrobox-enter archlinux # After creation, enter the container.
# You can now run Arch Linux commands and applications as if you are on an Arch system.
sudo pacman -Syu # Inside the container, update the package database.
sudo pacman -S --needed base-devel git # Let's make sure we have the base development packages and Git installed.
pacman -Sy archlinux-keyring --noconfirm # Ensure that the system's keyring is up-to-date, which helps in verifying the authenticity of packages during installation or upgrade.
git clone https://aur.archlinux.org/google-chrome.git # Clone the Google Chrome repository.
cd google-chrome
makepkg -si # Install the Package
distrobox-export --app google-chrome-stable # It takes care of exporting an app, a binary, or a service from the container to the host.

This command integrates Google Chrome from the container into your host’s application menu, allowing you to launch it as if it were installed on your NixOS system.

Step 6. Useful comands.

distrobox-assemble

distrobox-assemble allows you to create or destroy containers in batches based on a configuration file (manifest). This manifest file is named by default as ~/distrobox.ini. This is basically a Distrobox configuration file for assembling a container environment.

This file allows you to create a Distrobox using the specified settings. If distrobox.ini is in your current directory, you can run: distrobox assemble create (no further arguments are needed) and it will create as many container as specified in distrobox.ini.

You can also specify a custom manifest file: distrobox assemble create ‐‐replace ‐‐file ~/distrobox.ini, e.g., distrobox assemble create ‐‐replace ‐‐file ~/dotfiles/distrobox.ini.

The ‐‐replace option recreates the containers if they already exist.

Finally, you may want to remove containers: distrobox assemble rm.

Setting up a Custom Docker

cd dotfiles
mkdir distrobox
distrobox rm ‐‐all -f # Delete all previous distroboxes
sudo mkdir -p /home/arch-distro # Create a home directory for your container with the right permissions and ownership.
sudo chown nmaximo7:users /home/arch-distro
#      _            _
#     | |          | |
#   __| | ___   ___| | _____ _ __
#  / _` |/ _ \ / __| |/ / _ \ '__|
# | (_| | (_) | (__|   <  __/ |
#  \__,_|\___/ \___|_|\_\___|_|

# Change directory to where the Dockerfile is located
# cd dotfiles/distrobox

# Build the Docker image with the tag 'custom-arch'
# Using the latest Arch Linux image as a base ensures you start with the most recent packages and security updates.
# docker build -t custom-arch .

# Remove any existing Distrobox container named 'arch'
# distrobox rm arch -f

# Create a new Distrobox container named 'arch' using the custom image
# --home sets the home directory for the container
# --volume mounts a directory from the host into the container
# --verbose enables detailed output
# distrobox create --image custom-arch --name arch --home /home/arch-distro --volume /etc/static/profiles/per-user:/etc/profiles/per-user:ro --verbose

# Enter the created Distrobox container
# distrobox enter arch

# Use the official Arch Linux image as the base image
FROM archlinux:latest

# Initialize the pacman keyring and update the package repository
RUN pacman-key --init && \
    pacman-key --populate archlinux && \
    pacman -Syu --noconfirm

# Force a full refresh of all package databases:
RUN pacman -Syy

RUN pacman -S --noconfirm reflector # Install Reflector

# Update the mirror list using reflector:
RUN reflector --country Spain,France,Germany \
             --latest 20 \
             --protocol http,https \
             --save "/etc/pacman.d/mirrorlist" \
             --sort rate

# Install base development packages and essential tools
RUN pacman -Syu --noconfirm base-devel git

# Install additional tools for productivity
# eza (enhanced ls replacement), bc and qalc (calculators)
# bat (cat with syntax highlighting), ripgrep (a very popular alternative to grep)
RUN pacman -S --noconfirm eza zoxide fd bat ripgrep bc qalc

# Install system utilities and help (tldr), fuzzy finder (fzf)
RUN pacman -S --noconfirm fzf wl-clipboard lazygit jq rsync man-db tldr unzip plocate glibc sudo wget curl

# Install system utilities for various tasks
# bpytop (Linux resource monitor), figlet (convert text into ASCII art), cmatrix (an animated matrix in your terminal)
RUN pacman -S --noconfirm fastfetch vim bpytop cmatrix starship figlet fortune-mod

# Install glibc and glibc-locales to support locale generation
RUN pacman -S --noconfirm glibc glibc-locales

# Set up the locale, i.e., the language, numbering, date, and currency formats for your system.
RUN sed --in-place=.bak 's/^#en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
RUN locale-gen

# The /etc/locale.conf file defines system-wide locale settings.
RUN echo "LANG=en_US.UTF-8" >> /etc/locale.conf

# Set up the keyboard layout: loadkeys es. A Spanish keyboard layout is configured by:
RUN echo "KEYMAP=es" >> /etc/vconsole.conf

# Create a non-root user named 'nmaximo7' and allow passwordless sudo, ...
# making package building and maintenance safer than using root.
RUN useradd -m -G wheel nmaximo7 && \
    echo "nmaximo7 ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

# Install additional libraries for GUI applications
RUN pacman -S --noconfirm alsa-lib gtk3 libcups libxss libxtst nss ttf-liberation xdg-utils geany

# Switch to the 'nmaximo7' non-root user
USER nmaximo7
WORKDIR /home/nmaximo7

# Clone and install the AUR helper 'yay'
RUN git clone https://aur.archlinux.org/yay-git.git && \
    cd yay-git && \
    makepkg -si --noconfirm

# Install Google Chrome and Ferdium using yay
RUN yay -S google-chrome --noconfirm
RUN yay -S ferdium-bin --noconfirm

# Switch back to the root user
USER root

# Set Environment Variables for language support and locale settings
ENV LANG=es_ES.UTF-8
ENV LANGUAGE=es_ES:es
ENV LC_ALL=es_ES.UTF-8
distrobox create --image custom-arch --name arch --home /home/arch-distro --volume /etc/static/profiles/per-user:/etc/profiles/per-user:ro --verbose
# --home /home/arch-distro: select a custom HOME directory for the container
# --volume: mounts a host from the host into the container

Import/Export GPG Private/Public Keys

GPG is a widely-used tool used for encrypting data, creating digital signatures, and managing cryptographic keys. It allows you to generate and manage public-private key pairs and use these keys to securely communicate or verify the authenticity of messages, files, and software.

Steps to Export and Import GPG Keys

Step 1. Install the gnupg and pinentry packages and rebuild your system: sudo nixos-rebuild switch

  environment.systemPackages = with pkgs; [
  ···
  gnupg # The main GPG package for encryption and key management
  pinentry # A set of programs that handle passphrase input securely
];

After editing your configuration, apply the changes by rebuilding your system: sudo nixos-rebuild switch

Step 2. Export your public and private keys.

Before moving GPG keys to another system, you need to export them from the source system.

gpg --list-keys # List your GPG keys.
# You will see an output listing your keys, something like:
pub   ed25519 2024-04-09 [SC]
      YOUR-GPG-KEY
uid           [ultimate] Your Name 
sub   cv25519 2024-04-09 [E]
gpg --export YOUR-GPG-KEY > public-key.asc #  Export your GPG Public Key into a file name public-key.asc.
gpg --export-secret-key -a nmaximo7 > prv.key # Export your GPG Private key into a file name prv.key
# Enter the GPG passphrase if prompted, the password that you set when creating the key.

Step 3. Transfer Your Exported Keys to Your New System. Now that you have exported your keys, you need to copy the public-key.asc (public key) and prv.key (private key) files to your new system.

Ensure the private key file prv.key is never exposed to untrusted environments.

Step 4. Import Your Public and Private Keys on the New System

On the new system, ensure GPG and pinentry are installed.

gpg --pinentry-mode loopback --import prv.key # Import your GPG private key.
# The --pinentry-mode loopback option allows you to enter the passphrase directly on the terminal.
gpg --import public-key.asc # Import your GPG public key.

gpg --list-keys # After importing, verify your GPG public keys have been succesfully imported.

Encrypting files and signing documents

gpg --import someone_else_public.key
# Imports a public key from someone you wish to communicate with securely into your GPG keyring.

gpg --encrypt --recipient someone_else@email.com file.txt
# This command results in an encrypted file (e.g., file.txt.gpg).
# It is encrypted using the recipient's public key and can only be decrypted by the recipient who possesses the corresponding private key.
# This ensures that only the intended recipient can read its contents.

gpg --decrypt file.txt.gpg
# It decrypts an encrypted file.
# GPG will prompt for the passphrase associated with your private key if necessary.

gpg --sign document.txt
# It creates a digital signature for a file (typically in a .gpg or .sig file) ...
# that can be used to verify the authenticity and integrity of the document.
# Anyone with your public key can verify that the document has not been tampered with and that it was indeed signed by you.

Synching

Syncthing is a decentralized file synchronization service. It allows you to safely and privately synchronize files and directories between multiple machines without relying on a central server. It is a really good free alternative to Dropbox and Google Drive.

Each device connected via Syncthing can share directories (folders) with other devices on the local network or over the internet.

Step 1. Enable Synching declaratively by editing your configuration.nix.

services = {
  [...]
  syncthing = {
    enable = true; # Enable the Syncthing service
    openDefaultPorts = true; # Automatically open Syncthing's default ports in the firewall
    user = "YOUR NAME"; # Run Syncthing under user 'YOUR NAME'
    group = "users"; # Specify the group that the user belongs to
    # Directory for Synching's database and sync-related data
    dataDir = "~/.config/syncthing";
    # Define the directory where Syncthing will search for its configuration files
    configDir = "~/.config/syncthing";
    overrideDevices = true; # Allow overriding device settings (if needed), useful for custom device configurations
    overrideFolders = true; # Allow overriding folder settings (if needed), useful for custom folder configurations
    settings = {
        gui = {
            user = "nmaximo7"; # Specify the user for accessing the Syncthing web GUI
        };
    };
  };
};
# Ensure the firewall allows Syncthing traffic (21027/UDP, 22000/TCP), and the web GUI (8384/TCP)
networking.firewall = {
  allowedTCPPorts = [ 17500 22 22000 8384 ];
  allowedUDPPorts = [ 17500 22000 21027 ];
};

Step 2. Rebuild your system. After editing the configuration.nix file, you will need to rebuild your NixOS system to apply the changes: sudo nixos-rebuild switch

Step 3. You can confirm that Syncthing is running by accessing the Synching web GUI in your web browser: http://127.0.0.1:8384/. Then, you can manage your synchronization settings, add devices by exchanging device IDs (Syncthing automatically discovers other devices running Syncthing if they share the same local network),add new folders to sync, configure encryption and compression settings, and monitor synchronized status and activity logs. You may want to visit out webpage How to backup your data: Synching, rsync & backup hardware

Bitcoin donation

JustToThePoint Copyright © 2011 - 2025 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.