大网数据广告活动
服务器运维问答

How to bind ports to systemd services for firewall configuration?

· 52CE 我爱测

I would like to somehow bind the network ports a service needs to it's systemd configuration, so that the correlating ports are only open if the service is running properly. Just adding trigger that add/remove firewall rules woul…

问题原文

原帖链接 · Tobias Liese · CC BY-SA 4.0

I would like to somehow bind the network ports a service needs to it's systemd configuration, so that the correlating ports are only open if the service is running properly.

Just adding trigger that add/remove firewall rules would not be a senible solution, since this would upset the ruleset order.

Thanks in advance.

已采纳解答

原帖链接 · HBruijn · CC BY-SA 4.0

Please consider that in general services are expected to run continuously.

In that regard dynamically opening and closing ports in your firewall when a service is either started or stopped does not achieve much of a benefit.

When a port is open in your firewall but there is no listener to accept an incoming connection because the service is stopped/failed , that connection is going to be refused anyway.


Just adding trigger that add/remove firewall rules would not be a sensible solution, since this would upset the ruleset order.

Although under the hood all Linux flavours use iptables/netfiler for the actual firewall, rather than directly manipulating the rules most come with a userfriendly front-end to manage firewall settings.

Make your application work with those front-ends and there is much less risk that enabling/disabling your service will break things.

Systemd services are likely to come with firewalld - check for instance https://firewalld.org/documentation/howto/add-a-service.html on how to define a firewall profile for your service.

Once your service is defined opening all ports associated with that service during runtime is then limited to a single command such as:

firewall-cmd --zone=public --add-service=myservice

and removing the service is similarly simple:

firewall-cmd --zone=public --remove-service=myservice

I would like to somehow bind the network ports a service needs to it's systemd configuration, so that the correlating ports are only open if the service is running properly.

In your systemd service unit file use ExecStartPre= with the appropriate command to open up the firewall before starting your service and close the ports again when the service has been stopped with ExecStopPost=.

[Unit]
Description=My service

[Service]
Type=forking
ExecStart=/usr/sbin/my-simple-daemon -d
ExecStartPre=firewall-cmd --zone=public --add-service=myservice
ExecStopPost=firewall-cmd --zone=public --remove-service=myservice

[Install]
WantedBy=multi-user.target

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-10-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。