fbpx
28.3 C
Jakarta
Senin, 29 April 2024

Tuning NGINX Untuk Performa Terbaik

Untuk konfigurasi ini Anda dapat menggunakan server web yang Anda suka, saya memutuskan, karena saya kebanyakan bekerja dengannya menggunakan nginx.

Secara umum, nginx yang dikonfigurasi dengan benar dapat menangani hingga 400K hingga 500K permintaan per detik (berkerumun), sebagian besar yang saya lihat adalah 50K hingga 80K (non-cluster) permintaan per detik dan beban CPU 30%, tentu saja, ini adalah 2 x Intel Xeon dengan HyperThreading diaktifkan, tetapi dapat bekerja tanpa masalah pada mesin yang lebih lambat.

Anda harus memahami bahwa konfigurasi ini digunakan dalam lingkungan pengujian dan bukan dalam produksi sehingga Anda perlu menemukan cara untuk mengimplementasikan sebagian besar fitur tersebut sebaik mungkin untuk server Anda.
Stable version NGINX (deb/rpm)
Mainline version NGINX (deb/rpm)

Pertama, Anda harus menginstal nginx
RHEL/Centos

yum install nginx

Debian/Ubuntu

apt install nginx

Sebelum instalasi, cadangkan konfigurasi asli Anda dan Anda dapat mulai mengkonfigurasi ulang konfigurasi Anda.
Anda perlu membuka nginx.conf di /etc/nginx/nginx.conf dengan editor favorit Anda.
Berikut konfigurasinya:

# you must set worker processes based on your CPU cores, nginx does not benefit from setting more than that
worker_processes auto; #some last versions calculate it automatically

# number of file descriptors used for nginx
# the limit for the maximum FDs on the server is usually set by the OS.
# if you don't set FD's then OS settings will be used which is by default 2000
worker_rlimit_nofile 100000;

# only log critical errors
error_log /var/log/nginx/error.log crit;

# provides the configuration file context in which the directives that affect connection processing are specified.
events {
    # determines how much clients will be served per worker
    # max clients = worker_connections * worker_processes
    # max clients is also limited by the number of socket connections available on the system (~64k)
    worker_connections 4000;

    # optimized to serve many clients with each thread, essential for linux -- for testing environment
    use epoll;

    # accept as many connections as possible, may flood worker connections if set too low -- for testing environment
    multi_accept on;
}

http {
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # to boost I/O on HDD we can disable access logs
    access_log off;

    # copies data between one FD and other from within the kernel
    # faster than read() + write()
    sendfile on;

    # send headers in one piece, it is better than sending them one by one
    tcp_nopush on;

    # don't buffer data sent, good for small data bursts in real time
    tcp_nodelay on;

    # reduce the data that needs to be sent over network -- for testing environment
    gzip on;
    # gzip_static on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        application/atom+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

    # allow the server to close connection on non responding client, this will free up memory
    reset_timedout_connection on;

    # request timed out -- default 60
    client_body_timeout 10;

    # if client stop responding, free up memory -- default 60
    send_timeout 2;

    # server will close connection after this time -- default 75
    keepalive_timeout 30;

    # number of requests client can make over keep-alive -- for testing environment
    keepalive_requests 100000;
}

Setelah selesai Anda dapat menyimpan konfigurasi dan menjalankan perintah bawah

nginx -s reload
/etc/init.d/nginx start|restart

Jika Anda ingin menguji konfigurasi terlebih dahulu, Anda dapat menjalankannya

nginx -t
/etc/init.d/nginx configtest

Untuk masalah Alasan Keamanan dapat mematikan konfigurasi sbb:

server_tokens off;

Perlindungan sedarhana NGINX untuk DDoS

Ini jauh dari pertahanan DDoS yang aman namun dapat memperlambat beberapa DDoS kecil. Konfigurasi tersebut juga ada dalam lingkungan pengujian dan Anda harus melakukan nilai-nilai Anda.

# limit the number of connections per single IP
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

# limit the number of requests for a given session
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

# zone which we want to limit by upper values, we want limit whole server
server {
    limit_conn conn_limit_per_ip 10;
    limit_req zone=req_limit_per_ip burst=10 nodelay;
}

# if the request body size is more than the buffer size, then the entire (or partial)
# request body is written into a temporary file
client_body_buffer_size  128k;

