19
http://nginx.org/ Basic Configurations John Kim ([email protected])

Nginx basic configurations

Embed Size (px)

Citation preview

http://nginx.org/

Basic Configurations

John Kim ([email protected])

Kiril Georgiev played 360 people simultaneously in Sofia, Bulgaria. His final score was 284 wins, 70 draws and 6 losses.

• Multiple protocol support (HTTP, HTTPS, WebSocket, IMAP, POP3, SMTP)• SSL termination (TLSv1.1/TLSv1.2/SSL/SNI/PFS/PCI-DSS and OCSP Stapling)• HTTP video streaming using MP4/FLV/HDS/HLS• Caching static & dynamic content• Content compression• Header manipulation• Request filtering• Extended monitoring and logging• Upgrades without downtime using live binaries• Graceful restart with non-stop request processing• Complete reverse proxy and load balancer

$ sudo yum install epel-release$ sudo yum install epel-release$ sudo yum -y install nginx

$ nginx -hnginx version: nginx/1.0.15Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options: -?,-h : this help -v : show version and exit -V : show version and configure options then exit -t : test configuration and exit -q : suppress non-error messages during configuration testing -s signal : send signal to a master process: stop, quit, reopen, reload -p prefix : set prefix path (default: /usr/share/nginx/) -c filename : set configuration file (default: /etc/nginx/nginx.conf) -g directives : set global directives out of configuration file

$ sudo nginx

