SlideShare a Scribd company logo
http://nginx.org/
Basic Configurations
John Kim (yohany@gmail.com)
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 -h
nginx version: nginx/1.0.15
Usage: 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 process
nginx 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 shutdown
quit — graceful shutdown
reload — reloading the configuration file
reopen — reopening the log files
$ sudo kill -HUP `cat /var/run/nginx.pid` $ sudo nginx -s reload
SIGNALS
PID PPID USER %CPU VSZ WCHAN COMMAND
33126 1 root 0.0 1148 pause nginx: master process
33127 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 COMMAND
33126 1 root 0.0 1164 pause nginx: master process
33130 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 COMMAND
33126 1 root 0.0 1164 pause nginx: master process
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)
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
2
3
4
worker_process 는 Event Looping Single Thread 로 일반적으로 CPU Core 수에 맞게 설정한다.
또는, worker_processes auto; 하여 자동으로 Core 수에 맞게 실행되도록 할 수 있다.
$ grep ^processor /proc/cpuinfo | wc -l
Core 수 확인은 아래와 같이 함.
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)를 반환한다.
2
client_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 전체 내용

More Related Content

PDF
[오픈소스컨설팅] SELinux : Stop Disabling SELinux
PDF
vert.x 를 활용한 분산서버 개발하기
PDF
[H3 2012] 내컴에선 잘되던데? - vagrant로 서버와 동일한 개발환경 꾸미기
PPTX
PHP를 위한 NginX(엔진엑스) 시작과 설정
PDF
[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick Guide
PDF
20141229 dklee docker
PDF
Puppet과 자동화된 시스템 관리
PDF
[Hello world 오픈세미나]vertx&socket io
[오픈소스컨설팅] SELinux : Stop Disabling SELinux
vert.x 를 활용한 분산서버 개발하기
[H3 2012] 내컴에선 잘되던데? - vagrant로 서버와 동일한 개발환경 꾸미기
PHP를 위한 NginX(엔진엑스) 시작과 설정
[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick Guide
20141229 dklee docker
Puppet과 자동화된 시스템 관리
[Hello world 오픈세미나]vertx&socket io

What's hot (20)

PDF
Kafka slideshare
PDF
Hyperledger fabric practice(pdf)
PDF
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
PDF
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
PDF
[오픈소스컨설팅]Nginx jboss 연동가이드__v1
PDF
Openstack Instance Resize
PDF
Scouter와 influx db – grafana 연동 가이드
PDF
채팅서버의 부하 분산 사례
PDF
Play node conference
PDF
Hyperledger Fabric practice (v2.0)
PPTX
.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현
PDF
[오픈소스컨설팅]쿠버네티스를 활용한 개발환경 구축
PDF
[오픈소스컨설팅]Docker on Kubernetes v1
PDF
[1A7]Ansible의이해와활용
PDF
113 deview2013 varnish-day1_track1_session3_1013
PDF
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
PDF
[OpenInfra Days Korea 2018] Day 2 - E5: Mesos to Kubernetes, Cloud Native 서비스...
PPTX
Welcome to keystone the open stack identity service_v1.0.0-20141208-1212
PDF
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
PDF
resource on openstack
Kafka slideshare
Hyperledger fabric practice(pdf)
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
[오픈소스컨설팅] Docker를 활용한 Gitlab CI/CD 구성 테스트
[오픈소스컨설팅]Nginx jboss 연동가이드__v1
Openstack Instance Resize
Scouter와 influx db – grafana 연동 가이드
채팅서버의 부하 분산 사례
Play node conference
Hyperledger Fabric practice (v2.0)
.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현
[오픈소스컨설팅]쿠버네티스를 활용한 개발환경 구축
[오픈소스컨설팅]Docker on Kubernetes v1
[1A7]Ansible의이해와활용
113 deview2013 varnish-day1_track1_session3_1013
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
[OpenInfra Days Korea 2018] Day 2 - E5: Mesos to Kubernetes, Cloud Native 서비스...
Welcome to keystone the open stack identity service_v1.0.0-20141208-1212
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
resource on openstack
Ad

Viewers also liked (20)

PDF
실시간 서비스 플랫폼 개발 사례
PDF
WebRTC 현재와 미래 최진호 2016
PPTX
게임 분산 서버 구조
PDF
7가지 동시성 모델 람다아키텍처
PPT
What is web rtc
PPTX
Skates seminar 2 michael plummer
PPTX
Session 3 collectors-and-collecting
PDF
KG패스원 5월 패밀리데이
PPSX
Ma.candelaria parés
PDF
[2013년 11월] KG패스원 패밀리데이 사진첩
PPTX
Presentation for media
PDF
Demons - Storyboard
PDF
Mofuse mobile web
PPTX
Potential Treatment for ALS and Frontotemporal Dementia Discovered
PPTX
Best Cellulite Removal
PPTX
Tipos y beneficios de las herramientas web 2.0 en la gerencia educativa
PPT
Evaluation question 2
PPTX
Session 2 art-backed-financial-products
PDF
Storyboard - Demons
PPTX
Video Analysis
실시간 서비스 플랫폼 개발 사례
WebRTC 현재와 미래 최진호 2016
게임 분산 서버 구조
7가지 동시성 모델 람다아키텍처
What is web rtc
Skates seminar 2 michael plummer
Session 3 collectors-and-collecting
KG패스원 5월 패밀리데이
Ma.candelaria parés
[2013년 11월] KG패스원 패밀리데이 사진첩
Presentation for media
Demons - Storyboard
Mofuse mobile web
Potential Treatment for ALS and Frontotemporal Dementia Discovered
Best Cellulite Removal
Tipos y beneficios de las herramientas web 2.0 en la gerencia educativa
Evaluation question 2
Session 2 art-backed-financial-products
Storyboard - Demons
Video Analysis
Ad

Similar to Nginx basic configurations (20)

PDF
[오픈소스컨설팅]Nginx 1.2.7 설치가이드__v1
PPTX
Nginx Https 적용하기.pptx
PDF
Fluentd with MySQL
PPTX
Ngrok을 이용한 Nginx Https 적용하기.pptx
PDF
Linux Performan tuning Part I
PPTX
Hadoop security DeView 2014
PDF
Openstack live migration
PDF
Enterprise Linux 7 new feature_network configuration
PDF
OpenStack Swift Debugging
PPTX
Hadoop distributed file system rev3
PPTX
Tcp summary
PDF
Build the OpenStack Cloud with Neutron Networing, IceHouse
PDF
20141029 하둡2.5와 hive설치 및 예제
PDF
KAFKA 3.1.0.pdf
PPTX
PHP Log Tracking with ELK & Filebeat part#2
PDF
Java 초보자를 위한 hadoop 설정
PDF
Apache Tomcat ( 아파치 톰캣 ) 설치 가이드
PDF
(120128) #fitalk sql server anti-forensics
PPTX
docker on GCE ( JIRA & Confluence ) - GDG Korea Cloud
PDF
XECon2015 :: [1-5] 김훈민 - 서버 운영자가 꼭 알아야 할 Docker
[오픈소스컨설팅]Nginx 1.2.7 설치가이드__v1
Nginx Https 적용하기.pptx
Fluentd with MySQL
Ngrok을 이용한 Nginx Https 적용하기.pptx
Linux Performan tuning Part I
Hadoop security DeView 2014
Openstack live migration
Enterprise Linux 7 new feature_network configuration
OpenStack Swift Debugging
Hadoop distributed file system rev3
Tcp summary
Build the OpenStack Cloud with Neutron Networing, IceHouse
20141029 하둡2.5와 hive설치 및 예제
KAFKA 3.1.0.pdf
PHP Log Tracking with ELK & Filebeat part#2
Java 초보자를 위한 hadoop 설정
Apache Tomcat ( 아파치 톰캣 ) 설치 가이드
(120128) #fitalk sql server anti-forensics
docker on GCE ( JIRA & Confluence ) - GDG Korea Cloud
XECon2015 :: [1-5] 김훈민 - 서버 운영자가 꼭 알아야 할 Docker

Nginx basic configurations

  • 2. 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
  • 3. $ sudo yum install epel-release $ sudo yum install epel-release $ sudo yum -y install nginx $ nginx -h nginx version: nginx/1.0.15 Usage: 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
  • 4. $ 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
  • 5. 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
  • 6. 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
  • 7. 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 nginx 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
  • 8. 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 shutdown quit — graceful shutdown reload — reloading the configuration file reopen — reopening the log files $ sudo kill -HUP `cat /var/run/nginx.pid` $ sudo nginx -s reload SIGNALS
  • 9. PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1148 pause nginx: master process 33127 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 COMMAND 33126 1 root 0.0 1164 pause nginx: master process 33130 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 COMMAND 33126 1 root 0.0 1164 pause nginx: master process 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) BEFORE RELOAD AFTER RELOAD RELOADING RELOAD NEW CONFIGURATION WITH NO DOWNTIME
  • 10. RELOAD NEW BINARY WITH NO DOWNTIME
  • 12. Worker Process worker_processes 2; events { worker_connections 65536; use epoll; multi_accept on; } /etc/nginx/nginx.conf 1 2 3 4 worker_process 는 Event Looping Single Thread 로 일반적으로 CPU Core 수에 맞게 설정한다. 또는, worker_processes auto; 하여 자동으로 Core 수에 맞게 실행되도록 할 수 있다. $ grep ^processor /proc/cpuinfo | wc -l Core 수 확인은 아래와 같이 함. 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 를 처리 할 수 있도록 하는 옵션이다.
  • 13. 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 를 최소화 하여 지연을 줄이는 방식이다.
  • 14. 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)를 반환한다. 2 client_header_buffer_size (default : 1k) header 사이즈며 대부분 1k 면 충분하다. 하지만 Cookie 가 상당히 많은 경우는 이를 조정할 필요가 있다. on 하게 되면, 이미지나 비디오 같은 static 파일을 multi thread 로 보내도록 한다. 주로 이미지를 전송하게 되는 경우 사용한 다.
  • 15. 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 로 확인이 가능하다.
  • 16. 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” 가 지정한 경우와 일치하는 경우 압축하지 않도록 한다.
  • 17. 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)
  • 18. 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 전체 내용
  • 19. # 앞장 계속 # 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 전체 내용