# buffer size for reading client request header -- for testing environment
client_header_buffer_size 3m;

# maximum number and size of buffers for large headers to read from client request
large_client_header_buffers 4 256k;

# read timeout for the request body from client -- for testing environment
client_body_timeout   3m;

# how long to wait for the client to send a request header -- for testing environment
client_header_timeout 3m;

Sekarang Anda dapat melakukan tes konfigurasi lagi

nginx -t # /etc/init.d/nginx configtest

Dan kemudian muat ulang atau mulai ulang nginx Anda

nginx -s reload
/etc/init.d/nginx reload|restart

Anda dapat menguji konfigurasi ini dengan tsung dan bila Anda puas dengan hasilnya Anda dapat menekan Ctrl+C karena dapat berjalan berjam-jam.

Baca Juga:  Install atau upgrade ke PHP 8.3 di Ubuntu dan Debian

Meningkatkan Jumlah Maksimal File Terbuka (nofile limit) – Linux

Dua cara untuk menaikkan batas nofile/max open files/file descriptors/file handles untuk NGINX di RHEL/CentOS 7+. Dengan NGINX berjalan, memeriksa batas saat ini pada proses master

$ cat /proc/$(cat /var/run/nginx.pid)/limits | grep open.files
Max open files            1024                 4096                 files

Dan worker processes

ps --ppid $(cat /var/run/nginx.pid) -o %p|sed '1d'|xargs -I{} cat /proc/{}/limits|grep open.files

Max open files            1024                 4096                 files
Max open files            1024                 4096                 files

Mencoba dengan worker_rlimit_nofile di directive {,/usr/local}/etc/nginx/nginx.conf gagal karena kebijakan SELinux tidak mengizinkan setrlimit. Ini ditunjukkan di /var/log/nginx/error.log

015/07/24 12:46:40 [alert] 12066#0: setrlimit(RLIMIT_NOFILE, 2342) failed (13: Permission denied)

Dan di /var/log/audit/audit.log

type=AVC msg=audit(1437731200.211:366): avc:  denied  { setrlimit } for  pid=12066 comm="nginx" scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:httpd_t:s0 tclass=process

nolimit tanpa Systemd

# /etc/security/limits.conf
# /etc/default/nginx (ULIMIT)
$ nano /etc/security/limits.d/nginx.conf
nginx   soft    nofile  65536
nginx   hard    nofile  65536
$ sysctl -p

nolimit dengan Systemd

$ mkdir -p /etc/systemd/system/nginx.service.d
$ nano /etc/systemd/system/nginx.service.d/nginx.conf
[Service]
LimitNOFILE=30000
$ systemctl daemon-reload
$ systemctl restart nginx.service

SELinux boolean httpd_setrlimit to true(1)

Ini akan menetapkan batas fd untuk proses pekerja. Tinggalkan worker_rlimit_nofile directive in {,/usr/local}/etc/nginx/nginx.conf dan jalankan perintah berikut sebagai root

setsebool -P httpd_setrlimit 1

DoS HTTP/1.1 dan yang lebih baru: Rentang Permintaan

Secara default max_ranges tidak dibatasi. Serangan DoS dapat menyebabkan banyak Range-Request (Dampak pada stabilitas I/O).

Baca Juga:  8 Kesalahan Umum HTML yang Harus Anda Hindari untuk Pengembangan Web yang Lebih Baik

Socket Sharding di NGINX 1.9.1+ (DragonFly BSD dan Linux 3.9+)

Thread Pools di NGINX Boost Performance 9x! (Linux)

Pengiriman file multi-thread saat ini hanya didukung Linux. Tanpa batasan sendfile_max_chunk, satu koneksi cepat dapat menyita seluruh proses pekerja.

map $ssl_preread_protocol $upstream {
    ""        ssh.example.com:22;
    "TLSv1.2" new.example.com:443;
    default   tls.example.com:443;
}

# ssh and https on the same port
server {
    listen      192.168.0.1:443;
    proxy_pass  $upstream;
    ssl_preread on;
}

Tautan referensi:

