Course contentsShow
← Linux
Lesson 620 of 1,8196. Systemd Internals and Unit OrchestrationFree lesson

Dynamic User Management

Configure DynamicUser to execute services with ephemeral, non-privileged system users.

In this lesson, you will learn how to enhance service security by using the DynamicUser directive to create ephemeral, restricted service identities on the fly.

The Problem with Static Users

Traditionally, if you wanted to run a service with limited permissions, you had to manually create a system user using useradd. This clutters the /etc/passwd file, requires you to manage home directories, and leaves persistent accounts on your system long after a service might be decommissioned.

Enter DynamicUser

Systemd provides a feature called DynamicUser=yes within a service unit file. When this directive is enabled, systemd automatically creates a temporary user and group for that specific service at the moment it starts. When the service stops, the user is immediately discarded.

This creates a "sandboxed" environment for your process:

  1. Ephemeral Identity: The user doesn't exist in /etc/passwd.
  2. Resource Isolation: The service is automatically granted a private /tmp and /var/tmp directory, preventing it from seeing files in other temporary locations.
  3. Privilege Restriction: It effectively prevents the service from gaining elevated privileges, as the user has no login shell and no persistent home directory.

Practical Implementation

To use this, simply add the directive to the [Service] section of your unit file:

[Service]
ExecStart=/usr/bin/my-web-app
DynamicUser=yes
StateDirectory=myapp

When you set DynamicUser=yes, systemd also helps you manage persistent state. By defining StateDirectory=myapp, systemd creates a dedicated directory in /var/lib/myapp that is owned by that dynamic user. Even though the user is ephemeral, the directory persists, ensuring your service can save its configuration or log data without needing broad system access.

This approach is highly recommended for microservices or background tasks where you want to adhere to the Principle of Least Privilege without the administrative overhead of managing static system accounts.

Key Takeaway: The DynamicUser=yes directive automates the creation of temporary, isolated service identities that vanish when the service stops, significantly tightening system security with minimal configuration.