본문 바로가기

Docker

[Docker] Docker Nginx, Reverse Proxy로 서버 구동 및 보안 설정(with kibana) - 1

반응형

시작 전 읽어보면 도움 될 글 - https://kanoos-stu.tistory.com/entry/Nginx

 

[Nginx] Nginx란, Nginx 와 Apache

Nginx 란 트래픽이 많은 웹사이트의 확장성을 위해 개발된 경량의 고성능 웹서버이다. Nginx는 적은 자원의 사용으로 높은 성능과 높은 동시성을 목표로 만들어졌다. Nginx가 등장하기 전에는 Apache

kanoos-stu.tistory.com

 

Nginx Image 설치 (생략 가능)

docker pull nginx

최신버전 nginx를 받아준다. (태그 입력 생략 시 latest 버전 자동 설치)

 

Nginx container 실행

sudo docker run -d --name nginx -p 80:80 \
-v my-nginx-conf:/etc/nginx/ \
--network my-network \
nginx

run 명령어로 실행해준다.

호스트 ip를 통해 80포트에 접근을 가능하게 하기 위해 80포트를 포트포워딩 (-p) 해주었고

nginx의 설정 파일에 접근 및 상태를 유지하기 위해 my-nginx-conf 볼륨을 공유 (-v) 하였고

다른 프로세스에 접근할 수 있도록 네트워크를 (--network) 설정해 주었다.

 

Nginx 의 기본 명령어

nginx -s [signal]

[signal] 옵션

  • stop - 빠른 종료
  • quit - 정상 종료, 현재 요청이 처리가 끝날 때 까지 기다렸다가 nginx를 종료한다.
  • reload - 구성 파일 다시 로드, 구성 설정 파일 수정 시 재시작 하지 않고 반영할 수 있다.
  • reopen - 로그 파일 다시 열기

 

Nginx 구성 파일의 구조

nginx는 구성 파일의 정의된 directive에 따라 제어되는 모듈로 구성된다.

directive는 simple directive와 block directive로 나뉜다.

 

pid        /var/run/nginx.pid;

simple directive - 공백으로 구분된 이름과 매개변수로 구성되며 세미콜론(;)으로 끝난다.

 

events {
    worker_connections  1024;
}

block directive - simple directive와 구조는 동일하지만 세미콜론대신 중괄호({~}) 로 묶여있다.

 

여기서 block directive 내부에 다른 directive가 들어갈 수 있는 directive를 context라고 한다.

events, http, mail, stream 등 은 대표적인 최상위 context이다.

  • events - 일반 연결 처리
  • http - HTTP 트래픽
  • mail - 메일 트래픽
  • stream - TCP 및 UDP 트래픽

그리고 context들은 main context에 속해있다.

 

 

반응형

 

Nginx 구성 파일 설정

nginx를 설치하면 기본적으로 설정파일이 두 개 생성된다.

  • etc/nginx/nginx.conf - 실질적으로 nginx가 구동되는 과정에서 적용되는 구성 파일
  • etc/nginx/conf.d/default.conf - nginx.conf 에서 include 하여 사용할 구성 파일(옵션)

 

nginx.conf

 

user  nginx;
worker_processes  auto;

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

 

  • user - nginx를 구동시킬 유저 지정
  • worker_processes - worker process의 개수, 최적의 값으로는 cpu 코어 수, 하드 디스크 드라이브 수, 로드 패턴 등 여러 요인에 따라 달라지는데 확실하지 않을 경우, 사용 가능한 cpu코어 개수로 설정하는것을 권장(auto 설정 시 cpu코어 개수 지정)
  • error_log - 로그를 출력할 경로 지정 및 출력 로그 level을 지정
  • pid - nginx의 process id를 저장

 

events {
    worker_connections  1024;
}

 

  • events { } - 연결 처리에 영향을 미치는 directive가 지정되는 구성 파일 context를 제공
  • worker_connections - worker process의 최대 동시 연결 수 (클라이언트 연결, 프록시 서버 연결 등)

 

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;
}
  • include - 외부의 파일을 구성에 포함시킨다. 위의 코드에서는 mime.type(파일 확장자 명과 MIME타입 정보)과 conf.d 폴더 내의 모든 구성파일을 포함시키도록 되어있다. 
  • default_type - 기본 content-type 설정, octet-stream은 바이너리 형태의 타입을 의미한다.
  • log_format - 로그와 관련된 설정 (참고)
  • access_log - 엑세스 로그 저장 경로 및 로그 레벨 지정
  • sendfile - nginx가 정적 파일을 보낼지 지정
  • tcp_nopush - 클라이언트로 패킷이 전송되기 전에 버퍼가 가득 찼는지 확인하여 다 찼으면 패킷 전송하도록 하여 네트워크 오버헤드 줄이도록 설정
  • keppalive_timeout - 클라이언트에서 서버로 커넥션 유지할 수 있는 시간 설정, 자원 낭비 예방 (초 단위)
  • gzip - 웹서버에서 문서 요청에 대한 응답을 gzip 압축 전송할지 여부 지정.

참고 - https://nginx.org/en/docs/ngx_core_module.html#example

 

conf.d/default.conf

 

default.conf 구성 파일은 nginx.conf 구성 파일 내부의 include에 의해 http context 내부에 구성된 block directive라고 보면 된다.

 

server {
        listen      80;

        root         /usr/share/nginx/html;
        index index.html index.htm index.php;

        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf; 주석 해제되어 있으나, 주석해도 문제 없이 잘 작동한다.

        location / {
        }

        location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
        location ~ /\.ht {
             deny  all;
        }
        error_page 404 /404;
        location = /404 { # php 404 redirect
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
}
  • server { } - 가상 서버에 대한 구성 설정. 인증서, url, proxy 등 관리
  • listen - 구성을 적용할 가상 서버의 포트 설정
  • root - 디렉토리 경로 지정
  • index - root로 지정한 디렉토리 내부의 인덱스 파일 이름
  • location [path] - path에 해당하는 요청의 설정을 정의
  • error_page - 해당 에러 코드의 에러 페이지 지정

참고 - https://nginx.org/en/docs/http/ngx_http_core_module.html#server

 

kibana 설정, 실행 및 보안 설정은 다음 글에서 계속

반응형