Post

Nginx (Part 1): How Nginx Runs — Linux Foundations, Packages, systemd and Config

Nginx from the ground up: the Linux concepts underneath it, why the same nginx looks different depending on who packaged it, how systemd starts it, master and worker processes, nginx.conf and what include really does.

Nginx (Part 1): How Nginx Runs — Linux Foundations, Packages, systemd and Config

Nginx series: 1. How Nginx Runs · 2. Routing Requests · 3. Internal Requests & Auth · 4. Gateway Auth in Practice · Extra: Variables & Dynamic Proxy · Refresher & Quick Reference

This series explains nginx from the ground up: what it is on a Linux machine, how it routes requests, and how it handles authentication. This first part answers the basic questions: what is nginx on a server, who starts it, which processes run, and how its configuration is put together. Once this is clear, every config you meet later is just detail.

Every example comes from two real servers (hostnames, domains, IPs and app names anonymised):

ServerIPNginx packageWhat runs there
server14 (server 14)10.20.30.14nginx.org packageSeveral Django apps (tool1, tool2, tool3, tool4) via uwsgi, each on its own domain
server85 (server 85)10.20.30.185Ubuntu/Debian packageThe devicehub app: React frontend + FastAPI backend, path-based routing

The configs and command outputs are snapshots (October 2026): worked examples of two real setups, not the current state of those machines. On any machine, the live state is one command away: sudo nginx -T (full expanded config), systemctl cat nginx (how it’s started), ls -l /etc/nginx/conf.d /etc/nginx/sites-enabled (which sites exist).

📑 Table of Contents

1. The Big Picture in One Diagram

Before any detail, here is the whole story. Everything in this series zooms into one box of this picture.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 ┌──────────────┐
 │   Browser    │   user types http://10.20.30.185/  or  https://tool2-dev.example.com/
 └──────┬───────┘
        │ (1) DNS: "what IP is tool2-dev.example.com?"  → 10.20.30.14
        │ (2) TCP connect to IP:port (80 for http, 443 for https)
        │ (3) HTTP request with a "Host:" header + a path (/api/devices/)
        ▼
 ┌───────────────────────────────────────────────────────────────────────┐
 │  HOST MACHINE (Ubuntu)                                                │
 │                                                                       │
 │  systemd (PID 1) ──starts at boot──► nginx MASTER (root)             │
 │                                        │ forks                        │
 │                                        ▼                              │
 │                              nginx WORKERS (www-data / nginx user)    │
 │                                        │                              │
 │       (4) worker picks a server{} block by matching Host → server_name│
 │       (5) inside that block, picks a location{} by matching the path  │
 │                                        │                              │
 │          ┌─────────────────────────────┼─────────────────────────┐    │
 │          ▼                             ▼                         ▼    │
 │   serve static file          proxy_pass http://127.0.0.1:8000   uwsgi_pass unix:/run/uwsgi/x.sock
 │   from disk (React dist/)    (FastAPI — on host or in Docker)   (Django via uwsgi)
 │                                                                       │
 └───────────────────────────────────────────────────────────────────────┘
        │
        ▼ (6) response travels back the same way to the browser

The one-sentence version: systemd starts nginx at boot → nginx master forks workers → a worker receives each request → nginx picks the site by the Host header and the handler by the URL path → it either serves a file from disk or forwards the request to a backend app → the response goes back.

This part covers the top half of the picture: systemd, master, workers and the config they read. Part 2 covers steps (4) and (5).


2. Linux Foundations You Need First

nginx sits on top of a handful of Linux concepts. Most confusion about nginx is really confusion about these, so here they are first.

Processes

Every running program is a process. Every process has:

  • a PID (process ID): unique number
  • a PPID (parent process ID): the process that created it
  • an owner (UID / username): whose permissions it runs with

Processes form a tree. The root of the tree is PID 1, which on Ubuntu is systemd.

fork() is the Linux system call that makes a copy of the current process. The copy (child) gets a new PID, and its PPID points to the creator. This is exactly how the nginx master creates its workers.

