How To Configure a Linux Service to Start Automatically After a Crash or Reboot

Linux Services that can be controlled with Linux’s “service” command, for example –

sudo service nginx status

are controlled by scripts in the folder /etc/init.d/. These scripts define functions such as start(), stop(), reload(), status() etc that tells what to do when a service command is given. For example: when a service command such as –

sudo service nginx start

it calls the start() function defined in the script file nginx under the folder /etc/init.d/

With that background, let’s try to understand how Linux knows which service to start at the time of system boot. Services run at their levels and there are 7 run levels(0-6) defined in Linux. Each run level has its own folder in the /etc/ folder as shown below -.

If a service needs to be started or killed at a certain level, symbolic links are defined for that service in the respective run level directory. For example: if nginx needs to be started at the system boot at the level 2, you will see the following symbolic link under rc2.d directory for nginx:

Note that the symlinks that start with K indicate that the service will be stopped (killed) in that run level. Symlinks that start with S indicate that the service will be started. As you can see from the figure above: S85nginx points to the same service command script in init.d folder we talked about in the beginning of this article. This is how Linux knows which service to start at the system boot.

Does that mean you have to manually create these symbolic links for the service to start at the system boot? Fortunately, Linux (especially RedHat) comes with a command called chkconfig which you can use to create these symbolic links for you. For example –

sudo chkconfig nginx on 

will create symbolic links to start nginx at levels 2,3,4 and 5 by default. Before “chkconfig” system administrators used to manually create these symbolic links.

man chkconfig

to read more about chkconfig.

Leave a Reply

Your email address will not be published. Required fields are marked *