17.06.2012 09:02
OlegON
 
Чтобы определиться сразу, речь идет об обычной машинке, без RAID, i5, 8Гб памяти, 20МБит наружу.
Сначала просто вобью параметры, потом снабжу их комментариями. Данная конфигурация - результат настроек и чтения доков и рекомендаций достаточно длительного времени сбора. Убедительная просьба оставлять свои замечания.
Во-первых, необходимо настроить саму систему, т.е. sysctl.conf
Код:
kernel.panic = 3
vm.swappiness = 1
net.ipv4.tcp_low_latency = 0
net.ipv4.ip_forward = 1
net.ipv4.tcp_orphan_retries = 2
net.core.somaxconn = 10000
net.core.netdev_max_backlog = 10000
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1
net.core.rmem_max = 12582912
net.core.wmem_max = 12582912
net.ipv4.tcp_rmem = 4096 87380 2115424
net.ipv4.tcp_wmem = 4096 87380 2115424
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.netfilter.ip_conntrack_max = 2097152
kernel.sem = 1250 256000 100 1024
vm.overcommit_memory = 1
fs.file-max = 262144
vm.vfs_cache_pressure = 100
vm.dirty_background_ratio = 70
vm.dirty_ratio = 70
vm.dirty_writeback_centisecs = 180000
vm.dirty_expire_centisecs = 180000
Далее пример nginx.conf
Код:
user nginx nginx;
worker_processes 4;
timer_resolution 100ms;
worker_priority -5;


error_log /var/log/nginx/error_log warn;

events {
	worker_connections 1024;
	use epoll;
}

