Run systemd service in network namespace

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
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=${pkgs.iproute}/bin/ip netns add %I
ExecStop=${pkgs.iproute}/bin/ip netns del %I

# myservice.service
[Unit]
BindsTo=netns@wg.service
After=netns@wg.service
NetworkNamespacePath=/var/run/netns/wg
[Service]
ExecStart=myservice
4 Likes