As web applications continue to grow in popularity, it's increasingly important to limit the number of concurrent connections to web services in order to maintain a good user experience and ensure service stability. Nginx, a high-performance web server and reverse proxy server, offers a variety of configuration options to help achieve this goal. This article will explain how to configure the Nginx proxy server to limit concurrent connections in web services, along with concrete code examples.
First, you need to install Nginx. Below are the installation commands for Ubuntu:
<span class="fun">$ sudo apt update</span>
<span class="fun">$ sudo apt install nginx</span>
Once Nginx is installed, open and edit the Nginx configuration file:
<span class="fun">$ sudo nano /etc/nginx/nginx.conf</span>
Next, add the following configuration within the `http` block:
http {
...
# Limit concurrent connections to 100
limit_conn_zone $binary_remote_addr zone=concurrent:10m;
server {
...
# Limit concurrent connections to 10
limit_conn concurrent 10;
}
}
In this configuration, `limit_conn_zone` defines a shared memory zone (10MB in size) to store the concurrent connection counts for each client. The `limit_conn` directive is used inside each `server` block to define the maximum number of concurrent connections, in this case, 10.
After configuring, restart the Nginx service to apply the changes:
<span class="fun">$ sudo systemctl restart nginx</span>
To verify that the configuration is working, use the `ab` (Apache Benchmark) command for stress testing. Below is an example of using the `ab` command:
<span class="fun">$ ab -c 100 -n 1000 http://localhost/</span>
In this example, the `-c 100` flag sets the concurrency to 100, and the `-n 1000` flag sets the total number of requests to 1000. If the configuration is successful, you should see output similar to the following:
Concurrency Level: 100
Time taken for tests: 10.000 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 158000 bytes
...
By configuring the Nginx proxy server to limit concurrent connections, you can effectively prevent web services from being overwhelmed by too many connections, ensuring better performance. The configuration examples provided in this article help you implement this feature quickly. Depending on your specific needs, you may want to make further adjustments to these settings. We hope this article has been helpful!