http {
	include /etc/nginx/mime.types;
	default_type application/octet-stream;
	charset utf-8;
	fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=cache:200m inactive=2d max_size=2G;
	log_format main
		'$remote_addr $time_local '
		'"$http_referer" "$request" $status $bytes_sent '
		'"$http_user_agent" '
		'$upstream_response_time "$host"';
	server_tokens off; 
	client_header_timeout 60;
	client_body_timeout 60;
	send_timeout 10m;
	keepalive_timeout 60 60;

	connection_pool_size 512;
	client_header_buffer_size 8k;
	client_body_buffer_size 8k;
	client_max_body_size 200M;
	large_client_header_buffers 10 16k;
	fastcgi_buffers 20 8k;
	fastcgi_max_temp_file_size 0;
	request_pool_size 128k;
	server_names_hash_bucket_size 128;

	gzip on;
	gzip_min_length 2k;
	gzip_buffers 16 16k;
	gzip_types text/plain text/css image/x-icon application/x-perl application/x-httpd-cgi text/xml application/xml application/xml+rss text/javascript application/json application/x-javascript;
	gzip_comp_level 6;
	gzip_disable "MSIE [1-6]\.";
	gzip_vary on;

	output_buffers 16 128k;
	postpone_output 1460;

	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	reset_timedout_connection on;

	ignore_invalid_headers on;

	server {
	server_name www.olegon.ru supermag.olegon.ru bi.olegon.ru olegon.no-ip.org broadband-77-37-240-57.nationalcablenetworks.ru 77.37.240.57;
	rewrite ^ https://olegon.ru$request_uri? permanent;
	}

	server {
	listen 80 default;
	server_name olegon.ru;
	access_log /var/log/nginx/access_log main;

	fastcgi_cache_key $document_root$request_uri;

	fastcgi_cache_min_uses 1;
	fastcgi_cache_valid any 1m;
	fastcgi_cache_use_stale updating error timeout invalid_header http_500;
	fastcgi_cache cache;
	fastcgi_max_temp_file_size 0;
	fastcgi_read_timeout 300;
	fastcgi_connect_timeout 300;

	rewrite ^/forum/(.*).htm$ /link/fullurl.php?u=$1?  last;
	rewrite ^/forum/(.*)$ /$1 redirect;
	rewrite ^/(ora|ORA)-([0-9]*)\.htm$ /ora/index.php?err=$2?  last;
	rewrite ^/a/(.*)$ /pr/checkurl.php?urlo=$1?  last;
	rewrite ^/archive/index.php/(.*)$ /archive/index.php?$1?  last;
	rewrite ^/anony/mjpg.cgi /pr/camera.html last;
	rewrite ^/supermag2000.htm /forumdisplay.php?f=14 last;
	rewrite ^/supermag_plus.htm /forumdisplay.php?f=14 last;
	rewrite ^/optimizer.htm /showthread.php?t=7196 last;
	rewrite ^/sitemap_(.*)\.xml\.gz?$ /vbseo_sitemap/data/sitemap_$1.xml.gz last;
	rewrite ^/squares.html /squares.php last;
	rewrite ^/squares_for_stupid.html /squares_for_stupid.php last;
	rewrite ^/squares_for_idiots.html /squares_for_idiots.php last;
	if ($http_user_agent !~ FeedBurner) {
	rewrite ^/external.php$ http://feeds.feedburner.com/olegon/xnAG? last;
	rewrite ^/yarss.php$ http://feeds.feedburner.com/olegon/xnAG? last;
	}
	root /var/;
	index index.htm index.html index.php;
	error_page    404 = ;
	location ~ /\.ht {
	deny all;
	}
	location ~ /jabber/ {
	root /var/;
	autoindex on;
	expires 1m;
	deny 194.154.87.0/24;
	}
	location ~ /stat/ {
	add_header Cache-Control public;
	expires 1h;
	}
	location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|swf|html|htm)$ {
	index index.html index.php;
	add_header Cache-Control public;
	access_log off;
	open_file_cache max=1024 inactive=3600s;
	open_file_cache_valid 2000s;
	open_file_cache_min_uses 1;
	open_file_cache_errors on;
	expires max;
	}

	location ~ ^/squidstat/.*\.cgi$ {
	gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped
	fastcgi_pass  unix:/var/run/cgiwrap-dispatch.sock;
	fastcgi_index index.cgi;
	fastcgi_param SCRIPT_FILENAME /var/$fastcgi_script_name;
	fastcgi_param QUERY_STRING     $query_string;
	fastcgi_param REQUEST_METHOD   $request_method;
	fastcgi_param CONTENT_TYPE     $content_type;
	fastcgi_param CONTENT_LENGTH   $content_length;
	fastcgi_param GATEWAY_INTERFACE  CGI/1.1;
	fastcgi_param SERVER_SOFTWARE    nginx;
	fastcgi_param SCRIPT_NAME        $fastcgi_script_name;
	fastcgi_param REQUEST_URI        $request_uri;
	fastcgi_param DOCUMENT_URI       $document_uri;
	fastcgi_param DOCUMENT_ROOT      $document_root;
	fastcgi_param SERVER_PROTOCOL    $server_protocol;
	fastcgi_param REMOTE_ADDR        $remote_addr;
	fastcgi_param REMOTE_PORT        $remote_port;
	fastcgi_param SERVER_ADDR        $server_addr;
	fastcgi_param SERVER_PORT        $server_port;
        fastcgi_param SERVER_NAME        $server_name;
	allow 10.10.0.0/24;
	allow 77.37.240.57/32;
	deny all;
	expires 1m;
	}

	location ~ /(ora-|ORA-|link/|forum/|ora/|/pr) {
	rewrite ^/(ora|ORA)-([0-9]*)$ /oracle/index.php?err=$2?  last;
	fastcgi_ignore_headers "Expires" "Cache-control";
	fastcgi_buffer_size 8k;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	fastcgi_hide_header "Set-Cookie";
	expires max;
	}
	location ~ /(image\.php|tags\.php|calendar\.php) {
	fastcgi_ignore_headers Expires;
	fastcgi_buffer_size 8k;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	fastcgi_hide_header "Set-Cookie";
	expires 1d;
	}
	location ~ /admincp/ {
	auth_basic "Admin Zone";
	auth_basic_user_file /var/admincp/.htpasswd;
	fastcgi_ignore_headers Expires;
	fastcgi_buffer_size 8k;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	fastcgi_hide_header "Set-Cookie";
	expires 1m;
	}
	location ~ /modcp/ {
	auth_basic "Moderator Zone";
	auth_basic_user_file /var/modcp/.htpasswd;
	fastcgi_ignore_headers Expires;
	fastcgi_buffer_size 8k;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	fastcgi_hide_header "Set-Cookie";
	expires 1m;
	}
	location ~ /(online\.php|search\.php|register\.php|st\.php|opt\.php) {
	fastcgi_ignore_headers Expires;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	expires 1m;
	}
	location ~* php$ {
	fastcgi_buffer_size 8k;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	}
	} 

	server {
	listen 80;
	server_name stats.olegon.ru;
	location / {
	proxy_pass         http://127.0.0.1:10002/;
	proxy_redirect     off;
	proxy_set_header   Host             $host;
	proxy_set_header   X-Real-IP        $remote_addr;
	proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
	}
	}

	server {
	listen 80;
	server_name storage.olegon.ru;
	access_log /var/log/nginx/access_log;
	location ~ /\.ht {
	deny all;
	}
	location / {
	location ~ \.php$ {
	fastcgi_ignore_headers "X-Accel-Redirect" "X-Accel-Expires" "Expires" "Cache-Control" "Set-Cookie";
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	expires 10m;
	}
	root /var/storage/;
	index index.html index.php;
	expires 10m;
	}
	}

	server {
	listen 80;
	server_name zakrit.olegon.ru;
	auth_basic "Green Zone";
	auth_basic_user_file /var/zakrit/.htpasswd;
	access_log /var/log/nginx/access_log;
	location ~ /\.ht {
	deny all;
	}
	location / {
	location ~ \.php$ {
	fastcgi_ignore_headers "X-Accel-Redirect" "X-Accel-Expires" "Expires" "Cache-Control" "Set-Cookie";
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	expires 10m;
	}
	root /var/htdocs/zakrit/;
	index index.html index.php;
	expires 10m;
	}
	}

	server {
	listen 80;
	server_name comagency.olegon.ru comagency.ru www.comagency.ru;
	access_log /var/log/nginx/access_log;
	location ~ /\.ht {
	deny all;
	}
	location / {
	location ~ \.php$ {
	fastcgi_ignore_headers Expires;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	expires 1m;
	}
	root /var/com/;
	index index.html index.php;
	rewrite ^/index.php/(.*)$ /index.php?$1?  last;
	expires max;
	}
	}

	server {
	listen 80;
	server_name oleg.olegon.ru;
	access_log /var/log/nginx/access_log;
	location ~ /\.ht {
	deny all;
	}
	location / {
	location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|swf|html|htm)$ {
	add_header Cache-Control public;
	access_log off;
	open_file_cache max=1024 inactive=3600s;
	open_file_cache_valid 2000s;
	open_file_cache_min_uses 1;
	open_file_cache_errors on;
	expires max;
	}
	location ~ \.php$ {
	fastcgi_ignore_headers Expires;
	fastcgi_pass    unix:/var/run/php/fcgi-php.sock;
	fastcgi_index   index.php;
	fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
	include         fastcgi_params;
	expires 1m;
	}
	root /var/;
	error_page    404 = ;
	index index.html index.php;
	rewrite ^/index.php/(.*)$ /index.php?$1?  last;
	expires max;
	}
	}
}
все пути, кроме стандартных, я посбивал на всякий, некоторые секции вообще пришлось выкинуть. Но если что-то пропущенное из непубличного обнаружите - прошу сообщить.
Приведу и относящееся к этому содержимое /etc/security/limits.conf
Код:
*            soft    nofile          10000
*            hard    nofile          30000
05.12.2012 13:49
OlegON
 
