When we install Nginx by manually make and install from source, if the server restart Nginx will not launch automatically. In order to do so, we’ll need to create Nginx as Systemd service.
In addition to enabling Nginx to automatically turn on at shutdown, Systemd service has many other benefits, such as ability to use service command to view status, or to start, stop, restart, etc.
Start by create nginx.service file at /lib/systemd/system by using command:
sudo vi /lib/systemd/system/nginx.service
Then configure as follow:
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
User=root
Group=root
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
ExecStartPost=/bin/sleep 0.1
[Install]
WantedBy=multi-user.target
Enable the service:
sudo systemctl enable nginx
เสร็จแล้วควรลองรีสตาร์ทดูว่าเมื่อเปิดเครื่องกลับมาแล้ว nginx รันขึ้นมาไหม ซึ่งเราสามารถดูสถานะของการทำงานของ service นี้ได้โดยใช้คำสั่ง
Now, try restarting to see if Nginx launch automatically after the server is back on. We can see the working state of this service by using command:
sudo service nginx status
If PID file error appears when running the status command, check the settings in the nginx.conf file (at /usr/local/nginx/conf/nginx.conf) to see if the PID file path is set. If not, add new lines with the following values pid /run/nginx.pid;
Other service command such as:
sudo service nginx start
sudo service nginx stop
sudo service nginx restart