Bird
Raised Fist0
Nginxdevops~5 mins

Keepalive connections in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
When a web server talks to a client, it can open a new connection for every request. This wastes time and resources. Keepalive connections let the server reuse the same connection for multiple requests, making websites faster and saving resources.
When your website has many small requests like images, scripts, or stylesheets loading together.
When you want to reduce the delay users feel when clicking links or loading pages.
When your server handles many users and you want to save CPU and memory by not opening new connections repeatedly.
When you want to improve performance for mobile users with slower networks.
When you want to reduce network congestion by limiting how often connections open and close.
Config File - nginx.conf
nginx.conf
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    keepalive_timeout  65;
    keepalive_requests 100;

    server {
        listen       8080;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

keepalive_timeout sets how long the server keeps the connection open waiting for new requests.

keepalive_requests limits how many requests can reuse the same connection before closing it.

The server block defines a simple web server listening on port 8080.

Commands
Check the nginx configuration file for syntax errors before starting the server.
Terminal
nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Start the nginx server with the current configuration.
Terminal
nginx
Expected OutputExpected
No output (command runs silently)
Make a HTTP request to the server showing verbose output and using keepalive to reuse the connection.
Terminal
curl -v --keepalive-time 60 http://localhost:8080/
Expected OutputExpected
* Trying 127.0.0.1:8080... * Connected to localhost (127.0.0.1) port 8080 (#0) > GET / HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.68.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.21.6 < Date: Thu, 01 Jun 2023 12:00:00 GMT < Content-Type: text/html < Content-Length: 612 < Last-Modified: Wed, 31 May 2023 10:00:00 GMT < Connection: keep-alive < ETag: "609d-5c1a3e4f" < Accept-Ranges: bytes < {html content} * Connection #0 to host localhost left intact
→
--keepalive-time - Sets the TCP keepalive time in seconds to keep the connection alive.
→
-v - Shows detailed request and response information.
Make a second HTTP request reusing the same connection to demonstrate keepalive in action.
Terminal
curl -v --keepalive-time 60 http://localhost:8080/
Expected OutputExpected
* Re-using existing connection to localhost:8080. > GET / HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.68.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.21.6 < Date: Thu, 01 Jun 2023 12:00:05 GMT < Content-Type: text/html < Content-Length: 612 < Last-Modified: Wed, 31 May 2023 10:00:00 GMT < Connection: keep-alive < ETag: "609d-5c1a3e4f" < Accept-Ranges: bytes < {html content} * Connection #0 to host localhost left intact
→
--keepalive-time - Keeps the TCP connection alive for reuse.
→
-v - Shows detailed request and response information.
Key Concept

If you remember nothing else from this pattern, remember: keepalive connections let the server reuse the same network connection for multiple requests, making websites faster and saving resources.

Common Mistakes
Not setting keepalive_timeout or setting it too low.
The server closes connections too quickly, losing the benefit of reuse and causing delays.
Set keepalive_timeout to a reasonable value like 60 seconds to allow multiple requests on the same connection.
Not testing the configuration with 'nginx -t' before starting nginx.
Syntax errors cause nginx to fail silently or not start, leading to downtime.
Always run 'nginx -t' to verify configuration syntax before starting or reloading nginx.
Forgetting to reload or restart nginx after changing keepalive settings.
Changes do not take effect until nginx reloads the configuration, so keepalive behavior stays old.
Run 'nginx -s reload' or restart nginx after editing the config file.
Summary
Configure keepalive_timeout and keepalive_requests in nginx.conf to enable connection reuse.
Test nginx configuration syntax with 'nginx -t' before starting the server.
Use curl with verbose and keepalive flags to verify connections are reused.
Reload nginx after configuration changes to apply new keepalive settings.

Practice

(1/5)
1. What is the main benefit of using keepalive connections in nginx?
easy
A. They disable caching on the server.
B. They close connections immediately after each request.
C. They increase the number of open connections indefinitely.
D. They reuse the same connection for multiple requests, improving speed.

Solution

  1. Step 1: Understand what keepalive connections do

    Keepalive connections allow the same connection to be reused for multiple requests instead of opening a new one each time.
  2. Step 2: Identify the benefit of reusing connections

    Reusing connections reduces the time and resources needed to establish new connections, thus improving speed and reducing server load.
  3. Final Answer:

    They reuse the same connection for multiple requests, improving speed. -> Option D
  4. Quick Check:

    Keepalive = reuse connection for speed [OK]
Hint: Keepalive means reuse connection to speed up requests [OK]
Common Mistakes:
  • Thinking keepalive closes connections immediately
  • Believing keepalive increases open connections endlessly
  • Confusing keepalive with caching
2. Which of the following is the correct syntax to set the keepalive timeout to 30 seconds in nginx?
easy
A. keepalive_timeout 30s
B. keepalive_timeout 30;
C. keepalive_timeout: 30s;
D. keepalive_timeout = 30;

Solution

  1. Step 1: Recall nginx directive syntax

    Nginx directives use the format: directive_name value; without equal signs or colons.
  2. Step 2: Check the correct value format for time

    Timeout values in nginx can be specified as numbers (seconds) without units or with units like 's'. Both are accepted, but the common practice is just a number for seconds.
  3. Final Answer:

    keepalive_timeout 30; -> Option B
  4. Quick Check:

    Directive syntax = name value; no '=' or ':' [OK]
Hint: Nginx directives use 'name value;' syntax without '=' [OK]
Common Mistakes:
  • Using '=' sign in directive
  • Adding colon ':' after directive name
  • Adding units like 's' unnecessarily
3. Given this nginx configuration snippet:
keepalive_timeout 10;
keepalive_requests 100;

What happens after 100 requests on the same keepalive connection?
medium
A. The connection is closed and a new one is opened for the next request.
B. The connection stays open indefinitely.
C. The server resets the timeout to 10 seconds again.
D. The connection is closed immediately after the first request.

Solution

  1. Step 1: Understand keepalive_requests directive

    This directive limits how many requests can be sent over one keepalive connection before it closes.
  2. Step 2: Apply the limit of 100 requests

    After 100 requests, nginx closes the connection and opens a new one for the next request to avoid stale connections.
  3. Final Answer:

    The connection is closed and a new one is opened for the next request. -> Option A
  4. Quick Check:

    keepalive_requests = max requests per connection [OK]
Hint: keepalive_requests limits requests per connection [OK]
Common Mistakes:
  • Thinking connection stays open forever
  • Confusing timeout with request count
  • Assuming connection closes after first request
4. You set keepalive_timeout 20; but clients report connections close too quickly. Which is the likely mistake?
medium
A. The keepalive_requests is set to 1, closing after one request.
B. The timeout value is too low for client needs.
C. You forgot to reload nginx after changing config.
D. The server is running an old nginx version without keepalive support.

Solution

  1. Step 1: Check common reasons for config changes not applying

    If nginx is not reloaded or restarted after config changes, old settings remain active.
  2. Step 2: Confirm reload necessity

    After changing keepalive_timeout, nginx must be reloaded with nginx -s reload or restarted to apply changes.
  3. Final Answer:

    You forgot to reload nginx after changing config. -> Option C
  4. Quick Check:

    Config changes need reload to apply [OK]
Hint: Reload nginx after config changes to apply them [OK]
Common Mistakes:
  • Assuming timeout value alone fixes issue
  • Ignoring need to reload nginx
  • Blaming nginx version without checking
5. You want to optimize nginx for many short requests by keeping connections alive but closing them after 15 seconds or 50 requests, whichever comes first. Which configuration is correct?
hard
A. keepalive_timeout 15;\nkeepalive_requests 50;
B. keepalive_timeout 50;\nkeepalive_requests 15;
C. keepalive_timeout 15s;\nkeepalive_requests 50s;
D. keepalive_timeout 15s;\nkeepalive_requests 50; keepalive_disable none;

Solution

  1. Step 1: Set keepalive_timeout to 15 seconds

    This controls how long a connection stays open waiting for new requests.
  2. Step 2: Set keepalive_requests to 50

    This limits the number of requests per connection before closing it.
  3. Step 3: Verify correct syntax and values

    keepalive_timeout 15;\nkeepalive_requests 50; uses correct syntax and values matching the requirement: 15 seconds timeout and 50 requests limit.
  4. Final Answer:

    keepalive_timeout 15;\nkeepalive_requests 50; -> Option A
  5. Quick Check:

    Timeout 15 + Requests 50 = correct config [OK]
Hint: Timeout sets seconds, requests sets max requests per connection [OK]
Common Mistakes:
  • Swapping timeout and requests values
  • Adding units to keepalive_requests
  • Using invalid directives like keepalive_disable
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard