개발일기

Nginx 설치 및 nginx.conf, default.conf 이해하기 본문

Web Server/Nginx

Nginx 설치 및 nginx.conf, default.conf 이해하기

Flashback 2021. 11. 2. 17:03
728x90
반응형

 

1. Nginx란?

  • 가볍고 높은 성능을 가진 웹 서버 (Web Server) 이다.
  • HTTP Server로 활용되며 정적 파일들을 처리하기 위해 사용된다.
  • Reverse Proxy Server로 활용된다. 80번 포트로 들어오는 내용을 3000, 4000, 9000 등의 다른 포트로 분산 시켜줄 수 있다.
  • 비동기 이벤트 구조를 기반으로 동작한다.

 

 

2. Nginx와 Apache의 차이점은??

가장 큰 차이점은 두 서버의 동작 방식이다. Nginx는 Event-Driven 방식으로 작동하고, Apache는 쓰레드 / 프로세스 기반으로 작동한다.

 

Event-Driven : 

  • 서버로 들어오는 여러 개의 커넥션을 Event-Handler를 통해 비동기방식으로 처리를 하게 한다.
  • 이러한 방식으로 인해 적은 메모리로 서버를 운영할 수 있다.
  • 싱글 스레드, 프로세스로 작동한다.
  • socker read / writer, I/O 등 CPU가 관여하지 않아도 되는 작업을 진행할 때는 기다리지 않고 다른 작업을 수행한다. 진행 중인 I/O 등의 작업이 종료되면 이벤트가 발생하며 그 다음 작업 처리를 시작한다.

Thread / Process : 

  • 클라이언트의 접속 때마다 Thread 또는 Process를 생성하여 처리한다.
  • 다양한 모듈을 제공하며 확장성이 좋다.

Apache는 접속 때마다 Thread 또는 Process를 생성하기에 많은 수의 요청이 발생하면 속도가 느려지게 된다. 하지만 Nginx는 Event-Listener를 통해 요청 흐름을 처리하기에 많은 수의 요청도 효율적으로 처리할 수 있다.

 

 

3. Nginx의 설치방법

OS는 Centos를 기반으로 설치하겠다.

nano /etc/yum.repos.d/nginx.repo
vi /etc/yum.repos.d/nginx.repo
vim /etc/yum.repos.d/nginx.repo
# nginx 저장소를 추가하기 위해 파일을 생성한다.

 

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

# nginx.repo에 위의 내용을 추가한 후 저장한다.

 

yum install nginx -y
# nginx를 설치한다.

nginx -v
# 설치된 nginx 버전 확인

nginx를 설치하면 초기에 설정된 nginx.conf와 default.conf 파일을 확인할 수 있다.

 

 

4. nginx.conf 관련 내용

nginx의 기본 설정 파일인 nginx.conf에서 설정을 진행한다.

vi /etc/nginx/nginx.conf
vim /etc/nginx/nginx.conf
nano /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;

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;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    
    include /etc/nginx/conf.d/*.conf
}

 

error_log : nginx의 에러로그가 쌓이는 경로이다.

error_log  /var/log/nginx/error.log warn;

 

pid : nginx의 프로세스 아이디 (pid)가 저장되는 경로이다.

pid        /var/run/nginx.pid;

 

worker_connections : Worker Process가 동시에 처리할 수 있는 접속자의 수를 나타낸다. 기본은 1024로 설정되어져 있다.

events {
    worker_connections  1024;
}

 

include : 포함시킬 외부파일을 정의한다. mime.types란 파일에 작성되어진 내용들을 현재 파일로 가져오는 것을 뜻한다.

http {
    include       /etc/nginx/mime.types;
}

 

http의 마지막 줄에 있는 include는 서버 속성이 정의되어져 있는 파일을 포함시킨다는 명령어이다. /etc/nginx/conf.d에 .conf로 끝나는 파일들을 포함시켜 가져온다는 것을 뜻한다.

http {
    include      /etc/nginx/conf.d/*.conf;
}

 

default_type : 웹서버의 기본 Content-Type을 정의한다.

http {
    default_type  application/octet-stream;
}

 

log_format : 로그 형식을 지정한다. 후술한 로그 형태에 따라 로그가 작성되고 기록된다.

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
}

https://docs.nginx.com/nginx/admin-guide/monitoring/logging/

 

Configuring Logging | NGINX Plus

Configuring Logging Capture detailed information about errors and request processing in log files, either locally or via syslog. This article describes how to configure logging of errors and processed requests in NGINX Open Source and NGINX Plus. Setting

docs.nginx.com

$remote_addr, $remote_user 등의 로그 형태에 관한 자세한 내용은 nginx logging관련 문서에 영어로 정리되어져 있다.



access_log : 접속 로그가 쌓이는 경로이다.

http {
    access_log  /var/log/nginx/access.log  main;
}

 

sendfile : sendfile() 함수의 사용여부를 지정한다. sendfile() 함수는 한 파일의 디스크립터와 다른 파일의 디스크립터 간에 데이터를 복사하는 것으로 커널 내부에서 복사가 진행된다.

http {
    sendfile        on;
    # sendfile        off;
}

 

keepalive_timeout : 클라이언트에서 연결이 유지될 시간을 정의한다. 기본은 65로 설정되어져 있다.

http {
    keepalive_timeout  65;
}

 

 

5. default.conf 관련 내용

default.conf는 nginx.conf를 통해 include된 서버 설정관련 파일이다. default2.conf, default3.conf 등 여러 개의 파일을 추가하여 서버관련 설정을 추가로 만들어 포함시킬 수 있다.

vi /etc/nginx/conf.d/default.conf
vim /etc/nginx/conf.d/default.conf
nano /etc/nginx/conf.d/default.conf
# nginx 설치 후, default.conf 파일을 연다.


server {
    listen       80;
    server_name  localhost;

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

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

 

listen : 해당 포트로 들어오는 요청을 해당 server {} 블록의 내용에 맞게 처리하겠다는 것을 뜻한다.

server {
    listen       80;
    # http포트인 80번 포트를 통해 들어오는 요청을 해당 블록의 내용에 맞게 처리한다.
}

 

server_name : 호스트 이름을 지정한다. 가상 호스트가 있는 경우 해당 호스트명을 써넣으면 된다. 만약 로컬에서 작업하고 있는 내용을 nginx를 통해 띄우려고 하는 경우에는 localhost라고 적으면 된다.

server {
    server_name		localhost;
}

 

error_page : 요청결과의 http 상태코드가 지정된 http 상태코드와 일치할 경우, 해당 url로 이동한다. 보통 403, 404, 502 등의 에러처리를 위해 사용한다.

url 결과에 따라 이후에 나오는 location = /50x.html와 일치하면 /usr/share/nginx/html 경로에 존재하는 50x.html 파일을 보여준다.

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

 

location / : 처음 요청이 들어왔을 때 ( server_name이 127.0.0.1인 경우 -> 127.0.0.1로 요청이 들어왔을 때 ) 보여줄 페이지들이 속해있는 경로와 초기 페이지인 index를 지정해준다. / url로 접속했을 경우 index.html, index.htm로 정의된 파일을 보여준다.

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

 

 

6. nginx 가동 방법

systemctl restart nginx # nginx 재시작

systemctl start nginx # nginx 시작

systemctl stop nginx # nginx 중지
728x90
반응형

'Web Server > Nginx' 카테고리의 다른 글

Nginx - Reverse Proxy 설정 및 요소 이해하기  (0) 2021.11.03
Nginx php-fpm 설정방법  (2) 2021.11.03
Comments