A daemon is a background process with no terminal attached (that’s why ps shows ? in the TTY column). Services like nginx, sshd, docker are daemons. The classic way to become a daemon: start → fork → parent exits → child keeps running in the background.

Reading ps -ef output

1
2
3
UID        PID   PPID  C STIME TTY    TIME     CMD
root       1436  1     0 Oct03 ?      00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx      1437  1436  0 Oct03 ?      00:00:08 nginx: worker process
ColumnMeaningIn this example
UIDusername owning the processroot (master), nginx (worker)
PIDthis process’s ID1436 / 1437
PPIDparent’s IDmaster’s parent is 1 (systemd); worker’s parent is 1436 (master)
CCPU usage0
STIMEstart timeOct03 → running since boot on Oct 3
TTYterminal? = no terminal = daemon
TIMEtotal CPU time used8 seconds
CMDthe command linewhat was executed

ps -ef | grep nginx matches the text anywhere in the line, including the username column and the grep command itself. On a server where other apps run under the nginx user account, it lists them too. To see only the real nginx processes:

1
2
3
4
pgrep -a nginx                 # matches process NAME, not user
ps -C nginx -f                 # processes whose command name is nginx
ps -ef | grep "[n]ginx:"       # the [n] trick stops grep from matching itself
systemctl status nginx         # shows the service's own process tree (CGroup)

Signals

Signals are tiny messages the kernel delivers to a process. Nginx reacts to them:

SignalNginx’s reaction
HUPreload config (zero downtime)
QUITgraceful stop: finish current requests, then exit
TERM / INTfast stop
KILLcannot be caught: the kernel kills immediately

You’ll see these in the unit files (section 4).

PID files

A daemon writes its PID into a file (e.g. /run/nginx.pid) so other tools know which process to signal. cat /run/nginx.pid → 1436 on server 14. (/var/run is a symlink to /run, so pid /var/run/nginx.pid; in a config is the same location.)

Users and privileged ports

Linux has normal users (user01) and service accounts: users that exist only so a daemon can run with limited permissions. Nginx workers run as one:

  • Debian/Ubuntu package → user www-data
  • nginx.org package → user nginx

Different packagers created different accounts for the same purpose (section 3). On server 14 the admin also runs the Django apps under the nginx account, which is why ps lists their uwsgi and celery processes as user nginx; it also lets nginx use their socket files (see sockets below).

Privileged ports (< 1024): only root can bind (listen on) ports below 1024, like 80 (HTTP) and 443 (HTTPS). That’s why the nginx master starts as root. Ports ≥ 1024 (like 8000, 8080, 9090) can be used by any user, which is why app servers use them.

Files: symlinks and permissions

A symbolic link is a pointer to another file. Debian’s sites-enabled/ directory normally contains symlinks pointing into sites-available/:

1
2
ls -l /etc/nginx/sites-enabled/
# devicehub -> /etc/nginx/sites-available/devicehub

Delete the symlink → site disabled, original config still kept. (It can also be a plain file; nginx doesn’t care.)

File permissions matter for nginx

Workers run as www-data/nginx, not as you. To serve a file, that user needs:

  • read permission on the file, and
  • execute (x) permission on every parent directory in the path.

Server 85 serves from /home_ldap/user01/workspace/devicehub_frontend/dist, so www-data must be able to traverse /home_ldap, /home_ldap/user01, workspace, … If not → 403 Forbidden. Check with:

1
2
namei -l /home_ldap/user01/workspace/devicehub_frontend/dist/index.html
sudo -u www-data cat /home_ldap/user01/workspace/devicehub_frontend/dist/index.html

Network: interfaces, 0.0.0.0 and sockets

Network interfaces, loopback, and 0.0.0.0

A machine has several network interfaces, each with an address:

AddressMeansWho can reach an app bound to it
127.0.0.1 / localhostthe loopback interface onlyonly processes on the same machine (or same network namespace / container)
10.20.30.185 (example)the machine’s real network cardanyone on the network who can route to it
0.0.0.0all interfaces (loopback + real IPs + any others)anyone who can reach any of the machine’s IPs