– https://github.com/trimstray/nginx-admins-handbook
– https://github.com/GrrrDog/weird_proxies/wiki/nginx
– https://github.com/h5bp/server-configs-nginx
– https://github.com/leandromoreira/linux-network-performance-parameters
– https://github.com/nginx-boilerplate/nginx-boilerplate
– https://www.nginx.com/blog/thread-pools-boost-performance-9x/
– https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
– https://www.nginx.com/blog/nginx-1-13-9-http2-server-push/
– https://www.nginx.com/blog/performing-a-b-testing-nginx-plus/
– https://www.nginx.com/blog/10-tips-for-10x-application-performance/
– https://www.nginx.com/blog/http-keepalives-and-web-performance/
– https://www.nginx.com/blog/overcoming-ephemeral-port-exhaustion-nginx-plus/
– https://www.nginx.com/blog/tcp-load-balancing-udp-load-balancing-nginx-tips-tricks/
– https://www.nginx.com/blog/introducing-cicd-with-nginx-and-nginx-plus/
– https://www.nginx.com/blog/testing-the-performance-of-nginx-and-nginx-plus-web-servers/
– https://www.nginx.com/blog/smart-efficient-byte-range-caching-nginx/
– https://nginx.org/r/pcre_jit
– https://nginx.org/r/ssl_engine (openssl engine -t )
– https://www.nginx.com/blog/mitigating-ddos-attacks-with-nginx-and-nginx-plus/
– https://www.nginx.com/blog/tuning-nginx/
– https://github.com/intel/asynch_mode_nginx
– https://openresty.org/download/agentzh-nginx-tutorials-en.html
– https://www.maxcdn.com/blog/nginx-application-performance-optimization/
– https://www.nginx.com/blog/nginx-se-linux-changes-upgrading-rhel-6-6/
– https://medium.freecodecamp.org/a8afdbfde64d
– https://medium.freecodecamp.org/secure-your-web-application-with-these-http-headers-fd66e0367628
– https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88
– https://gist.github.com/denji/9130d1c95e350c58bc50e4b3a9e29bf4
– https://8gwifi.org/docs/nginx-secure.jsp
– http://www.codestance.com/tutorials-archive/nginx-tuning-for-best-performance-255
– https://ospi.fi/blog/centos-7-raise-nofile-limit-for-nginx.html
– https://www.linode.com/docs/websites/nginx/configure-nginx-for-optimized-performance
– https://haydenjames.io/nginx-tuning-tips-tls-ssl-https-ttfb-latency






Reporter: Nyoman Artawa Wiguna

Untuk konfigurasi ini Anda dapat menggunakan server web yang Anda suka, saya memutuskan, karena saya kebanyakan bekerja dengannya menggunakan nginx.

Secara umum, nginx yang dikonfigurasi dengan benar dapat menangani hingga 400K hingga 500K permintaan per detik (berkerumun), sebagian besar yang saya lihat adalah 50K hingga 80K (non-cluster) permintaan per detik dan beban CPU 30%, tentu saja, ini adalah 2 x Intel Xeon dengan HyperThreading diaktifkan, tetapi dapat bekerja tanpa masalah pada mesin yang lebih lambat.

Anda harus memahami bahwa konfigurasi ini digunakan dalam lingkungan pengujian dan bukan dalam produksi sehingga Anda perlu menemukan cara untuk mengimplementasikan sebagian besar fitur tersebut sebaik mungkin untuk server Anda.
Stable version NGINX (deb/rpm)
Mainline version NGINX (deb/rpm)

Pertama, Anda harus menginstal nginx
RHEL/Centos

yum install nginx

Debian/Ubuntu

apt install nginx

Sebelum instalasi, cadangkan konfigurasi asli Anda dan Anda dapat mulai mengkonfigurasi ulang konfigurasi Anda.
Anda perlu membuka nginx.conf di /etc/nginx/nginx.conf dengan editor favorit Anda.
Berikut konfigurasinya:

# you must set worker processes based on your CPU cores, nginx does not benefit from setting more than that
worker_processes auto; #some last versions calculate it automatically

# number of file descriptors used for nginx
# the limit for the maximum FDs on the server is usually set by the OS.
# if you don't set FD's then OS settings will be used which is by default 2000
worker_rlimit_nofile 100000;

# only log critical errors
error_log /var/log/nginx/error.log crit;

# provides the configuration file context in which the directives that affect connection processing are specified.
events {
    # determines how much clients will be served per worker
    # max clients = worker_connections * worker_processes
    # max clients is also limited by the number of socket connections available on the system (~64k)
    worker_connections 4000;

    # optimized to serve many clients with each thread, essential for linux -- for testing environment
    use epoll;

    # accept as many connections as possible, may flood worker connections if set too low -- for testing environment
    multi_accept on;
}

