This blog is a short reminder, a quick how to create a simple systemd service.
I will use two mock-up files, /etc/init.d/firewall.sh
service script and the firewall.service
systemd unit file.
1. Create /etc/init.d/firewall.sh
service script and make it executable.
#!/bin/sh ### BEGIN INIT INFO # Provides: Firewall # Required-Start: # Required-Stop: # Default-Start: # Default-Stop: # Short-Description: Starts firewall rules # Description: Starts firewall rules ### END INIT INFO # Exit immediately if a command exits with a non-zero status. set -e case $1 in start) iptables -F iptables -A INPUT -s 192.168.200.0/24 -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j DROP ;; stop) iptables -F ;; *) echo "Usage: /etc/init.d/firewall.sh {start|stop}" exit 1 ;; esac
chmod +x /etc/init.d/firewall.sh
2. Create the systemd service unit file /lib/systemd/system/firewall.service
.
[Unit] Description=Firewall Requires=network-online.target After=network-online.target [Service] User=root Type=oneshot RemainAfterExit=yes ExecStart=/etc/init.d/firewall.sh start ExecStop=/etc/init.d/firewall.sh stop [Install] WantedBy=multi-user.target
3. Enable at startup the firewall.service
.
systemctl enable firewall
Created symlink /etc/systemd/system/multi-user.target.wants/firewall.service → /lib/systemd/system/firewall.service.
That’s it, now that we created and enabled the service, let’s see other useful commands.
Start and stop the service.
systemctl start firewall
systemctl stop firewall
Disable the service.
systemctl disable firewall
Removed /etc/systemd/system/multi-user.target.wants/firewall.service.
List available systemd targets.
systemctl list-units --type target