Sub topic 1
What Nginx Is and How It Works
Prerequisites
This chapter assumes you already have the following:
- Basic Linux command line use, including running commands with
sudo. - A working idea of HTTP requests and responses: methods, status codes, and headers.
- Basic knowledge of DNS names and TCP ports.
You do not need to have installed Nginx yet. The next chapter covers installation.
What Nginx Does
Nginx (pronounced "engine x") is a server program that listens for network connections and answers them. It is most often used for four jobs:
- Web server. It sends static files such as HTML, CSS, images, and downloads from disk to clients.
- Reverse proxy. It accepts requests from clients, forwards them to an application server, and returns the application's answer. The client never talks to the application directly.
- Load balancer. It spreads requests across several backend servers.
- TLS terminator. It handles HTTPS encryption so the backend can speak plain HTTP on a private network.
One Nginx instance can do all four at once. A common layout is Nginx on ports 80 and 443 serving static assets itself and passing dynamic requests to an application on a local port.
The Process Model
Nginx runs as a small group of processes, each with a different role.
- The master process starts as root. It reads the configuration, opens the listening ports, and starts and supervises the workers. It does not handle client traffic.
- The worker processes handle all client traffic. They run as an unprivileged user, often
www-dataon Debian and Ubuntu ornginxon Red Hat family systems.
Opening ports 80 and 443 needs root privileges, because ports below 1024 are privileged. After the master process opens them, the workers inherit them and do not need root.
You can see the layout on a running system:
ps -o pid,ppid,user,cmd -C nginxThe output shows one process owned by root whose command line contains master process, and one or more processes owned by the unprivileged user whose command line contains worker process. The workers' parent PID (ppid) is the master's PID.
The Event-Driven Model
The key design choice in Nginx is that one worker handles thousands of connections at the same time. It does this without giving each connection its own thread or process.
A traditional design, such as Apache's prefork mode, dedicates one process or thread to each connection. That worker sits idle while it waits for a slow client to send or receive data. Memory use grows with the number of connections, and the system spends time switching between many threads.
Nginx uses an event loop instead. Each worker asks the kernel to report which of its connections are ready for reading or writing. On Linux this uses the epoll interface. The worker handles whatever is ready, then asks again. Its operations are non-blocking, which means a call that cannot finish immediately returns at once instead of making the worker wait. The worker moves on to another connection and comes back when the kernel reports that the first one is ready.
The practical effects are:
- Memory use per idle connection is small, so a modest server can hold many open connections, such as slow clients and keep-alive connections.
- The number of workers is tied to CPU cores, not to the number of clients. A common setting is one worker per core.
- A single slow client does not block other clients on the same worker.
Where the Model Breaks Down
The event loop depends on every operation being quick. If a worker blocks, every connection assigned to it stalls. The main causes are:
- Slow disk reads. Reading a file from a slow or overloaded disk can block a worker. Nginx has a thread pool option for file operations, but you must enable it deliberately.
- CPU-heavy work in the worker. Very large compression levels or heavy TLS handshakes use CPU time that the worker cannot spend on other connections.
- Blocking modules. Third-party modules that do blocking work, such as a synchronous lookup, hold up the whole worker.
For this reason Nginx is not a place to run application code. It forwards that work to a separate application server.
How a Request Is Handled
When a request arrives, Nginx follows a fixed sequence of decisions. Later chapters cover each step in detail, but you need the overall order now.
- Accept the connection. A worker accepts a TCP connection on a port that a
listendirective opened. For HTTPS it completes the TLS handshake. - Choose a server block. Nginx picks a
serverblock by matching the port and address first, then theHostheader against theserver_namevalues. - Choose a location. Within that server block, Nginx matches the request URI against the
locationblocks and picks one. - Produce a response. The chosen location decides what happens next. It can serve a file from disk, forward the request to a backend with
proxy_pass, return a redirect, or return an error. - Log the request. Nginx writes a line to the access log, and writes problems to the error log.
Configuration Is Declarative and Hierarchical
You control Nginx with a text configuration file. It is made of directives, which are instructions such as listen 80;. A simple directive is a name, its values, and a semicolon. A block directive wraps other directives in braces, and the block forms a context.
The main contexts are nested like this:
main: the top level of the file. It holds process-level settings such asworker_processes.events: connection-handling settings.http: everything related to HTTP, which holdsserverblocks.server: one virtual host.location: one URI pattern inside a server.
A directive set in an outer context is generally inherited by inner contexts unless an inner one overrides it. The next chapters cover the exact rules, because inheritance has exceptions that cause common errors.
This sketch shows the shape. It is not a full working file, so do not use it as your configuration.
worker_processes auto;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name example.com;
location / {
root /var/www/example.com/html;
}
}
}The auto value tells Nginx to start one worker per available CPU core. The worker_connections value is the number of simultaneous connections each worker may hold.
Applying Configuration Changes Without Dropping Connections
The master and worker split gives Nginx a useful property: you can change the configuration without a restart that cuts off clients.
When you ask for a reload, the master process does this:
- It reads and checks the new configuration. If the check fails, it keeps the old workers running and logs the error.
- If the check passes, it starts new workers that use the new configuration.
- It tells the old workers to stop accepting new connections, finish the requests they already have, and then exit.
This is why a reload is normally safe for a live site, while a full restart stops the service briefly. The next chapters show the commands, including a syntax check you should run before every reload.
Nginx Compared With Adjacent Tools
Nginx is one of several programs that can fill similar roles. This table shows how it differs from two common ones.
| Tool | Main design | Typical strength | Typical limit |
|---|---|---|---|
| Nginx | Event-driven workers | Static files, reverse proxy, many idle connections | Runs no application code itself |
| Apache HTTP Server | Process or thread per connection in some modes, event mode in newer setups | Per-directory `.htaccess` overrides, many modules | Needs more tuning for very high connection counts |
| HAProxy | Event-driven proxy | Detailed load balancing and health checks | Does not serve files from disk |
One difference affects day-to-day work. Apache can read per-directory .htaccess files on every request, so users can change behavior without touching the main configuration. Nginx has no equivalent. All settings live in the main configuration files, which makes requests faster and keeps control with the administrator. It also means every change needs a reload.
Common Misunderstandings
- "Nginx runs my PHP or Python code." It does not. It passes requests to a separate program, such as PHP-FPM or an application server, and returns the result.
- "More workers is always faster." Workers beyond the number of CPU cores mostly add switching overhead. Start with
auto. - "A reload applies instantly everywhere." Old workers keep serving their current requests until they finish. A long download can keep an old worker alive for some time after a reload.
- "The master process serves requests." It does not. If you see traffic problems, look at worker behavior and logs, not the master.
Key Takeaways
Nginx is a master process that supervises event-driven worker processes. Each worker serves many connections by reacting to readiness events, so keep its work short and non-blocking. Every request is matched to a server block and then to a location, and that location decides the response. Configuration is hierarchical text, and a reload lets you apply it without dropping connections.
Exercise
You run ps -o pid,ppid,user,cmd -C nginx and see one process owned by root and four owned by www-data. A teammate says the root process is slowing down requests because it runs as root. What is wrong with that claim, and which processes would you examine if requests were slow?
Show answer
The root process is the master. It reads configuration, opens the listening ports, and supervises the workers, but it does not handle client requests, so it cannot slow them. The four www-data processes are the workers that handle all traffic. To investigate slow requests you would look at the workers' behavior and at the access and error logs, and check for blocking causes such as slow disk reads, heavy CPU use, or a slow backend.
Exercise
A site with 5,000 mostly idle keep-alive connections runs on a server with 4 CPU cores. Explain why Nginx can serve them with a few worker processes, and suggest a value for worker_processes.
Show answer
Each worker uses an event loop with non-blocking operations, so it only does work for connections the kernel reports as ready. Idle connections cost little memory and no thread time, so one worker can hold thousands of them. A sensible setting is worker_processes auto;, which starts one worker per core, so four workers on this server.