Course contentsShow
← Linux
Lesson 1294 of 1,81911. Automation and System SchedulingFree lesson

Network-Aware Service Activation

Ensure automation tasks wait for specific network interfaces to be online before running.

In this lesson, you will learn how to configure your automated service units to wait until a specific network interface is fully operational before executing their tasks.

The Problem of Premature Execution

When using systemd timers or event-driven automation, your script might attempt to connect to a remote database, download a file, or sync a repository the exact millisecond the system boots. If the network interface is still negotiating an IP address or the routing table isn't populated, your task will fail immediately. While you could add sleep commands to your scripts, that is a brittle "hope-based" approach. Instead, we use systemd dependencies to ensure the service only activates when the network is ready.

Leveraging network-online.target

The most common way to ensure network readiness is by using network-online.target. This target is a synchronization point that waits for networking services to confirm they have an established connection. To force your service to wait, you must define the following in your service unit file (not the timer unit):

[Unit]
Description=My Network-Dependent Task
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/local/bin/sync-script.sh

Targeting Specific Interfaces

If you need to wait for a specific interface—for example, a secondary VPN interface or a specialized hardware bridge—the standard network-online.target might trigger too early. In these cases, you can utilize systemd's ability to track device units.

If your interface is eth0, systemd creates a unit named sys-subsystem-net-devices-eth0.device. You can explicitly add this as a dependency:

[Unit]
After=sys-subsystem-net-devices-eth0.device
Requires=sys-subsystem-net-devices-eth0.device

By using Requires, you tell systemd that your service absolutely depends on the existence of that hardware state. If the interface is not present, the service will not start, preventing the execution of logic that would otherwise hang or crash due to the missing link. This creates a clean, deterministic startup flow that respects the actual state of your hardware rather than relying on arbitrary timers.

Key Takeaway: Use After= and Wants= directives to anchor your automated services to specific network targets or device units, ensuring your tasks only execute once the required connectivity is verified by the system.