http {
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # to boost I/O on HDD we can disable access logs
    access_log off;

    # copies data between one FD and other from within the kernel
    # faster than read() + write()
    sendfile on;

    # send headers in one piece, it is better than sending them one by one
    tcp_nopush on;

    # don't buffer data sent, good for small data bursts in real time
    tcp_nodelay on;

    # reduce the data that needs to be sent over network -- for testing environment
    gzip on;
    # gzip_static on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        application/atom+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

    # allow the server to close connection on non responding client, this will free up memory
    reset_timedout_connection on;

    # request timed out -- default 60
    client_body_timeout 10;

    # if client stop responding, free up memory -- default 60
    send_timeout 2;

    # server will close connection after this time -- default 75
    keepalive_timeout 30;

    # number of requests client can make over keep-alive -- for testing environment
    keepalive_requests 100000;
}

Setelah selesai Anda dapat menyimpan konfigurasi dan menjalankan perintah bawah

nginx -s reload
/etc/init.d/nginx start|restart

Jika Anda ingin menguji konfigurasi terlebih dahulu, Anda dapat menjalankannya

nginx -t
/etc/init.d/nginx configtest

Untuk masalah Alasan Keamanan dapat mematikan konfigurasi sbb:

server_tokens off;

Perlindungan sedarhana NGINX untuk DDoS

Ini jauh dari pertahanan DDoS yang aman namun dapat memperlambat beberapa DDoS kecil. Konfigurasi tersebut juga ada dalam lingkungan pengujian dan Anda harus melakukan nilai-nilai Anda.

# limit the number of connections per single IP
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

# limit the number of requests for a given session
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

# zone which we want to limit by upper values, we want limit whole server
server {
    limit_conn conn_limit_per_ip 10;
    limit_req zone=req_limit_per_ip burst=10 nodelay;
}

# if the request body size is more than the buffer size, then the entire (or partial)
# request body is written into a temporary file
client_body_buffer_size  128k;

# buffer size for reading client request header -- for testing environment
client_header_buffer_size 3m;

# maximum number and size of buffers for large headers to read from client request
large_client_header_buffers 4 256k;

# read timeout for the request body from client -- for testing environment
client_body_timeout   3m;

# how long to wait for the client to send a request header -- for testing environment
client_header_timeout 3m;

Sekarang Anda dapat melakukan tes konfigurasi lagi

nginx -t # /etc/init.d/nginx configtest

Dan kemudian muat ulang atau mulai ulang nginx Anda

nginx -s reload
/etc/init.d/nginx reload|restart

Anda dapat menguji konfigurasi ini dengan tsung dan bila Anda puas dengan hasilnya Anda dapat menekan Ctrl+C karena dapat berjalan berjam-jam.

Baca Juga:  Temukan Fitur Terbaru di PHP 8.3

Meningkatkan Jumlah Maksimal File Terbuka (nofile limit) – Linux

Dua cara untuk menaikkan batas nofile/max open files/file descriptors/file handles untuk NGINX di RHEL/CentOS 7+. Dengan NGINX berjalan, memeriksa batas saat ini pada proses master

$ cat /proc/$(cat /var/run/nginx.pid)/limits | grep open.files
Max open files            1024                 4096                 files

Dan worker processes

ps --ppid $(cat /var/run/nginx.pid) -o %p|sed '1d'|xargs -I{} cat /proc/{}/limits|grep open.files

Max open files            1024                 4096                 files
Max open files            1024                 4096                 files

Mencoba dengan worker_rlimit_nofile di directive {,/usr/local}/etc/nginx/nginx.conf gagal karena kebijakan SELinux tidak mengizinkan setrlimit. Ini ditunjukkan di /var/log/nginx/error.log

015/07/24 12:46:40 [alert] 12066#0: setrlimit(RLIMIT_NOFILE, 2342) failed (13: Permission denied)

Dan di /var/log/audit/audit.log

type=AVC msg=audit(1437731200.211:366): avc:  denied  { setrlimit } for  pid=12066 comm="nginx" scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:httpd_t:s0 tclass=process

nolimit tanpa Systemd

# /etc/security/limits.conf
# /etc/default/nginx (ULIMIT)
$ nano /etc/security/limits.d/nginx.conf
nginx   soft    nofile  65536
nginx   hard    nofile  65536
$ sysctl -p

