Running portable service in systemd
Portable service is New and Preview feature added in systemd which isolates a group of services. This will just attach a subfodler or raw image that contains the OS-Tree
to the host systemd. This will not provide all kind of isolation as containers does but will provide strict access control for the running service. For detailed explanation on the internals please check systemd portable service.
In this Blog will see how to create a image subfolder, populating basic hello-world application service then running that service as portable service.
Pre-requisite
- Ubuntu 20.04 or higher
-
Portable systemd enabled. In ubuntu this can be done by installing
systemd-container
package.sudo apt install systemd-container
-
gcc installed. In ubuntu it can be done by following command,
sudo apt install gcc
Creating the image sub-folder and hello world service
Portable service attach a subfolder or the raw os image to the running systemd. But the requirement is this subfolder or raw image should contain some basic folder structure (os-tree) in place. In this section we will create this structure and create a hello world service
-
Create the basic folder structure.
mkdir ./portabletest cd ./portabletest mkdir -p ./usr/bin/ ./usr/lib/systemd/system/ /usr/lib/ ./etc/ ./proc/ ./sys/ ./dev/ ./run/ ./tmp/ ./var/tmp/ cd -
-
Create required os files.
touch portabletest/etc/resolv.conf touch portabletest/etc/machine-id cp /usr/lib/os-release portabletest/usr/lib/
-
Create a hello world application service.
echo -e "#include <stdio.h> int main(void) { printf(\"hello-world\n\"); return 0; } " > main.c && gcc -static main.c -o ./portabletest/usr/bin/helloworld echo -e "[Unit] Description=hello world [Service] Type=oneshot ExecStart=/usr/bin/helloworld RemainAfterExit=true StandardOutput=journal [Install] WantedBy=multi-user.target" > ./portabletest/usr/lib/systemd/system/portabletest-helloworld.service
Attaching the portable service and start
-
Attach the portable service.
portablectl attach ./portabletest
-
Start the service and verify it is running.
systemctl start portabletest-helloworld.service systemctl status portabletest-helloworld.service
Now the Portable service can be treated as any other systemd service.
Detach or remove the portable service
To detach the portable service, execute the following command,
portablectl --now detach ./portabletest
--now
flag is required if this portable service contains services which is already running and you want to stop that and detach.