In Docker this matters: an app inside a container must bind 0.0.0.0, because the container’s localhost is its own (Part 2, section 13).

0.0.0.0 is not an address you connect to. It’s a wildcard meaning “bind to everything.” After binding to 0.0.0.0:8080, the app answers on 127.0.0.1:8080 and on 10.x.x.x:8080.

1
2
ip addr        # list interfaces and their IPs
ss -tlnp       # list listening TCP sockets: which address:port, which process

Example ss -tlnp lines and what they mean:

1
2
LISTEN 0 511   0.0.0.0:80        ...  nginx       ← reachable from network
LISTEN 0 2048  127.0.0.1:8000    ...  uvicorn     ← only reachable from this machine (nginx can reach it, outsiders can't)

Sockets: TCP vs Unix domain sockets

Two ways processes talk:

  • TCP socket: 127.0.0.1:8000. Goes through the network stack (even if local).
  • Unix domain socket: a special file, e.g. /run/uwsgi/tool2_autodeploy.sock. Only works on the same machine, slightly faster, and access is controlled by file permissions (that’s one reason the Django apps on server 14 run as the nginx user: nginx can read/write their socket file).

3. One Program, Two Packages

Nginx is one compiled C program: the binary /usr/sbin/nginx. When run, it reads a config file and starts listening on the ports the config says (usually 80 and 443). It can:

  • serve static files directly from disk, or
  • act as a reverse proxy: receive requests and forward them to another application (FastAPI, Django, …).

But you never install just the binary. You install a package (a .deb on Ubuntu, via apt), and whoever builds the package decides everything around the binary:

  • the systemd unit file (/usr/lib/systemd/system/nginx.service) → how nginx is started
  • the default config (/etc/nginx/nginx.conf, plus mime.types etc.) → what nginx does out of the box
  • the service user the workers run as (www-data or nginx)
  • man pages, log-rotation config, install scripts

apt install nginx downloads the .deb, unpacks all of these, registers and enables the service.

Same binary, different packaging. Ubuntu/Debian and the nginx team both package the same program, but each made its own choices for the unit file, the default config and the user. So the same nginx can look different on two machines: it’s launched differently, its config is laid out differently, and it runs as a different user. The program and its behaviour are the same. When two servers’ nginx look different, compare the unit file (section 4) and the main config (section 6).

The two sources of nginx packages

 Source A: Ubuntu/Debian repoSource B: nginx.org repo
Who builds itDebian/Ubuntu maintainersThe nginx team
How you get itapt install nginx on a stock Ubuntufirst add nginx.org’s repo, then apt install nginx
Unit file style-g 'daemon on; master_process on;', ExecStartPre test, start-stop-daemon-c ${CONFFILE}, raw kill -s HUP/TERM
Worker userwww-datanginx
Site config dirsconf.d/ and sites-available/ + sites-enabled/only conf.d/
Modulesseparate packages via modules-enabled/compiled in
Example serverserver 85server 14

Both install the same program, load /etc/nginx/nginx.conf, and produce master + workers. Only the surrounding files differ.

Which package does this server have?

1
2
3
4
5
nginx -v                         # version; Ubuntu builds usually show "(Ubuntu)"
nginx -V 2>&1 | tr ' ' '\n'      # full build flags, incl. --conf-path=/etc/nginx/nginx.conf
apt-cache policy nginx           # shows which repo it came from (nginx.org/packages/... vs ubuntu archive)
dpkg -S /usr/lib/systemd/system/nginx.service   # which package owns the unit file
dpkg -l | grep nginx             # Debian splits into nginx, nginx-common, libnginx-mod-*

--conf-path=/etc/nginx/nginx.conf in nginx -V is the compiled-in default config path: the file nginx loads when no -c is given.


4. systemd — Who Starts Nginx and How

When Linux boots, the kernel starts exactly one user-space process: systemd (PID 1), the init system. Its job is to start and manage every other service, using unit files: plain-text descriptions of services.

  • Package-provided units live in /usr/lib/systemd/system/
  • Admin overrides go in /etc/systemd/system/ (these win)
1
systemctl cat nginx    # shows the unit file actually in effect, including overrides

systemd itself (unit files, where they live, enable vs start, drop-in overrides, Type=, timers) is explained from scratch in systemd, systemctl and Service Files. This section covers only what nginx’s two packages do with it.

How the two packages start nginx

Both packages ship a unit file that starts the same binary. The lines that differ are the Exec* commands; the rest is shared plumbing. Grouped for comparison (the real files have [Unit]/[Service]/[Install] sections; both full files are in the appendix). The # notes at the ends of lines are annotations for reading: in a real unit file, comments must be on their own line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ── Ubuntu/Debian package (server 85) ──────────────────────────────────────────
ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;'    # TEST config first; abort start if broken
ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'             # no -c → compiled-in default nginx.conf
ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload  # reload via nginx itself
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid   # graceful QUIT → TERM → KILL

# ── nginx.org package (server 14) ──────────────────────────────────────────────
Environment="CONFFILE=/etc/nginx/nginx.conf"
ExecStart=/usr/sbin/nginx -c ${CONFFILE}                                 # -c = explicit config path
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /run/nginx.pid)"      # reload = HUP signal to master
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /run/nginx.pid)"       # stop  = TERM signal to master

