Managing Services on Linux with systemctl
Many of the modern Linux distros use systemd to manage services. To control the services the command used is systemctl. Below we will see how you can start, stop, enable and disable services using systemctl. We will also look at how to view service logs using journalctl.
To experiment with systemctl we will first install nginx which is a web server. You can install nginx using the package manager of your system. For example, if you are using Ubuntu you can install nginx using the below command.
sudo apt install nginx
This will install nginx and start and enable the service. If a service is enabled it means it will start whenever the operating system boots.
To confirm if nginx is running you can run the below curl command which should show the HTML of the default nginx page.
Starting and Stopping Services
If you have done the above you know that nginx service is running. Now we will stop this service. You can run the below command to stop the service.
sudo systemctl stop nginx
To verify that nginx has stopped you can run the curl command which we has used above. This will now display an error message as the service is not running.
To start the service again you can run the below command. Use curl to verify that the service is started.
sudo systemctl start nginx
If you want to restart a service you can use the below command.
sudo systemctl restart nginx
And finally, if you want to reload nginx configuration changes without restarting the service then you can use the below command.
sudo systemctl reload nginx
If you want to check if nginx service is running or stopped you can use the below command.
sudo systemctl status nginx
This displays the status of the service with some additional information. To exit the command you can press q.
Enabling and Disabling Services
After nginx was installed the service was automatically enabled. If you reboot your system now and then check the status of the nginx service you will find that it will be running.
If you do not want to automatically start the service after booting you can disable it by running the below command.
sudo systemctl disable nginx
To enable it back you can run the below command.
sudo systemctl enable nginx
Viewing Service Logs
To view all the basic logs for the service you can use the below command. This will show the logs since the time the service was installed.
sudo journalctl -u nginx
If you want to only view logs after the system was rebooted last time you can use the below command.
sudo journalctl -b -u nginx
About the Author
Salil Ponde is software developer, blogger and DevOps enthusiast.
He has over 11 years of experience in the industry.