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

Advanced ExecStart Pre-processing

Utilize ExecStartPre and ExecStartPost to initialize prerequisites or perform cleanup tasks.

In this lesson, you will learn how to automate the setup and teardown of your services using ExecStartPre and ExecStartPost directives within a Systemd unit file.

Orchestrating Service Life-Cycles

Often, a daemon needs more than just a binary to run successfully. It might require specific directory permissions, a pre-validated configuration file, or a network interface to be ready. Instead of writing complex wrapper scripts, you can utilize Systemd’s built-in hooks to manage these prerequisites directly.

  • ExecStartPre=: These commands run before the main ExecStart process. If any command listed here fails (returns a non-zero exit code), the main service will not start. This is the perfect place to create temporary runtime directories, verify connectivity to a database, or perform sanity checks on config files.
  • ExecStartPost=: These commands run immediately after the main process has successfully started. Use this for tasks like sending a "Service Ready" notification to a monitoring system, updating a log file status, or clearing out temporary lock files from a previous crashed run.

Practical Implementation

Imagine a web server that requires a specific log directory and a notification once it's live:

[Service]
ExecStartPre=/usr/bin/mkdir -p /run/myapp/logs
ExecStartPre=/usr/bin/chown myuser:myuser /run/myapp/logs
ExecStart=/usr/bin/myapp-server
ExecStartPost=/usr/bin/curl -X POST http://monitoring-server/notify-up

By placing these tasks here, you maintain a clean separation of concerns. You ensure the environment is pristine before the daemon binds to its resources and handle reporting automatically once it is active. Because these commands are part of the unit definition, Systemd keeps track of them within the service's cgroup, ensuring that if you stop the service, the logic is treated as part of that single, cohesive unit of work.

Key Takeaway: Use ExecStartPre to guarantee a valid environment before launch and ExecStartPost to trigger necessary post-launch side effects, keeping your service logic modular and self-contained.