# ── shared by both ─────────────────────────────────────────────────────────────
Type=forking                  # nginx will daemonize (fork into background)
PIDFile=/run/nginx.pid        # systemd reads the master's PID from here
WantedBy=multi-user.target    # "enabled" = start during normal boot
FlagMeaning
-g '...'set global directives on the command line (here: run as daemon, use master process)
-ttest the config and exit (syntax check)
-qquiet: only print errors during the test
-s reloadsend a signal to the running master (reload, quit, stop, reopen)
-c <file>use this config file; without -c, the compiled-in default /etc/nginx/nginx.conf
- before a command (ExecStop=-...)systemd ignores a failure exit code from that command

What this changes in practice: the ps line looks different, because it shows the command each unit ran:

1
2
server 85:  nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
server 14:  nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf

But both load the same file, /etc/nginx/nginx.conf: server 85 implicitly (compiled-in default), server 14 explicitly (-c). Same file, same behaviour. Only style differs: Debian also tests the config before starting and stops gracefully; nginx.org’s unit sends raw signals.

The boot sequence step by step (Type=forking)

  1. Machine boots; kernel starts systemd (PID 1).
  2. systemd reaches multi-user.target; nginx is enabled, so systemd starts it (after the network is up).
  3. (Server 85 only) systemd runs ExecStartPre → nginx -t checks the config. Error → start aborted.
  4. systemd runs ExecStart: it literally forks and executes that command, as if typed in a terminal.
  5. Nginx reads its config and binds port 80/443 (it’s root at this point, so it may).
  6. Nginx forks: the original process exits (“I’m done starting”), the child continues as the master.
  7. The master writes its PID to /run/nginx.pid.
  8. systemd reads the PID file → now monitors that process. If it dies, systemd knows the service crashed.
  9. The master forks worker processes (section 5).

5. Master and Worker Processes

Once systemd has started nginx, you can see the result directly:

1
2
3
4
5
6
7
8
9
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-10-06 14:36:51 CEST; 2 days ago
   Main PID: 431185 (nginx)
      Tasks: 9 (limit: 19063)
     CGroup: /system.slice/nginx.service
             ├─431185 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ├─431186 "nginx: worker process"
             ... (8 workers total)
  • Loaded: … enabled: which unit file is used, and that it starts at boot
  • Active: … since: when it was started (≈ last boot/restart)
  • Main PID: the master process
  • Tasks: 9: 1 master + 8 workers
  • CGroup: the exact processes belonging to the service, only real nginx, unlike grep

