r/NixOS • • 5d ago

True

Post image
1.3k Upvotes

49 comments sorted by

146

u/Psionikus 5d ago
  1. podman.enable
  2. pkgs.dockerTools.streamLayeredImage and other Nix container build tools

Nix is the best tool out there for building containers, and there are several tools out there likely better than the vanilla tools from nixpkgs.

6

u/Master-Chocolate1420 4d ago

Never tried the second one till-date, seems really handy.

162

u/Early-Independent-36 5d ago • Popcorn

Nix + containers is the goat

17

u/Mars_Bear2552 4d ago

containers for what exactly?

30

u/Early-Independent-36 4d ago

I use dev shells for my projects then use the same flake to create the docker image. Taking the "it works on my machine" to it works everywhere

29

u/riisen 4d ago

Everything.

8

u/gogliker 4d ago

There is a number of things that make containers easier to use for services. Scaling, management, gradually rolling out new versions with kubernetes or docker swarm, setting up isolated environments and networks, setting up volumes and storage, setting up CPU/GPU limits, building to and deploying from some kind of registry, e.t.c.

Everything is also possible to do on the server with Linux magic and box magic too. It's just container are literally build for the usecase, there are a lot of devs that are familiar with all the tools, e.t.c.

At work we mostly use nix for dev environments and stuff, but we use containers for deployment.

10

u/ggPeti 4d ago

independently deployed services

2

u/BananaTeleoperator 4d ago

I use a NixOs template on proxmox to create services under a network configuration . One of those services is a gitea runner that has docker on it to run git actions

3

u/mrdragon99 3d ago

Temple os with a wm with mint is better.

46

u/Ybenax 5d ago

I declare Quadlets as nix modules and let Podman do its magic.

7

u/-OutRage 4d ago

I wish we could easily manage them. There is a fork of komodo (docker) named Quomodo that uses podmam to see pod stats and so. Other alternative I found was cockpit for podman or grafana.

9

u/bew78 4d ago edited 4d ago

I've never heard of quadlets (looking into it now), do you have good resources about that and any Nix/NixOS integration?

And I'd be interested about why you prefer this option compared to using systemd services directly or nixos containers started by systemd-nspawn 🤔

7

u/Ybenax 4d ago edited 4d ago

I've been familiarizing myself with Quadlets for some years now, so I don't really have any specific resources to point you to, but I can leave you one of my service modules below as an example.

Regarding your question as to why Quadlets, I've been using them from before I switched over to Nix, and I like to be able to easily port my services in the case I ever want to leave the Nix ecosystem. Unlikely at this point, but I prefer to stay on the cautious side; I can always just install Podman to a Debian host and drop in those Quadlet files manually if I want to. As u/Humble-Persimmon2471 mentioned, Quadlets are just a convenient abstraction for what are ultimately systemd units, and use the same INI-style syntax systemd units do.

As per integrations, there's the quadlet-nix project. You can declare Quadlets directly using nix syntax. I've never tried it myself, though, so I can't really attest anything about it.

EDIT: there might be some crimes to English in my comments; English is a second language, so I apologize in advance for the eye-bleeding.

{ config, lib, pkgs, ... }:

let

  varServiceName = "jellyfin";
  varTsNode = "pod-${varServiceName}";
  varServePort = "8096";
  varUid = 1503;

  varServer = "${varDirectory}/${varServiceName}_server";
  varMedia = "${varServer}/media";
  varQuadlet = "containers/systemd/users/${toString varUid}";

  # Optional: see the extra setup for Tailscale and btrfs snapshots below.
  varDiskUUID = "/dev/disk/by-uuid/(UUID)";
  varDirectory = "/var/lib/${varServiceName}";
  varTailscale = "${varDirectory}/${varServiceName}_tailscale";
  varSnapshots = "${varDirectory}/.snapshots";

  # Optional: see btrfs subvolume mounts below.
  varMountOptions = [
    "defaults"
    "noatime"
    "compress=zstd:3"
    "discard=async"
  ];

in