кстати, конвертер .htaccess в правила nginx тут:
11.03.2013 17:08
OlegON
 
Сборник наиболее часто встречающихся ошибок конфигурации nginx
16.11.2015 14:56
OlegON
 
Много воды утекло с тех пор, ядра поменялись...
Вот, текущие настройки.
Код:
kernel.panic = 3
net.ipv4.ip_forward = 1
net.core.somaxconn = 32768
net.core.netdev_max_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 1024000
net.ipv4.tcp_max_syn_backlog = 32768
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_slow_start_after_idle = 0
fs.file-max = 262144
kernel.shmall = 6231459840
kernel.shmmax = 2077153280
kernel.msgmax = 1024
kernel.msgmnb = 2048
kernel.msgmni = 8192
vm.dirty_background_bytes = 134217728
vm.dirty_bytes = 268435456
vm.vfs_cache_pressure = 10
nginx.conf тоже претерпел изменения.
Во-первых, порекомендую еще в ядре отключить transparent hugepages. Либо при загрузке передать параметр тем, кто не собирает ядро сам.
Во-вторых, современное ядро достаточно грамотно автонастраивает буфера, поэтому, если вы не занимаетесь стримингом и не хостите гигабайтные файлы, всяческие rmem и wmem трогать не нужно.

Аналогичным образом не следует задирать в высокие значения буферов и nginx. Не забываем, что многие буферы выделяются при каждом подключении, помимо раздачи лишней памяти непонятно на что, сам процесс выделения большего количества памяти занимает больше времени, как и оперирование ею. Более того, чисто визуально сайт работает медленнее при шустром соединении и большом буфере. Нет смысла сначала наполнять буферы, а потом передавать их пользователю, если это наполнение мелкое, зато часто происходит. Отклик сайта на быстром канале значительно ускоряется, если буфер маленький и практически сразу выплевывает данные клиенту.

Однако, нельзя забывать, что нагрузка веб-сервера отличается от десктопной, поэтому значения по умолчанию, например, по количеству открытых файлов, количеству соединений и их ожиданию лучше изменить.

Вот такая вот религия у меня по настройкам в данный момент :) Конечно же, все это подтверждается многократным тестированием на протяжении значимого количества времени.
08.02.2021 10:59
OlegON
 
Чтобы не переписывать изменения, я просто сделал линк на текущий конфиг, который теперь может посмотреть любой
https://olegon.ru/sysctl.txt
27.11.2023 12:04
OlegON
 
Кстати, на одном саммите рекомендовали при настройке ядра под веб-сервер обращать на следующие параметры:

Memory management:
swappiness
vfs_cache_pressure
dirty_ratio
min_slab_ratio
min_unmapped_ratio

Networking:
tcp_reordering
tcp_limit_output_bytes
tcp_notsent_lowat
tcp_min_tso_segs

CPU:
sched_latency_ns
sched_min_granularity_ns
sched_wakeup_granularity_ns

IO:
fifo_batch
read_expire
write_expire
writes_starved

пока многие даже не знаю, что обозначают, но, думаю, повод присмотреться есть.
27.11.2023 12:44
OlegON
 
Цитата:
OlegON min_slab_ratio
Following the path of SLOB, Linux's SLAB memory allocator is now officially deprecated beginning with the Linux 6.5 kernel series.
Многие другие параметры тоже отсутствуют в моем 6.5 ядре
Часовой пояс GMT +3, время: 01:29.

Форум на базе vBulletin®
Copyright © Jelsoft Enterprises Ltd.
В случае заимствования информации гипертекстовая индексируемая ссылка на Форум обязательна.