nolimit dengan Systemd

$ mkdir -p /etc/systemd/system/nginx.service.d
$ nano /etc/systemd/system/nginx.service.d/nginx.conf
[Service]
LimitNOFILE=30000
$ systemctl daemon-reload
$ systemctl restart nginx.service

SELinux boolean httpd_setrlimit to true(1)

Ini akan menetapkan batas fd untuk proses pekerja. Tinggalkan worker_rlimit_nofile directive in {,/usr/local}/etc/nginx/nginx.conf dan jalankan perintah berikut sebagai root

setsebool -P httpd_setrlimit 1

DoS HTTP/1.1 dan yang lebih baru: Rentang Permintaan

Secara default max_ranges tidak dibatasi. Serangan DoS dapat menyebabkan banyak Range-Request (Dampak pada stabilitas I/O).

Baca Juga:  Bangun Situs Doc Dengan Next.js Menggunakan Nextra

Socket Sharding di NGINX 1.9.1+ (DragonFly BSD dan Linux 3.9+)

Thread Pools di NGINX Boost Performance 9x! (Linux)

Pengiriman file multi-thread saat ini hanya didukung Linux. Tanpa batasan sendfile_max_chunk, satu koneksi cepat dapat menyita seluruh proses pekerja.

map $ssl_preread_protocol $upstream {
    ""        ssh.example.com:22;
    "TLSv1.2" new.example.com:443;
    default   tls.example.com:443;
}

# ssh and https on the same port
server {
    listen      192.168.0.1:443;
    proxy_pass  $upstream;
    ssl_preread on;
}

Tautan referensi:

– https://github.com/trimstray/nginx-admins-handbook
– https://github.com/GrrrDog/weird_proxies/wiki/nginx
– https://github.com/h5bp/server-configs-nginx
– https://github.com/leandromoreira/linux-network-performance-parameters
– https://github.com/nginx-boilerplate/nginx-boilerplate
– https://www.nginx.com/blog/thread-pools-boost-performance-9x/
– https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
– https://www.nginx.com/blog/nginx-1-13-9-http2-server-push/
– https://www.nginx.com/blog/performing-a-b-testing-nginx-plus/
– https://www.nginx.com/blog/10-tips-for-10x-application-performance/
– https://www.nginx.com/blog/http-keepalives-and-web-performance/
– https://www.nginx.com/blog/overcoming-ephemeral-port-exhaustion-nginx-plus/
– https://www.nginx.com/blog/tcp-load-balancing-udp-load-balancing-nginx-tips-tricks/
– https://www.nginx.com/blog/introducing-cicd-with-nginx-and-nginx-plus/
– https://www.nginx.com/blog/testing-the-performance-of-nginx-and-nginx-plus-web-servers/
– https://www.nginx.com/blog/smart-efficient-byte-range-caching-nginx/
– https://nginx.org/r/pcre_jit
– https://nginx.org/r/ssl_engine (openssl engine -t )
– https://www.nginx.com/blog/mitigating-ddos-attacks-with-nginx-and-nginx-plus/
– https://www.nginx.com/blog/tuning-nginx/
– https://github.com/intel/asynch_mode_nginx
– https://openresty.org/download/agentzh-nginx-tutorials-en.html
– https://www.maxcdn.com/blog/nginx-application-performance-optimization/
– https://www.nginx.com/blog/nginx-se-linux-changes-upgrading-rhel-6-6/
– https://medium.freecodecamp.org/a8afdbfde64d
– https://medium.freecodecamp.org/secure-your-web-application-with-these-http-headers-fd66e0367628
– https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88
– https://gist.github.com/denji/9130d1c95e350c58bc50e4b3a9e29bf4
– https://8gwifi.org/docs/nginx-secure.jsp
– http://www.codestance.com/tutorials-archive/nginx-tuning-for-best-performance-255
– https://ospi.fi/blog/centos-7-raise-nofile-limit-for-nginx.html
– https://www.linode.com/docs/websites/nginx/configure-nginx-for-optimized-performance
– https://haydenjames.io/nginx-tuning-tips-tls-ssl-https-ttfb-latency






Reporter: Nyoman Artawa Wiguna

Untuk mendapatkan Berita & Review menarik Saksenengku Network
Google News

Artikel Terkait

Populer

Artikel Terbaru