Sunday, April 16, 2017

Running a service in own network namespace in Ubuntu

Running a service inside network namespace in pre Ubuntu 16.04 versions was as easy as running a command such as:  
ip netns exec [NAMESPACE_NAME] service [SERVICE_NAME] start

However things got slightly more complicated in Ubuntu 16.04 and newer versions.

In this example we will run transmission-daemon service inside a namespace. You have to remember that the namespace MUST exist and be configured before starting the transmission-daemon. Otherwise the command will fail. For this purpose we have to modify the /lib/systemd/system/transmission-daemon.service file as follows:

[Unit]
Description=Transmission BitTorrent Daemon
After=network.target

[Service]
User=root
Type=simple
ExecStart=/bin/sh -c 'exec /sbin/ip netns exec YOURNAMESPACE /usr/bin/sudo -u debian-transmission /usr/bin/transmission-daemon -f --log-error --config-dir /var/lib/transmission-daemon/info'
ExecReload=/bin/kill -s HUP $MAINPID

[Install]
WantedBy=multi-user.target

Here we need to start service as root because we will need to access the namespace to be able to start the transmission-daemon. It is important to change the Type as simple otherwise you may have problems returning back to command line after giving the service start command. The rest is simply a matter of changing ExecREload to run transmission-daemon manually inside the network namespace while changing user to debian-transmission user

Remember to change YOURNAMESPACE with the namespace you want to use. Now you can start transmission daemon easily by running service transmission-daemon start

No comments:

Post a Comment