问题原文
原帖链接 · 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
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
