A host firewall works per port. systemd can also filter per service: this program may only talk to these addresses, whatever port it uses.
A drop-in for a service that should only reach a local database:
sudo systemctl edit myapp.service
[Service]
IPAddressDeny=any
IPAddressAllow=localhost
IPAddressAllow=192.0.2.0/24
After a restart, every socket the service opens is checked. For incoming traffic the source address is compared with the lists, for outgoing traffic the destination. An address on the allow list always gets through. Anything else that matches the deny list is dropped. any, localhost, link-local and multicast are special names you can use.
I like this for things that should never phone home. If a plugin in that app gets taken over, it can’t download a second stage or send data to some random host.
Keep DNS in mind. With the lines above, the service can’t reach an outside DNS server, so host names stop resolving unless your resolver listens on localhost, as systemd-resolved does on 127.0.0.53.
The filter uses eBPF in the kernel. Where that support is missing, for example in some containers, the settings silently do nothing, and the systemd docs say not to rely on them alone. I see it as an extra layer next to ufw or nftables.
Further reading: systemd.resource-control(5): IPAddressAllow=