Skip to content

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 nginx
    3656 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_processes module

Basic Tasks

The general syntax for nginx is:

nginx -s <signal>
SignalDescription
stopFast shutdown
quitGraceful shutdown
reloadReloading the configuration file
reopenReopening 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 reload should be used
  • when reload signal 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.pid which can be at /usr/local/nginx/local directory or /var/run directory 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 -1 to get master process’ pid
  • ps -ax | grep [n]ginx can be also used to get master and worker processes’ pid however pgrep nginx is modern way of greping pids

About Config Files

  • config file is generally named as nginx.conf and can be found inside -> /etc/nginx, /usr/local/nginx/conf, /usr/local/etc/nginx depending 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 whereas server, 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: events and http directives reside in main context whereas server resides inside http and location resides inside server forming nested contexts:
    http {
        ...
        server {
            ...
            location {
                ...
            }
            ...
        }
        ...
    }

HTTP Status Code Quick Reference Table

CodeMeaningTypeExplanation
100ContinueInformationalThe server has received the initial part of the request and the client can continue sending the request.
101Switching ProtocolsInformationalThe server agrees to switch to a different protocol requested by the client, such as upgrading from HTTP to WebSocket.
102ProcessingInformationalThe server has received and is processing the request, but the final response is not ready yet.
103Early HintsInformationalThe 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.
200OKSuccessThe request was successfully processed. The response usually contains the requested resource or the result of the operation.
201CreatedSuccessThe request succeeded and caused a new resource to be created. Commonly returned after POST requests that create a resource.
202AcceptedSuccessThe server accepted the request for processing, but processing has not necessarily completed yet. Useful for asynchronous operations.
204No ContentSuccessThe request succeeded, but there is no content to return in the response body. Commonly used after successful DELETE or update operations.
206Partial ContentSuccessThe server is returning only part of a resource, usually because the client requested a specific byte range. Common for resumable downloads and media streaming.
300Multiple ChoicesRedirectionMultiple possible responses/resources are available, and the client may need to choose one. It is relatively uncommon in normal web applications.
301Moved PermanentlyRedirectionThe requested resource has permanently moved to a new URL. Clients and search engines can update their references to use the new URL.
302FoundRedirectionThe requested resource is temporarily available at another URL. The original URL should generally continue to be used for future requests.
303See OtherRedirectionThe client should retrieve the requested information from another URL, typically using a GET request.
304Not ModifiedRedirectionThe resource has not changed since the client’s cached version. The client can use its existing cached copy instead of downloading it again.
307Temporary RedirectRedirectionThe resource is temporarily available at another URL, while preserving the original HTTP method. For example, a POST remains a POST.
308Permanent RedirectRedirectionThe resource has permanently moved to another URL, while preserving the original HTTP method.
400Bad RequestClient ErrorThe server cannot understand or process the request because the request is invalid or malformed. For example, invalid JSON or missing required parameters.
401UnauthorizedClient ErrorAuthentication is required or the supplied authentication credentials are invalid. Despite the name, this generally means “not authenticated” rather than “not authorized.”
403ForbiddenClient ErrorThe server understood the request but refuses to fulfill it. The client may be authenticated but does not have sufficient permission.
404Not FoundClient ErrorThe requested resource could not be found on the server. The URL may be incorrect, or the resource may no longer exist.
405Method Not AllowedClient ErrorThe requested HTTP method is not supported for that resource. For example, sending DELETE to an endpoint that only supports GET.
406Not AcceptableClient ErrorThe server cannot provide a response that matches the client’s requested representation, such as an unsupported response format.
408Request TimeoutClient ErrorThe server did not receive the complete request from the client within the time it was willing to wait.
409ConflictClient ErrorThe request conflicts with the current state of the resource. For example, attempting to create a username that already exists.
410GoneClient ErrorThe requested resource has been permanently removed and is intentionally no longer available.
411Length RequiredClient ErrorThe server requires the request to include a Content-Length header.
412Precondition FailedClient ErrorA condition specified by the client in the request headers was not satisfied. This is commonly used with conditional requests.
413Content Too LargeClient ErrorThe request body is larger than the server is willing or able to process. For example, uploading a file that exceeds the configured size limit.
414URI Too LongClient ErrorThe requested URL is too long for the server to process. This can happen when excessive data is placed in the URL/query string.
415Unsupported Media TypeClient ErrorThe server does not support the format of the request body. For example, sending XML when an API only accepts JSON.
416Range Not SatisfiableClient ErrorThe requested portion of a resource cannot be provided, usually because the requested byte range is invalid or outside the resource’s size.
429Too Many RequestsClient ErrorThe client has sent too many requests within a certain period. It is commonly used for rate limiting APIs and other services.
500Internal Server ErrorServer ErrorA generic server-side failure occurred while processing the request. The server encountered an unexpected condition it could not handle.
501Not ImplementedServer ErrorThe server does not support the functionality required to fulfill the request.
502Bad GatewayServer ErrorA server acting as a gateway or proxy received an invalid response from an upstream server. Common with reverse proxies such as NGINX.
503Service UnavailableServer ErrorThe server is currently unable to handle the request, usually because it is overloaded, undergoing maintenance, or temporarily unavailable.
504Gateway TimeoutServer ErrorA 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.
505HTTP Version Not SupportedServer ErrorThe 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:

CodeRemember it as
200Everything worked
201Resource created
204Worked, but nothing to return
301Permanently moved
302Temporarily moved
304Use your cached copy
400Your request is invalid
401You need to authenticate
403You’re authenticated/recognized, but not allowed
404Resource not found
405HTTP method not allowed
408Request took too long
409Request conflicts with current state
413Request is too large
429Too many requests
500Server crashed/failed unexpectedly
502Proxy/gateway got a bad upstream response
503Service temporarily unavailable
504Proxy/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