SoFunction
Updated on 2025-04-11

Nginx configures system services and sets environment variables

Operational issues

Since we use source code to compile and install Nginx, it is more troublesome to start, close nginx or reload configuration files. We need to first enter the executable file directory of nginx before we can execute nginx related commands.

In order to facilitate related operations on nginx, we can configure nginx as a system service and set environment variables.

2. Configure system services

1) Create a file in the /usr/lib/systemd/system directory

sudo vim /usr/lib/systemd/system/

Add the following content:

[Unit]
#Describe the serviceDescription=nginx web service
Documentation=/en/docs/
After=
[Service]
# Backend runType=forking
# Detect configuration files before startupExecStartPre=/usr/local/nginx/nginx -t -c /usr/local/nginx/
# Start nginxExecStart=/usr/local/nginx/nginx
# Reload nginx configurationExecReload=/usr/local/nginx/nginx -s reload
# Stop nginxExecStop=/usr/local/nginx/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=

2) Modify file permissions

sudo chmod 755 /usr/lib/systemd/system/

3) Execute relevant commands

After the configuration is completed, we can use system commands to operate nginx

# Check nginx service statussystemctl status nginx

# Start nginxsystemctl start nginx

# Restart nginxsystemctl restart nginx

# Stop nginxsystemctl stop nginx

# Reload nginx configurationsystemctl reload nginx

3. Set environment variables

By configuring the system service, we can start, stop or reload nginx, but if we want to execute other commands, such as checking the nginx version, we still need to first enter the directory of the nginx executable file and then execute./nginx -v, such an operation is quite cumbersome, we can simplify the operation steps by setting environment variables.

1) Modify /etc/profile

sudo vim /etc/profile

Add at the end of the file:

export PATH=$PATH:/usr/local/nginx

2) Let the modification take effect

sudo source /etc/profile

At this point, we executenginx -v, you can see the nginx version information.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.