(Warning: some journal files were not opened due to insufficient permissions just means you’re not root; use sudo journalctl -u nginx to see the logs.)

Who creates the workers, and how many

The master does. Chain: systemd starts the master → master reads the config → master calls fork() N times → N workers.

How many is set in the main config (section 6), not on the command line:

1
worker_processes auto;

auto = ask the OS how many CPU cores there are, create one worker per core. Both servers’ packaged configs use it, so the worker count simply follows the hardware: server 85 has 8 cores → 8 workers, server 14 has 4 cores → 4 workers. You could hard-code worker_processes 4;, but auto is the sensible default.

1
2
3
nproc                                       # number of CPU cores
grep worker_processes /etc/nginx/nginx.conf # the directive
pgrep -c -f "nginx: worker"                 # count workers

Why one worker per core?

Each nginx worker is a single-threaded event loop. One worker handles thousands of connections at once using epoll (a Linux system call): “are any of my sockets ready to read/write? yes → handle it; no → wait.” No threads, no context switching between them → very efficient.

But one single-threaded process uses one core at a time. 8 cores + 1 worker = 7 idle cores. 8 workers = the kernel spreads them across all 8 cores. 16 workers on 8 cores = extra context switching, slower. So auto = maximum use without oversubscribing.

worker_connections: capacity per worker

1
2
3
4
5
6
events {
    worker_connections 768;    # server 85: the Debian package's default
}
events {
    worker_connections 1024;   # server 14: the nginx.org package's default
}

Max simultaneous connections per worker. The two values are just what each packager chose; you can change them. Rough total = workers × worker_connections (server 85: 8 × 768 = 6144; server 14: 4 × 1024 = 4096). A proxied request uses two connections (client↔nginx and nginx↔backend), so real client capacity is about half.

What the master and the workers do

 Master (runs as root)Workers (run as www-data / nginx)
Handles requests?neverall of them
Its jobsbinds port 80/443 (needs root), reads the config, forks the workers, restarts a crashed worker, swaps workers on reloadaccept connections, read HTTP requests, serve files, forward to backends (proxy_pass), send responses
How it worksone process, waits for signalsindependent processes; the OS distributes incoming connections among them

Why workers drop root privileges

The master needs root for one thing only: binding ports < 1024. After that, workers are started under the user from the config (user www-data; / user nginx;). If someone exploits a bug in the HTTP-handling code (which runs in a worker), they get www-data permissions, not root. The master never touches untrusted HTTP traffic.

1
2
3
4
5
root   1436  ← master (root: binds port 80)
 ├─ nginx  1437  ← worker (low-privilege user)
 ├─ nginx  1438
 ├─ nginx  1439
 └─ nginx  1440

Zero-downtime reload

sudo systemctl reload nginx (or sudo nginx -s reload):

  1. Signal reaches the master.
  2. Master reads and validates the new config. (Invalid → keeps running with the old one, logs an error.)
  3. Master starts new workers with the new config.
  4. Master tells old workers: stop accepting new connections, finish current ones, exit.
  5. Old workers drain and die; new workers handle everything.

The master never stops: its PID stays the same. At no moment are there zero workers. Old and new overlap briefly.

Always test before reloading:

1
sudo nginx -t && sudo systemctl reload nginx

reload vs restart: reload = graceful, keeps master; restart = full stop + start (drops connections briefly).


6. The Main Config File — nginx.conf

systemd starts the binary; the binary reads one main config: /etc/nginx/nginx.conf (via the compiled-in default or -c, section 4). This file comes with the package, filled with that packager’s defaults, and it’s yours to edit.

It holds the global settings (user, workers, logging, defaults for all sites), plus include lines that pull in more files. Those included directories are where your own sites go: you normally don’t add a site by editing nginx.conf, you drop a file with a server {} block into conf.d/ (or sites-enabled/ on Debian) and reload.

Structure: contexts (nesting)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# ── main context (global) ────────────────────────────
user  www-data;
worker_processes auto;

