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

Ordering Dependencies

Use Before and After directives to ensure services start in a specific logical sequence.

Mastering Execution Sequence with Ordering Dependencies

In this lesson, you will learn how to orchestrate the startup sequence of your services using the Before and After directives to ensure a logical and stable boot process.

When managing multiple services, you often encounter situations where one application cannot function unless another is already running. For example, a web application might require a database to be fully initialized and accepting connections before it attempts to bind to a port. If they start simultaneously, the application might crash because its dependency isn't ready.

Controlling the Timeline

In systemd, dependencies are defined within the [Unit] section of your service files. While Requires or Wants tell the system which units should be started, they do not inherently guarantee the order in which they start. That is where Before= and After= come in.

  • After=: Ensures the current unit starts only after the specified units have successfully initialized.
  • Before=: Ensures the current unit completes its startup sequence before the specified units begin theirs.

Consider this scenario for a web application and its database:

[Unit]
Description=My Web Application
After=postgresql.service

[Service]
ExecStart=/usr/bin/web-app

In this configuration, systemd will wait for postgresql.service to transition to an "active" state before it triggers the execution of your web application. It is important to note that these directives only affect the ordering; they do not create a strict requirement. If you want to ensure the database is both a prerequisite and an ordering dependency, you would use Requires=postgresql.service alongside After=postgresql.service.

Why This Matters

Using these directives allows you to build a resilient dependency tree. Instead of relying on "sleep" timers or brittle scripts that blindly wait for ports to open, you define the desired state of the system explicitly. This ensures that your services are launched in the exact sequence required for operational readiness, preventing race conditions during the critical boot window.

Key Takeaway: Use the Before and After directives in your unit files to explicitly define the chronological sequence of service startup, ensuring that services only begin once their prerequisites are fully active.