Nginx is a web server and mail proxy server, often used as a front end on high-traffic web projects. From time to time there is a need to monitor the number of requests processed by them in order to respond in a timely manner to the increase in load. Next, it will be shown how to organize monitoring of Nginx using MRTG.

To begin with, enable status in nginx. To do this, add the following lines to the configuration of one of the virtual hosts:

        # By this path will be available server status
location / nginx_status {
# Enable status display
stub_status on;
# Who is allowed to access here. At least our monitoring server
allow 10/12/14/16;
# At the same time the network in which our administrators are sitting (just in case)
allow 172.17.233.0/25;
# All other access is closed
deny all; }

After that, restart nginx. Now, when accessing the “/ nginx_status” location of our virtual host from one of the resolved addresses, we will get approximately this information:

Active connections: 272
server accepts handled requests
65274467 65274255 150927366
Reading: 47 Writing: 68 Waiting: 157

We are interested in the first number in the third line (the number of connections processed) and the third (the number of requests). Parsing is a simple PHP script:


#! / usr / bin / php
<? php
// Get the host name
$ host = isset ($ argv [1])? $ argv [1]: '127.0.0.1';
// Get the data
$ data = file ('http: //'. $ host. '/ nginx_status');
// Parsing data
$ line = trim ($ data [2]);
$ conns = preg_replace ('/ ^ (\ d +?) \ s +? \ d +? \ s +? \ d +? $ /', "$ 1", $ line);
$ reqs = preg_replace ('/ ^ \ d +? \ s +? \ d +? \ s +? (\ d +?) $ /', "$ 1", $ line);
// Display the result
print "$ conns \ n";
print "$ reqs \ n";
print time (). "\ n";
print "$ host \ n";

The script must be saved to a file and made executable. At the same time, you need to check the path to the PHP interpreter in the first line (it may differ depending on the system). To draw a graph in the MRTG configuration, you need to add lines like this:

Target [nginx]: /var/www/mrtg/scripts/nginx.php frontend.domain.com
MaxBytes [nginx]: 1
Title [nginx]: nginx statistics
PageTop [nginx]: <h1> nginx statistics </ h1>
AbsMax [nginx]: 1250000
Options [nginx]: integer, nopercent, nobanner, growright, dorelpercent
YLegend [nginx]: per second
ShortLegend [nginx]: per second
Legend1 [nginx]: Connections per second
Legend2 [nginx]: Requests per second

As a result, this graph will be drawn:

Here the blue line is the number of requests processed every second. Green – the number of connections. Yellow – the ratio of the number of connections to the number of requests. It allows you to indirectly assess the efficiency of using tcp connections (the lower the line the better).

That’s all. Have a nice work!