NGINX 설치(직접 컴파일 해야 하는 경우는 http://nginx.org/en/docs/configure.html)

INSTALL NGINX

$ pwd/etc/nginx$ tree.|-- conf.d| |-- default.conf| |-- ssl.conf| `-- virtual.conf|-- default.d|-- fastcgi.conf|-- fastcgi.conf.default|-- fastcgi_params|-- fastcgi_params.default|-- koi-utf|-- koi-win|-- mime.types|-- mime.types.default|-- nginx.conf|-- nginx.conf.default|-- scgi_params|-- scgi_params.default|-- uwsgi_params|-- uwsgi_params.default`-- win-utf

설치 후 파일 구조user nginx;worker_processes 1;

error_log /var/log/nginx/error.log;pid /var/run/nginx.pid;

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;

sendfile on; keepalive_timeout 65;

include /etc/nginx/conf.d/*.conf;

}

/etc/nginx/nginx.conf

NESTED CONFIGURATION

server { listen 80 default_server; server_name _;

access_log logs/host.access.log main;

# Load configuration files for the default server block. include /etc/nginx/default.d/*.conf;

location / { root /usr/share/nginx/html; index index.html index.htm; }

error_page 404 /404.html; location = /404.html { root /usr/share/nginx/html; }

error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; }

}

/etc/nginx/nginx.conf

[ . . . . . . ]

http {

[ . . . . . . ]

include /etc/nginx/conf.d/*.conf;

}

/etc/nginx/conf.d/default.conf

HTTP SECTION SERVER SECTION

DIRECTIVE

NESTED CONFIGURATION

WORKER PROCESS

MASTER PROCESS

WORKER PROCESS

WORKER PROCESS

WORKER PROCESS

root 32475 1 0 13:36 ? 00:00:00 nginx: master process /usr/sbin/nginx nginx 32476 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32477 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32479 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32480 32475 0 13:36 ? 00:00:00 \_ nginx: worker process

worker_processes 4;events { worker_connections 2048;}

( Total worker connections : 4 x 2048 )

PROCESSES

WORKER PROCESS

MASTER PROCESS

WORKER PROCESS

WORKER PROCESS

WORKER PROCESS

root 32475 1 0 13:36 ? 00:00:00 nginx: master process /usr/sbin/nginx nginx 32476 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32477 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32479 32475 0 13:36 ? 00:00:00 \_ nginx: worker process nginx 32480 32475 0 13:36 ? 00:00:00 \_ nginx: worker processnginx 32481 32475 0 13:36 ? 00:00:00 \_ nginx: cache manager process nginx 32482 32475 0 13:36 ? 00:00:00 \_ nginx: cache loader process

CACHE MANAGER

CACHE LOADER

PROCESSES

TERM, INT fast shutdown

QUIT graceful shutdown

HUP

changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes

USR1 re-opening log files

USR2 upgrading an executable file

WINCH graceful shutdown of worker processes

$ sudo nginx -s [OPTION]

stop — fast shutdownquit — graceful shutdownreload — reloading the configuration filereopen — reopening the log files

$ sudo kill -HUP `cat /var/run/nginx.pid` $ sudo nginx -s reload

SIGNALS

PID PPID USER %CPU VSZ WCHAN COMMAND33126 1 root 0.0 1148 pause nginx: master process33127 33126 nobody 0.0 1380 kqread nginx: worker process (nginx)33128 33126 nobody 0.0 1364 kqread nginx: worker process (nginx)33129 33126 nobody 0.0 1364 kqread nginx: worker process (nginx)33130 33126 nobody 0.0 1364 kqread nginx: worker process (nginx)

PID PPID USER %CPU VSZ WCHAN COMMAND33126 1 root 0.0 1164 pause nginx: master process33130 33126 nobody 0.0 1380 kqread nginx: worker process is shutting down (nginx)33135 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33137 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33138 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)

PID PPID USER %CPU VSZ WCHAN COMMAND33126 1 root 0.0 1164 pause nginx: master process33135 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33137 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)33138 33126 nobody 0.0 1368 kqread nginx: worker process (nginx)

BEFORE RELOAD

AFTER RELOAD

RELOADING

RELOAD NEW CONFIGURATION WITH NO DOWNTIME

RELOAD NEW BINARY WITH NO DOWNTIME

CUSTOMIZED CONFIGURATION

Worker Process

worker_processes 2;

events { worker_connections 65536; use epoll; multi_accept on;}

/etc/nginx/nginx.conf

1

23

4

worker_process 는 Event Looping Single Thread 로 일반적으로 CPU Core 수에 맞게 설정한다.또는, worker_processes auto; 하여 자동으로 Core 수에 맞게 실행되도록 할 수 있다.

$ grep ^processor /proc/cpuinfo | wc -lCore 수 확인은 아래와 같이 함.

1

3 epoll 방식은 Kernel 에 의존하여 file descriptor 중 변화가 있는(이벤트 감지) 신호를 받아 처리 하는 방식으로 대용량 트래픽 처리에 적합하다.

2 worker process 별로 최대 연결할 수 있는 수이며, $ ulimit -n 로 file descriptor 수를 확인하여 같거자 작은 값으로 설정해야 한다.worker_connections = inbound 연결수 + 연결 대기 수 + outbound 수(proxy 대상인 upstream servers)

4 work process 가 동시에 file descriptor 를 처리 할 수 있도록 하는 옵션이다.

HTTP section

http {

keepalive_timeout 65;keepalive_requests 100000;

sendfile on;

tcp_nopush on;

tcp_nodelay on;

}

/etc/nginx/nginx.conf

1

2

3

4

1

4

keepalive_timeout 은 TCP 연결 timeout (default: 75s) 이다.keepalive_requests 는 하나의 Connection 에서 처리 할 수 있는 최대 request 수 (default : 100) 이다.

2

3 tcp_nopush on 은 sendfile on 일때만 동작하며, 소켓 옵션 중 TCP_CORK 를 사용하여 HTTP Header 를 하나의 소켓으로 전송한다.

sendfile (default : off) 을 on 하게 되면, 이미지나 비디오 같은 static 파일을 multi thread 로 보내도록 한다. 주로 이미지를 전송하게 되는 경우 사용한다.

tcp_nopush on 과 함께 사용하며, Client 로 부터의 ACK 를 최소화 하여 지연을 줄이는 방식이다.

HTTP section

http {

client_body_buffer_size 128k;client_max_body_size 10m;

client_header_buffer_size 1k;

}

/etc/nginx/nginx.conf

1

2

1 client_body_buffer_size (Default 8k(32Bit) / 16k(64Bit)) 는 POST 로 전송되는 payload 사이즈이며 일반적으로 128k 가 적당하다. 초과 할 경우 temp 파일이 생성되어 속도 저하가 발생한다.client_max_body_size (Default: 1m) 는 최대 사이즈이며 초과 할 경우 413 (Request Entity Too Large)를 반환한다.

2client_header_buffer_size (default : 1k) header 사이즈며 대부분 1k 면 충분하다. 하지만 Cookie 가 상당히 많은 경우는 이를 조정할 필요가 있다. on 하게 되면, 이미지나 비디오 같은 static 파일을 multi thread 로 보내도록 한다. 주로 이미지를 전송하게 되는 경우 사용한다.

Kernel Network Configuration

net.core.somaxconn = 65536

net.ipv4.tcp_max_tw_buckets = 1440000

/etc/sysctl.conf

1

2

1 net.core.somaxconn 는 socket max connection을 의미하며, 커널이 최대 연결 가능한 소캣 수이다. 일반적으로 $ ulimit -n 에서 나오는 File Descriptor 와 일치 시킨다.현재 설정 값은 $ cat /proc/sys/net/core/somaxconn 로 확인이 가능하다.

2 net.ipv4.tcp_max_tw_buckets 는 동시에 발생하는 timewait socket 수의 최대 값을 지정하는 것으로, 이를 초과 하면 socket 을 제거 된다.현재 설정 값은 $ cat cat /proc/sys/net/ipv4/tcp_max_tw_buckets 로 확인이 가능하다.

Compression

http {

server {

gzip on;gzip_min_length 1000;gzip_types: text/html text/javascript text/plain text/xml application/xml;gzip_disable "MSIE [1-6]\.”;

}

}

/etc/nginx/nginx.conf

gzip on (default: off) 으로 응답 결과를 압축하도록 설정한다.gzip_min_length (default: 20) 로 응답 사이즈의 최소값을 지정한다. 단위는 bytes.gzip_types (default: text/html) 으로 MIME 타입을 지정하고 해당하는 MIME 타입인 경우에만 압축하도록 한다.gzip_disable 요청 해더의 “User-Agent” 가 지정한 경우와 일치하는 경우 압축하지 않도록 한다.

location / {

gzip on;gzip_proxied any;gzip_types image/gif text/css application/javascript;gzip_vary on;gzip_disable "MSIE [1-6]\.(?!.*SV1)";

proxy_cache static_cache; proxy_cache_revalidate on; proxy_cache_min_uses 3; proxy_cache_lock on;

proxy_pass http://image.gsshop.com; }

http://nonsecurityserver.comhttps://turn.stalk.com https request

proxy

upstream server

gzip compress response Cache Storage

SAMPLE (SSL CDN Proxy Server)

proxy_cache_path /data/cache levels=1:2 keys_zone=static_cache:10m max_size=10g inactive=60m use_temp_path=off;

server { listen 80; server_name turn.stalk.io; return 301 https://$host$request_uri;}

server { listen 443 ssl; server_name turn.stalk.io; root /usr/share/nginx/html;

add_header Strict-Transport-Security "max-age=31536000; includeSubdomains"; add_header X-Frame-Options DENY;

ssl on; ssl_certificate /etc/letsencrypt/live/turn.stalk.io/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/turn.stalk.io/privkey.pem; ssl_stapling on; ssl_stapling_verify on; ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';

ssl_dhparam /etc/nginx/conf.d/dhparam.pem; ssl_prefer_server_ciphers on; ssl_session_timeout 1d; ssl_session_cache shared:SSL:10m;

access_log /var/log/nginx/turn.stalk.io.access.log; error_log /var/log/nginx/turn.stalk.io.error.log warn;

# 다음 장 계속 #

SAMPLE (SSL CDN Proxy Server)/etc/nginx/conf.d/default.conf 전체 내용

# 앞장 계속 #

location / {

gzip on; gzip_proxied any; gzip_types image/gif application/javascript text/plain text/xml text/css application/x-javascript; gzip_vary on; gzip_disable "MSIE [1-6]\.(?!.*SV1)";

proxy_cache static_cache; proxy_cache_revalidate on; proxy_cache_min_uses 3; proxy_cache_lock on;

proxy_pass http://nonsecurityserver.com; }

# Block dot file (.htaccess .htpasswd .svn .git .env and so on.) location ~ /\. { deny all; }

location = /favicon.ico { log_not_found off; access_log off; }

location = /robots.txt { allow all; log_not_found off; access_log off; }

}

SAMPLE (SSL CDN Proxy Server)/etc/nginx/conf.d/default.conf 전체 내용