events {                       # ── connection handling ──
    worker_connections 768;
}

http {                         # ── everything HTTP ──
    # settings here apply to all sites below

    server {                   # ── one virtual host (one site) ──
        listen 80;
        server_name example.com;

        location /api/ {       # ── rule for a URL path ──
            proxy_pass http://127.0.0.1:8000;
        }
    }
}

Settings inherit downward: something set in http {} applies to every server {} unless overridden inside it.

What the two packages ship

Trimmed to the lines that matter (... = left out; full files in the appendix):

1
2
3
4
5
6
7
8
9
10
11
12
# ── Ubuntu/Debian package (server 85) ──
user www-data;                                   # workers run as www-data
worker_processes auto;
include /etc/nginx/modules-enabled/*.conf;       # Debian-only: load optional modules
events { worker_connections 768; }

http {
    include /etc/nginx/mime.types;               # maps .js → application/javascript, .css → text/css ...
    ...
    include /etc/nginx/conf.d/*.conf;            # site configs (style 1)
    include /etc/nginx/sites-enabled/*;          # Debian-only: site configs (style 2) ← devicehub lives here
}
1
2
3
4
5
6
7
8
9
10
# ── nginx.org package (server 14) ──
user  nginx;                                     # workers run as "nginx"
worker_processes  auto;
events { worker_connections  1024; }

http {
    include       /etc/nginx/mime.types;
    ...
    include /etc/nginx/conf.d/*.conf;            # ONLY conf.d — no sites-enabled
}

Same structure, different packager choices: the worker user, the default worker_connections, and where site files go (Debian adds sites-enabled/). The user nginx; line is also where server 14’s nginx account comes from (section 2).

This main file is only global settings. The parts that matter for your app (which ports, which domains, where to proxy) live in the included files. How including works is the next section.


7. include — It’s Copy-Paste

Yes, it works like C’s #include

When nginx reads /etc/nginx/nginx.conf and hits an include line, it replaces that line with the full contents of the matching file(s), before processing anything. A glob like *.conf is expanded and the files are pasted in alphabetical order.

Server 14’s main config:

1
2
3
4
http {
    ...
    include /etc/nginx/conf.d/*.conf;
}

Directory contents:

1
2
3
4
5
6
7
default.conf
devicehub-upload.conf
tool1-api-dev.conf
tool1-dev.conf
tool2-dev.conf
tool3-dev.conf
tool4-api-def.conf

What nginx effectively sees in memory:

1
2
3
4
5
6
7
8
9
10
11
http {
    ...everything from nginx.conf above the include...

    ...entire contents of default.conf...
    ...entire contents of devicehub-upload.conf...
    ...entire contents of tool1-api-dev.conf...
    ...entire contents of tool1-dev.conf...
    ...entire contents of tool2-dev.conf...
    ...entire contents of tool3-dev.conf...
    ...entire contents of tool4-api-def.conf...
}

Server 85 has two includes, so both directories are pasted into the same http {} block:

1
2
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;     # ← devicehub

Why split into files at all?

Purely for humans: one file per app is easier to manage, add, remove, and review than one giant file. To nginx it’s all one config.

Consequences of “it’s one config”

  • A syntax error in any included file breaks the whole config → nginx -t fails → reload refused.
  • Two files defining the same server_name on the same port → nginx warns conflicting server name ... ignored.
  • An upstream name defined in one file is visible to all others (they share one namespace).
  • Files must be pasted where the directive is allowed: conf.d files contain server {}/upstream {} blocks because they’re included inside http {}.

See the fully expanded config with your own eyes

1
2
3
sudo nginx -T              # test + DUMP the entire config, every included file, in order
sudo nginx -T | grep -n "server_name"      # all virtual hosts at a glance
sudo nginx -T | grep "# configuration file"  # which files got included

nginx -T is the proof that include = copy-paste: it prints the main file plus each included file with a # configuration file /etc/nginx/conf.d/xyz.conf: marker.


Appendix: full reference files

The complete files from the two servers as captured (October 2026). Sections 4 and 6 show the parts that matter; expand these when you want the whole picture.

Server 85's unit file (Debian/Ubuntu package), annotated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Stop dance for nginx
# ExecStop sends SIGQUIT (graceful stop) to the nginx process.
# If, after 5s (--retry QUIT/5) nginx is still running, systemd takes control
# and sends SIGTERM (fast shutdown) to the main process.
# After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends
# SIGKILL to all the remaining processes in the process group (KillMode=mixed).

[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network-online.target remote-fs.target nss-lookup.target   # start only after network/DNS are up
Wants=network-online.target
ConditionFileIsExecutable=/usr/sbin/nginx                        # skip if the binary is missing

[Service]
Type=forking                       # nginx will daemonize (fork into background)
PIDFile=/run/nginx.pid             # systemd reads the master's PID from here
ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;'   # TEST config first; abort start if broken
ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'            # the real start command
ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload # reload = send HUP via nginx itself
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid
TimeoutStopSec=5
KillMode=mixed                     # TERM to main process; leftover processes get KILL after timeout

[Install]
WantedBy=multi-user.target         # "enabled" = start during normal boot
Server 14's unit file (nginx.org package), annotated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
Environment="CONFFILE=/etc/nginx/nginx.conf"     # variable used below
Environment="cmdopts="                           # empty extra options
EnvironmentFile=-/etc/default/nginx              # optional file that can override those vars ("-" = ignore if missing)
ExecStart=/usr/sbin/nginx -c ${CONFFILE} $cmdopts   # -c = explicit config path
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /run/nginx.pid)"   # reload = HUP signal to master
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /run/nginx.pid)"    # stop  = TERM signal to master

[Install]
WantedBy=multi-user.target

This is where -c /etc/nginx/nginx.conf in server 14’s ps output comes from: the ExecStart line expands ${CONFFILE}.

Unit files side by side
 Server 85 (Debian)Server 14 (nginx.org)
ps showsnginx: master process /usr/sbin/nginx -g daemon on; master_process on;nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
Config pathimplicit (compiled-in default)explicit (-c)
Config file loaded/etc/nginx/nginx.conf/etc/nginx/nginx.conf
Pre-start testyes (ExecStartPre ... -t)no
Reloadnginx -s reloadkill -s HUP
Stopgraceful QUIT, then TERM, then KILLTERM
Server 85's nginx.conf (Debian), annotated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
user www-data;                                   # workers run as www-data (Debian's web user)
worker_processes auto;                           # one worker per CPU core
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;       # Debian-only: load optional modules

events {
        worker_connections 768;
}

http {
        sendfile on;                             # kernel copies files directly to socket (fast static files)
        tcp_nopush on;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;           # maps .js → application/javascript, .css → text/css ...
        default_type application/octet-stream;   # unknown extensions

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        gzip on;                                 # compress responses

        include /etc/nginx/conf.d/*.conf;        # site configs (style 1)
        include /etc/nginx/sites-enabled/*;      # Debian-only: site configs (style 2) ← devicehub lives here
}
Server 14's nginx.conf (nginx.org), annotated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
user  nginx;                                     # workers run as "nginx" user
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;                   # /var/run → /run (same place)

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;  # uses the "main" format above

    sendfile        on;
    keepalive_timeout  65;                        # keep idle client connections open 65s
    server_tokens off;                            # hide nginx version in errors/headers (admin added)

    include /etc/nginx/conf.d/*.conf;             # ONLY conf.d — no sites-enabled
}
The two nginx.conf files compared
SettingServer 85 (Debian)Server 14 (nginx.org)Why
userwww-datanginxeach packager created its own account
modules-enabled includeyesnoDebian splits modules into packages
sites-enabled includeyesnoDebian convention (symlink enable/disable)
worker_connections7681024different defaults
gziponoff (commented)different defaults
log_format mainnoyesnginx.org default
server_tokens offno (commented)yessecurity tweak by admin
This post is licensed under CC BY 4.0 by the author.