{

  # Quadlets are included alongside Podman when enabled.
  virtualisation.podman.enable = true;
  
  environment.etc = {

    # This is '/etc/containers/systemd/users/(UID)/jellyfin_server.container'. Systemd
    # will automatically spawn a service unit running a rootless podman container.
    "${varQuadlet}/${varServiceName}_server.container".text = ''
      [Unit]
      Description=Jellyfin server container

      [Container]
      ContainerName=${varServiceName}_server
      Image=docker.io/jellyfin/jellyfin:latest
      AutoUpdate=registry
      Pod=${varServiceName}.pod
      Timezone=local

      User=1000
      Group=1000

      Volume=${varServer}/config:/config
      Volume=${varServer}/cache:/cache
      Volume=${varServer}/fonts:/usr/local/share/fonts/custom:ro
      Volume=${varMedia}/movies:/movies:ro
      Volume=${varMedia}/shows:/shows:ro
      Volume=${varMedia}/anime:/anime:ro
      Volume=${varMedia}/misc:/misc:ro

      [Service]
      Restart=always
      RestartSec=5

      [Install]
      WantedBy=default.target
    '';

  };

  # -- EVERYTHING BELOW IS OPTIONAL STUFF --

  # Some subvolume mounts to organize and snapshot the container files
  # (this assumes a btrfs host, of course).
  fileSystems = {

    "${varDirectory}" = {
      device = varDiskUUID;
      fsType = "btrfs";
      options = varMountOptions ++ [ "subvol=var_lib/@${varServiceName}" ];
    };

    "${varMedia}" = {
      device = varDiskUUID;
      fsType = "btrfs";
      options = varMountOptions ++ [ "subvol=var_lib/${varServiceName}/${varServiceName}_server/@media" ];
    };

    "${varSnapshots}" = {
      device = varDiskUUID;
      fsType = "btrfs";
      options = varMountOptions ++ [ "subvol=var_lib/${varServiceName}/@snapshots" ];
    };

    "${varTailscale}/state" = {
      device = varDiskUUID;
      fsType = "btrfs";
      options = varMountOptions ++ [ "subvol=var_lib/${varServiceName}/${varServiceName}_tailscale/@state" ];
    };

  };

  # Snapper service for automated btrfs snapshots.
  services.snapper.configs.${varServiceName} = {
    SUBVOLUME = varDirectory;
    TIMELINE_CREATE = true;
    TIMELINE_CLEANUP = true;
    TIMELINE_LIMIT_HOURLY = 6;
    TIMELINE_LIMIT_DAILY = 5;
    TIMELINE_LIMIT_WEEKLY = 3;
    TIMELINE_LIMIT_MONTHLY = 2;
    TIMELINE_LIMIT_YEARLY = 0;
  };

  # A dedicated system user for Jellyfin with its own dedicated namespace and UID.
  users = {
    groups.${varServiceName} = { };

    users.${varServiceName} = {
      isNormalUser = true;
      uid = varUid;
      group = varServiceName;
      home = varDirectory;
      createHome = true;
      linger = true;
    };
  };

  environment.etc = {

    # Pods make it easy to share networking namespaces between containers,
    # kind of like docker compose. It also spawns a "-pod.service" systemd unit
    # as a convenience to stop/start multiple containers at once. I set up the
    # Cloudflare DNS explicitely here to bypass some DNS routing I do on
    # Tailscale that is not relevant to this Jellyfin server in particular.
    "${varQuadlet}/${varServiceName}.pod".text = ''
      [Pod]
      PodName=${varServiceName}
      UserNS=keep-id:uid=1000,gid=1000
      DNS=1.1.1.1
      DNS=1.0.0.1
    '';

    # A Tailscale sidecard container that basically makes the Jellyfin server
    # into its own Tailscale node, so I don't have to open ports at all, since
    # all traffic in and out goes through my tailnet.
    "${varQuadlet}/${varServiceName}_tailscale.container".text = ''
      [Unit]
      Description=Tailscale container for the ${varServiceName} pod

      [Container]
      ContainerName=${varServiceName}_tailscale
      Image=docker.io/tailscale/tailscale:latest
      AutoUpdate=registry
      Pod=${varServiceName}.pod
      Timezone=local

      Environment=TS_HOSTNAME=${varTsNode}
      Environment=TS_STATE_DIR=/var/lib/tailscale
      Environment=TS_SERVE_CONFIG=/config/serve.json
      Environment=TS_USERSPACE=true
      Environment=TS_AUTHKEY=(secret)
      Environment=TS_AUTH_ONCE=true

      Volume=${varTailscale}/state:/var/lib/tailscale:U
      Volume=/etc/${varServiceName}/serve.json:/config/serve.json:ro

      [Service]
      Restart=always
      RestartSec=5

      [Install]
      WantedBy=default.target
    '';

    # A Tailscale config file to serve Jellyfin to my tailnet over HTTPS.
    "${varServiceName}/serve.json".text = ''
      {
        "TCP": { "443": { "HTTPS": true } },
        "Web": {
          "''${TS_CERT_DOMAIN}:443": {
            "Handlers": { "/": { "Proxy": "http://127.0.0.1:${varServePort}" } }
          }
        }
      }
    '';

  };

  # Auto-pulls the latest image for every container marked with `AutoUpdate=registry`
  # and automatically restarts said containers, on calendar.
  systemd.user.timers."podman-auto-update" = {
    wantedBy = [ "timers.target" ];
    timerConfig = {
    OnCalendar = [ "" "Tue,Thu,Sun 05:40:00" ];
      RandomizedDelaySec = "20m";
      Persistent = true;
    };
  };

}

5

u/schitcrafter 4d ago

Theres the quadlet-nix flake which provides lots of options. Also the main advantage above systemd services is versioning outside of nixpkgs and the docker tooling, as well as docker containers oftentimes being officialy supported by applications

5

u/Humble-Persimmon2471 4d ago

Quadlets is just an abstraction over systemd units. It gets converted to a systemd unit in the end.

2

u/jerrygreenest1 4d ago

