Run systemd service in network namespace

I could prepend ip netns exec xx where applicable (e.g. serviceConfig.ExecStart). But ip netns requires root privileges. What can I do if serviceConfig.User isn’t "root"?

maybe using JoinNamespaceOf (see man systemd.unit) on another unit that is running as root ?

1 Like

@azazel75 thanks a lot! got it working:

{ config, pkgs, lib, ... }: {"netns@" = {
    description = "%I network namespace";
    before = [ "" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
      PrivateNetwork = true;
      ExecStart = (pkgs.writeScript "netns-up" ''
        #! ${pkgs.bash}/bin/bash
        ${pkgs.iproute}/bin/ip netns add $1
        ${pkgs.utillinux}/bin/umount /var/run/netns/$1
        ${pkgs.utillinux}/bin/mount --bind /proc/self/ns/net /var/run/netns/$1
      '') + " %I";
      ExecStop = "${pkgs.iproute}/bin/ip netns del %I";

Any<name> can join with:

bindsTo = [ "netns@wg.service" ];
after = [ "netns@wg.service" ];
unitConfig.JoinsNamespaceOf = "netns@wg.service";
serviceConfig.PrivateNetwork = true;

stolen from

1 Like

I might write a blog post soon about using this to sandbox transmission in a network namespace with wireguard, since I have a working setup. My Raspberry Pi is a NixOS seedbox, yay!

ok, here we go:

1 Like

For your interest, in NixOS 19.09 you’ll be able to directly specify the netns for a service to Join

So this could simplify your code a bit

# netns@.service
ExecStart=${pkgs.iproute}/bin/ip netns add %I
ExecStop=${pkgs.iproute}/bin/ip netns del %I

# myservice.service