NGINX Introduction
What is NGINX?
- NGINX was initially launched as open source high performant webserver.
- since then NGINX has been matured and now widely serve as load balancer, reverse proxy, http caching, etc.
Why NGINX?
- delivers high performance, handles massive concurrent connections, and consumes minimal memory compared to traditional web servers.
- NGINX is fast primarily because of its asynchronous, event-driven architecture.
- unlike traditional web servers that create a new process or thread for every single user connection, NGINX handles thousands of connections concurrently within a very small number of fixed worker processes.
- NGINX is very easy to configure which makes it popular in K8s space too.
Notes
- nginx has one master process and several worker processes ->
pgrep -a nginx3656 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; 3657 nginx: worker process 3658 nginx: worker process 3659 nginx: worker process 3660 nginx: worker process 3661 nginx: worker process 3663 nginx: worker process - master process reads and evaluates the configuration and also manages worker processes
- workder process does the actual processing of requests
- the requests are distributed efficiently among workers using event-based model and OS dependent mechanisms
- the number of workers can be set fixed in config file OR can also be dynamic based on available CPU cores which is managed by
worker_processesmodule
Basic Tasks
The general syntax for nginx is:
nginx -s <signal>| Signal | Description |
|---|---|
stop | Fast shutdown |
quit | Graceful shutdown |
reload | Reloading the configuration file |
reopen | Reopening the log files |
nginx -t can be used to validate syntax of configuration files.
About nginx -s reload
- changes made to configuration files won’t be applied unless NGINX is reloaded
- whenever you make changes,
nginx -s reloadshould be used - when
reloadsignal is received by NGINX, it checks syntax and everything else and tries to apply the new configuration - if it succeeds, master process starts new worker processes and asks the old processes to stop serving (not shutdown immediately)
- old worker processes are not shutdown immediately, they just stops getting new requests but keep serving current requests and exit once all pending requests are served which is similar to graceful shutdown
- when NGINX is unable to apply new configuration, it rolls back and keep serving with the same old configuration
Note
nginx supports reload which means it is possible to systemctl reload nginx.
Process Files and Killing NGINX
- master process pid file is
nginx.pidwhich can be at/usr/local/nginx/localdirectory or/var/rundirectory depending on OS and configuration - you can use this pid file to directly kill NGINX master process as:
kill -s QUIT $(cat /var/run/nginx.pid)- you can also use
pgrep nginx | head -1to get master process’ pid ps -ax | grep [n]ginxcan be also used to get master and worker processes’ pid howeverpgrep nginxis modern way ofgreping pids
About Config Files
- config file is generally named as
nginx.confand can be found inside ->/etc/nginx,/usr/local/nginx/conf,/usr/local/etc/nginxdepending on implementation - NGINX has several modules which are controlled by directives inside the config file
- directives can be simple or block directives
- simple directive anatomy ->
simple_directive param1 param2 paramN; - block directive anatomy:
block_directive { simple_directive param1 param2 paramN; ... another_block_directive { ... } ... } - for example:
root,listen, etc. are simple directives whereasserver,location, etc. are block directives - directives inside block directives are known as contexts
- directives in config file outside of any contexts are main directives
- for example:
eventsandhttpdirectives reside in main context whereasserverresides insidehttpandlocationresides insideserverforming nested contexts:http { ... server { ... location { ... } ... } ... }
HTTP Status Code Quick Reference Table
| Code | Meaning | Type | Explanation |
|---|---|---|---|
| 100 | Continue | Informational | The server has received the initial part of the request and the client can continue sending the request. |
| 101 | Switching Protocols | Informational | The server agrees to switch to a different protocol requested by the client, such as upgrading from HTTP to WebSocket. |
| 102 | Processing | Informational | The server has received and is processing the request, but the final response is not ready yet. |
| 103 | Early Hints | Informational | The server sends preliminary information, often HTTP headers such as Link, before the final response is ready. This can help the browser start loading resources early. |
| 200 | OK | Success | The request was successfully processed. The response usually contains the requested resource or the result of the operation. |
| 201 | Created | Success | The request succeeded and caused a new resource to be created. Commonly returned after POST requests that create a resource. |
| 202 | Accepted | Success | The server accepted the request for processing, but processing has not necessarily completed yet. Useful for asynchronous operations. |
| 204 | No Content | Success | The request succeeded, but there is no content to return in the response body. Commonly used after successful DELETE or update operations. |
| 206 | Partial Content | Success | The server is returning only part of a resource, usually because the client requested a specific byte range. Common for resumable downloads and media streaming. |
| 300 | Multiple Choices | Redirection | Multiple possible responses/resources are available, and the client may need to choose one. It is relatively uncommon in normal web applications. |
| 301 | Moved Permanently | Redirection | The requested resource has permanently moved to a new URL. Clients and search engines can update their references to use the new URL. |
| 302 | Found | Redirection | The requested resource is temporarily available at another URL. The original URL should generally continue to be used for future requests. |
| 303 | See Other | Redirection | The client should retrieve the requested information from another URL, typically using a GET request. |
| 304 | Not Modified | Redirection | The resource has not changed since the client’s cached version. The client can use its existing cached copy instead of downloading it again. |
| 307 | Temporary Redirect | Redirection | The resource is temporarily available at another URL, while preserving the original HTTP method. For example, a POST remains a POST. |
| 308 | Permanent Redirect | Redirection | The resource has permanently moved to another URL, while preserving the original HTTP method. |
| 400 | Bad Request | Client Error | The server cannot understand or process the request because the request is invalid or malformed. For example, invalid JSON or missing required parameters. |
| 401 | Unauthorized | Client Error | Authentication is required or the supplied authentication credentials are invalid. Despite the name, this generally means “not authenticated” rather than “not authorized.” |
| 403 | Forbidden | Client Error | The server understood the request but refuses to fulfill it. The client may be authenticated but does not have sufficient permission. |
| 404 | Not Found | Client Error | The requested resource could not be found on the server. The URL may be incorrect, or the resource may no longer exist. |
| 405 | Method Not Allowed | Client Error | The requested HTTP method is not supported for that resource. For example, sending DELETE to an endpoint that only supports GET. |
| 406 | Not Acceptable | Client Error | The server cannot provide a response that matches the client’s requested representation, such as an unsupported response format. |
| 408 | Request Timeout | Client Error | The server did not receive the complete request from the client within the time it was willing to wait. |
| 409 | Conflict | Client Error | The request conflicts with the current state of the resource. For example, attempting to create a username that already exists. |
| 410 | Gone | Client Error | The requested resource has been permanently removed and is intentionally no longer available. |
| 411 | Length Required | Client Error | The server requires the request to include a Content-Length header. |
| 412 | Precondition Failed | Client Error | A condition specified by the client in the request headers was not satisfied. This is commonly used with conditional requests. |
| 413 | Content Too Large | Client Error | The request body is larger than the server is willing or able to process. For example, uploading a file that exceeds the configured size limit. |
| 414 | URI Too Long | Client Error | The requested URL is too long for the server to process. This can happen when excessive data is placed in the URL/query string. |
| 415 | Unsupported Media Type | Client Error | The server does not support the format of the request body. For example, sending XML when an API only accepts JSON. |
| 416 | Range Not Satisfiable | Client Error | The requested portion of a resource cannot be provided, usually because the requested byte range is invalid or outside the resource’s size. |
| 429 | Too Many Requests | Client Error | The client has sent too many requests within a certain period. It is commonly used for rate limiting APIs and other services. |
| 500 | Internal Server Error | Server Error | A generic server-side failure occurred while processing the request. The server encountered an unexpected condition it could not handle. |
| 501 | Not Implemented | Server Error | The server does not support the functionality required to fulfill the request. |
| 502 | Bad Gateway | Server Error | A server acting as a gateway or proxy received an invalid response from an upstream server. Common with reverse proxies such as NGINX. |
| 503 | Service Unavailable | Server Error | The server is currently unable to handle the request, usually because it is overloaded, undergoing maintenance, or temporarily unavailable. |
| 504 | Gateway Timeout | Server Error | A server acting as a gateway or proxy did not receive a response from an upstream server within the expected time. Common when a backend application is slow or unavailable. |
| 505 | HTTP Version Not Supported | Server Error | The server does not support the HTTP version used in the request. |
The most important ones to remember
For everyday web development and troubleshooting, these are the ones you’ll encounter most often:
| Code | Remember it as |
|---|---|
| 200 | Everything worked |
| 201 | Resource created |
| 204 | Worked, but nothing to return |
| 301 | Permanently moved |
| 302 | Temporarily moved |
| 304 | Use your cached copy |
| 400 | Your request is invalid |
| 401 | You need to authenticate |
| 403 | You’re authenticated/recognized, but not allowed |
| 404 | Resource not found |
| 405 | HTTP method not allowed |
| 408 | Request took too long |
| 409 | Request conflicts with current state |
| 413 | Request is too large |
| 429 | Too many requests |
| 500 | Server crashed/failed unexpectedly |
| 502 | Proxy/gateway got a bad upstream response |
| 503 | Service temporarily unavailable |
| 504 | Proxy/gateway timed out waiting for upstream |
A useful way to remember the categories:
1xx = “I’m working on it”
2xx = “It worked”
3xx = “Go somewhere else / use something else”
4xx = “Your request has a problem”
5xx = “The server has a problem”
References
NGINX Beginners Guide -> https://nginx.org/en/docs/beginners_guide.html
Last updated on