Why not just make systemd units, especially since it’s so easy to do them in NixOS

Honestly I never wanted to do any systemd units on Linux before, other than on server. But once switched to NixOS, I now make em even on my desktop machine

3

u/Humble-Persimmon2471 4d ago

Because it's easier to read and write, I guess.

12

u/FloweyTheFlower420 4d ago

nspawn containers my beloved

10

u/Ok_Office_4873 4d ago

systemd units gang

7

u/AspectSpiritual9143 4d ago

container != docker

i use nixos-container frequently for networking purposes

11

u/AssistantIcy6117 4d ago

I still use docker on nixos

5

u/NotPatin 4d ago

me too, to run services and stuff

4

u/monr3d 4d ago

Nixos-container...

3

u/veltair-d 4d ago

Idk if there are some issues with docker, I tried using docker and had no issue with gpu passthrough (which is most of the complaints I see in some distros), so idk if there are issues elsewhere.

Where do the docker complains come from?

3

u/kwinz 4d ago edited 4d ago

I don't know exactly, I also use Docker on my NixOS host. Possible explanations:

Sometimes it seems more cumbersome than a sandboxed systemd service declared in nix for a similar effect.

NixOS also doesn't run well inside a docker container so most perfer LXC or systemd-nspawn over docker.

And building a container in a dockerfile seems antiquated compared to a nix flake. You can also vendor and package your software as a nix flake.

All in all it can be seen as an additional layer that you have to manage independently for very little gain because most of what docker does like reproducable deployments you can do better with other tools on nixos.

2

u/Hefty_Acanthaceae348 4d ago edited 4d ago

Imo it has design issues that come from it being (sort of) the first thing that did what it does. The central daemon and requiring root for example, and networks aren't solved in docker. Every time I had an issue with docker, it was related to networks.

1

u/Ursa_Solaris 4d ago

Where do the docker complains come from?

Honestly, most of it is performative. On any enthusiast forum, people will peacock by having the most niche and bespoke setups possible. I'm not saying there are no valid criticisms of Docker or the organization behind it, and that there are no benefits to using Podman or whatever else, but any assessment of this must include that much of it is just posturing for e-peen. Docker (Docker Engine specifically, Docker Desktop is a whole other matter) is largely fine if it accomplishes your goals. It's an open source, well-supported engine for container workloads without advanced requirements. There's a reason why the Docker image went on to become the basis of the OCI standard.

That said, a lot of the time people here will suggest just directly using NixOS packages instead of containers, and these people just don't understand the purpose of a container and can be safely ignored.

3

u/spaceduck107 4d ago

Podman+Quadlets>Docker.

2

u/arbv 4d ago

I also use LXC extensively as "lightweight VMs".

2

u/AnonymousRand 4d ago

if docker and nix had a baby i would be very happy

4

u/RabbitsAgenda 4d ago

pft no pride necessary, it's just better tech tho. Nerd pride is generally highly recommended anyway tho, it's just not a requirement when the tech is just that damn good.

3

u/juipeltje 4d ago

Yeah i really dislike containers for some reason, can't quite put my finger on the reason for it. I use Guix and they also have support for declaring containers, but for things that aren't packaged in Guix, like Jellyfin for example, i just have a separate user declared with it's own home manager configuration to install Jellyfin, and then have a service declared that runs Jellyfin as that user. I feel like in some ways just running a container would be more straightforward in this scenario, but at this point i'm more familiar with Nix than i am with containers.

1

u/NoRequirement5796 4d ago

finally I agree with something with nix

1

u/erubim 4d ago

With LLMs I get to just build it with a package/app derivation. If for containment, its either bwrap or VM. Some very complex docker compose "recipes" still make me have podman around tho.

1

u/TrainingTheory552 4d ago

what do you mean? nix is the best for containers.

1

u/Lou_Papas 4d ago

Tbf chroot is free

1

u/TDR-Java 4d ago

„We need full reproducibility and the only thing capable of that is a 5GB docker container”

1

u/german-gentil 20h ago

I developed a helper to declarative build and run container for nix: https://github.com/Dauliac/nix-oci

1

u/Illustrious-Gur8335 5d ago

while true; do echo true; done

1

u/I7sReact_Return 4d ago

Me using Gentoo without containers

Baremetal this shit, NOW!

1

u/Jayden_Ha 4d ago

I will never understand the hate of docker

0

u/KvasDimas 5d ago

True 

0

u/LeateWonceslace 4d ago

Nix users looking at docker containers:
"Pathetic."

-4

u/seven-circles 4d ago

Containers are a solution looking for a problem.

1

u/necrophcodr 4d ago

Containers don't exist, only processes.

0

u/NickPetertails 4d ago

I think NixOS is to Docker as Docker is to Kubernetes (forgive the ignorant comparison). They're different tools at different levels with different scopes, but overlapping in use cases. Personally I use Podman over NixOS and I deem dockerTools to be a terrific tool for building containers (streamlined syntax with minimal waste of space). I even converted my CI-served (GitLab) Docker images to nix and I'm satisfied with that.