Top Nginx Performance Tweaks: Worker Processes and CPU Affinity Explained
This guide shows how to edit nginx.conf to adjust worker_processes based on CPU cores, explains when I/O blocking requires extra workers, and demonstrates Linux‑only worker_cpu_affinity settings with concrete examples for 2, 4, and 8‑core systems, including the exact commands to apply and reload the configuration.
All Nginx performance improvements start by editing the nginx.conf file.
1. worker_processes – number of worker processes
The default is one worker with a maximum of 1024 connections per process. Each worker runs a single thread and invokes various modules. If the modules are non‑blocking, the number of workers should match the number of CPU cores; if blocking I/O is possible, a few extra workers may be needed.
For example, when static files are read from a small‑memory server, disk I/O can block workers and degrade overall performance.
Typical setting: set the number of workers to the number of CPU cores (or cores × 2). Use top -1 to view core count.
# Edit nginx configuration
vi /usr/local/nginx/conf/nginx.conf
# Set workers, e.g., 4
worker_processes 4;
# Reload configuration
/usr/local/nginx/sbin/nginx -s reload
# Verify processes
ps -aux | grep nginx | grep -v grep2. worker_cpu_affinity – binding workers to CPU cores
If each worker is heavily loaded, allowing multiple workers to compete for the same CPU can cause contention. Assigning each worker a dedicated core enables true parallelism on Linux.
Note: worker_cpu_affinity works only on Linux.
Configuration examples:
# 2‑core system
worker_processes 2;
worker_cpu_affinity 10 01;
# 4‑core system
worker_processes 4;
worker_cpu_affinity 1000 0100 0010 0001;
# 8‑core system
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;These settings bind each worker to a specific CPU mask, eliminating CPU contention and improving throughput.
Linux Tech Enthusiast
Focused on sharing practical Linux technology content, covering Linux fundamentals, applications, tools, as well as databases, operating systems, network security, and other technical knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
