Implementing Per-Service Firewalling Using systemd (Without iptables or firewalld)

Overview

Traditional Linux firewalling relies on global rule sets managed by iptables, nftables, or firewalld. While effective, these approaches apply rules system-wide and can become complex in multi-service environments.

A lesser-known but powerful feature of systemd allows administrators to enforce network access control on a per-service basis, without modifying global firewall rules.

This document explains how to implement per-service firewall restrictions using systemd on AlmaLinux, Rocky Linux, and RHEL-based systems.


Why This Matters


Supported Systems


Key systemd Networking Directives

systemd provides built-in network filtering through the following directives:

These controls apply only to the service, not the entire system.


Step 1: Identify the Target Service

Example service:

Check the service unit:

systemctl cat nginx

Step 2: Create a systemd Override File

Never edit vendor unit files directly.

systemctl edit nginx

This opens an override configuration.


Step 3: Restrict Outbound Network Access

Allow only specific IPs or networks.

[Service]
IPAddressDeny=any
IPAddressAllow=127.0.0.1
IPAddressAllow=192.168.10.0/24

Explanation


Step 4: Restrict Protocol Families

Limit the service to IPv4 only:

[Service]
RestrictAddressFamilies=AF_INET

Supported families include:


Step 5: Reload systemd and Restart Service

systemctl daemon-reexec
systemctl restart nginx

Verify:

systemctl status nginx

Step 6: Test Network Enforcement

Attempt outbound access from the service context.

Example (PHP-FPM or app-based service):

Check logs:

journalctl -u nginx

Blocked connections are logged by systemd.


Step 7: Full Network Isolation (Optional)

To fully isolate a service:

[Service]
PrivateNetwork=yes

Result


Real-World Use Cases


Comparison with Traditional Firewalls

Feature

systemd

iptables/firewalld

Per-service rules

✅ Yes

❌ No

Global impact

❌ No

✅ Yes

Configuration complexity

Low

Medium-High

Requires extra tooling

❌ No

✅ Yes


Limitations


Security Best Practices


Verification Commands

systemctl show nginx | grep IPAddress
systemd-analyze security nginx

Conclusion

systemd’s per-service network controls provide a clean, powerful, and underutilized security layer that eliminates the need for complex firewall rules in many scenarios.

This approach is widely used in hardened enterprise environments but remains largely undocumented in public tutorials.