ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [CentOS 7] Nginx 서버 "1"
    Linux/CentOS 2018. 5. 16. 15:58

     Nginx는 웹 서버이면서 동시에 HTTP, HTTPS, SMTP, POP3, IMAP 프로토콜을 위한 리버스 프록시 서버로도 사용된다. 또한 로드 밸런서 및 HTTP 캐시로도 사용된다. 이렇게 다양한 기능을 제공하는 Nginx 서버는 2002년 러시아의 개발자 lor Sysoev에 의해 처음 개발돼 2004년 배포되기 시작했는데, 현재 리눅스와 유닉스를 비롯한 대부분의 운영체제에서 사용가능한 오픈소스 소프트웨어다. 

     Nginx는 1999년 Dan Kegel이 처음 사용한 C10k 문제, 즉 한 개의 웹 서버에서 10,000개의 동시 접속 한계를 극복하기 위한 높은 성능을 구현하는 것이 그 개발에 초점이 됐다. 이러한 문제를 해결하기 위해 Nginx 서버는 비동기적 EDA(Asynchronous Event-Driven Architecture)라는 방식을 사용했는데, 이는 Apache 서버처럼 하나의 스레드(Thread)에서 하나의 접속을 허용하는 전통적인 방식과는 차이가 있다. Nginx 서버는 Apache처럼 요청을 받을 때마다 프로세스를 만들지 않고, 이 EDA 방식을 통해 하나의 프로세스로 많은 접속을 처리하게 함으로써  CPU 부하와 메모리 사용은 더 적으면서 속도는 더 빠른 장점을 갖고 있다. 그래서 Nginx 서버는 클라이언트의 접속량이 많은 고부하 환경에서 더 큰 성능을 발휘하기 때문에 Apache 서버를 이을 차세대 웹 서버라고 불리기도 한다. 물론 Apache 서버도 EventMPM(Multi Processing Module)모델을 통해 이와 유사한 방식으로 서비스 제공이 가능한다. 


    1. Nginx 이해


    1.1 Nginx 구조 이해


    a. HTTP와 HTTPS 프로토콜

    1. 사용자는 웹 클라이언트 프로그램 브라우저를 통해 웹 서버에 접근하는데, 이때 사용하는 프로토콜 HTTP, 그리고 데이터 암호화를 위해 SSL이 적용된 HTTPS다.

    2. 웹 서버는 HTTP 접속을 위해 포트 80번, 그리고 HTTPS 접속을 위해 기본적으로 포트 443번을 통해 이러한 클라이언트의 요청을 받아들인다.


    b. Master와 Worker 프로세스

    1. Nginx 웹 서버의 경우 HTTP나 HTTPs를 사용한 클라이언트의 요청을 한 개의 master 프로세스와 여러 worker 프로세스르 통해 처리하는데, Nginx 서버가 시작되면 한 개의 master 프로세스가 실행되고 worker 프로세스는 이 master 프로세스의 호출에 따라 실행된다.

    2. 설정 파일 /etc/nginx/nginx.conf에서 지시어 worker_processes 를 통해 이러한 초기 worker 프로세스 생성 개수를 지정할 수 있다. 그 값을 auto로 설정한 경우 프로세서(processor) 개수만큼 실행된다. /proc/cpuinfo에서 확인가능하다.

    3. 각 woker 프로세스는 클라이언트의 요청마다 새로운 프로세스를 생성하지 않고 하나의 worker 프로세스가 많은 요청을 동시에 처리하는 기능으로 인해 single-threaded프로세스라고 부르기도 한다. 

    4. 한 worker 프로세스가 처리하는 연결 개수는 설정 파일인 nginx.conf에서 지시어 worker_connections를 통해 그 숫자를 지정할 수 있으며, 기본으로 1024가 사용되는데 이는 초당 1024 클라이언트의 접속 요청을 처리할 수 있다는 의미다. 

    5. 각각의 worker 프로세스는 독립적으로 실행되기 때문에 한 프로세스에서 발생하는 에러가 다른 worker 프로세스에 영향을 주지 않으며, 공유된 캐시 데이터나 다른 공유 자원을 위해 공유 메모리를 사용해 서로 간에 통신할 수 있다. 

    6. worker 프로세스 내부에는 nginx 모듈이 내장돼 있는데 이들은 연결 요청 처리, 필터링, 그리고 프록시 연결처리와 부하 분산 및 그 밖에 여러 일을 처리한다. worker 프로세스는 클라이언트의 기본적인 HTTP 요청을 처리하기 위해 기본적으로 ht_core 모듈을 로딩해 사용한다. 

    7. nginx 서버와는 다르게 Apache 서버는 스레드 기반/프로세스 기반을 사용하느데, 이는 각 클라이언트의 연결 요청에 대해 새 스레드/프로세스가 생성되고 이에 응답을 보내면 스레드/프로세스는 종료되며, 이들이 사용했던 CPU나 메모리 같은 자원을 다른 스레드/프로세스가 사용하도록 방출하게 된다.

    8. Master 프로세스는 설정 파일 읽기와 검증하기, 소켓 처리하기, worker 프로세스 호출 및 관리하기, 로그 파일 오픈하기 등의 역할을 담당하며, SIGHUP과 같은 시그널을 통해 관리자의 요청에 응답할 수 있다.

    9. Nginx는 Asynchronous 비동기식 Event-driven 개념을 사용한다고 서두에서 설명했는데, 여기서 Event-driven이란 기본적으로 웹 서버가 처리해야 할 여러 다양한 작업을 이벤트로서 처리하기 위한 접근 방법이다. 클라이언트의 연결 요청이나 디스크 읽기 및 쓰기도 모두 하나의 이벤트라고 할 수 있는데, 이 개념은 처리해야 할 이벤트가 없다면 서버의 리소스를 낭비할 필요가 없다는 개념에서 시작됐다. 

    10. 우리가 현재 사용 중인 운영체제는 이러한 작업의 시작이나 종료에 대한 내용을 웹 서버에게 알릴 수 있다. 이렇게 하면 Nginx worker프로세스는 이 이벤트 처리를 위해 알맞은 방법을 적용해 적절한 자원을 사용할 수 있다. 그러면 웹 서버의 자원은 요청에 따라서 동적으로 할당되고 또한 제거되는데, 이러한 방법은 네트워크나 메모리, 그리고 CPU 같은 하드웨어를 최적화해 사용할 수 있도록 도와준다.


    c. Helper 프로세스

    1. Helper 프로세스로 사용되는 캐시 로더(Cache Loader)프로세스는 Nginx 시작 시에 실행돼 디스크 기반의 캐시를 메모리로 로딩하는 역할을 수행한 뒤에 빠저 나간다.

    2. 캐시 매니저(Cache Manager)는 설정한 크기 내에서 캐시를 유지하기 위해 규칙적으로 실행하면서 디스크 캐시에서 유효하지 않은 엔트리를 제거하는 역할을 수행

    3. FastCGI 프로세스는 백엔드에 위치한 어플리케이션 서버에 저장된 파이썬, 루비와 같은 코드들을 실행하기 위해 사용된다.

    4. Memcached 서버는 메모리 기반의 오브젝트 캐시 시스템으로서 캐시에 저장된 동적인 웹 어플리케이션의 데이터를 직접 클라이언트에게 제공함으로써 그 응답 속도를 높이기 위한 목적으로 사용되는데, Nginx 서버는 이를 위해 memcache 모듈을 사용한다. 



    1.2 Nginx와 Apache 서버

    # apche와 nginx 서버 비교

     항목

    Apache 서버 

    Nginx 서버 

    개발 시작 

    1995년 Rovert Macool가 개발 시작 

     2002년 lgor Sysoev가 개발 시작

    아키텍처 

    프로세스와 스레드 및 Event MPM  

    Event-driven 

    연결 요청 

    새로운 프로세스 또는 스레드 요청 

    한 프로세스가 많은 연결 처리 

    메모리 

    많은 메모리 소요 

    정적 페이지 제공 위해 낮은 메모리 필요 

    문서 

    문서 정리가 Nginx에 비해 뛰어남 

    문서 정리가 Apache보다 뛰어나지 않음 

    운영체제 

    대부분의 운영체제 지원 

    OpenVMS나 IBMi 지원하지 않음 

    속도 

    Nginx에 비해 느림 

    정적 페이지 제공 속도 뛰어남 

    기능 

    Nginx에 비해 많은 기능 제공 

    Apache에 비해 지원 기능 요소가 적음 

    복잡성 

    다양한 기능을 지원함으로써 Nginx에 비해 복잡 

    웹 서버로서 필요한 핵심 기능만 가지고 시작해서 더 가벼움 

    성능과 확장성 

    메모리나 CPU 같은 하드웨어 자원 의존적

    하드뒈어의 자원에 전적으로 의존하지 않음





    2. Nginx  서비스 시작과 PHP 사용


    2.1 Nginx 서버 설치와 서비스 시작


    a. 설치와 기본 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    1. yum을 이용해 패키지 설치
    [root@master ~]# yum install epel-release -y
    [root@master ~]# yum install nginx -y
     
    2. 패키지 설치를 확인하면 의존 관계에 있는 패키지도 같이 설치된다.
    [root@master ~]# rpm -qa | grep nginx
    nginx-1.12.2-2.el7.x86_64
    nginx-filesystem-1.12.2-2.el7.noarch
    nginx-all-modules-1.12.2-2.el7.noarch
     
    3. 설정 파일을 열어서
    [root@master ~]# vi /etc/nginx/nginx.conf
        server {
            listen       80 default_server;
            #listen       [::]:80 default_server;  # IPv6를 사용하지 않을 경우 주석처리
            server_name  www.chul.com;    # Nginx에서 사용할 주 도메인을 정의
            root         /usr/share/nginx/html;    # Nginx 서버에서 데이터를 저장할 루트 디렉토리 
    cs


    b. 서비스 시작

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    1. Apache 서버가 작동하고 있다면 서비스를 중단해야 하는데, 같은 80번 포트를 사용하기 때문에 충돌하기 때문이다.
    [root@master ~]# systemctl stop httpd
    Failed to stop httpd.service: Unit httpd.service not loaded.
     
    2. Nginx 데몬 시작
    [root@master ~]# systemctl start nginx
     
    3. Nginx 서비스가 부팅 이후에도 시작되도록 설정
    [root@master ~]# systemctl enable nginx
    Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
     
    4. Nginx 상태를 확인하는데, 한 개의 master프로세스 및 worker 프로세를 볼 수 있다.
    [root@master ~]# systemctl status nginx
    ● nginx.service - The nginx HTTP and reverse proxy server
       Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
       Active: active (running) since Wed 2018-05-09 15:43:20 UTC; 9s ago
     Main PID: 4556 (nginx)
       CGroup: /system.slice/nginx.service
               ├─4556 nginx: master process /usr/sbin/nginx
               └─4557 nginx: worker process
    May 09 15:43:20 master.chul.com systemd[1]: Starting The nginx HTTP and reverse proxy server...
    May 09 15:43:20 master.chul.com nginx[4551]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    May 09 15:43:20 master.chul.com nginx[4551]: nginx: configuration file /etc/nginx/nginx.conf test is successful
    May 09 15:43:20 master.chul.com systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
    May 09 15:43:20 master.chul.com systemd[1]: Started The nginx HTTP and reverse proxy server.
     
    5. nginx가 사용하는 포트 및 PID를 확인
    [root@master ~]# netstat -natp | grep nginx
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      4556/nginx: master
     
    6. 프로토콜 TCP와 포트 80번을 확인하면 Nginx가 http 서비스를 사용하고 있음을 알 수 있다.
    [root@master ~]# lsof -i tcp:80
    COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    nginx   4556  root    6u  IPv4  27149      0t0  TCP *:http (LISTEN)
    nginx   4557 nginx    6u  IPv4  27149      0t0  TCP *:http (LISTEN)
     
    7. Nginx 프로세스 확인
    [root@master ~]# ps -ef | grep nginx
    root      4556     1  0 15:43 ?        00:00:00 nginx: master process /usr/sbin/nginx
    nginx     4557  4556  0 15:43 ?        00:00:00 nginx: worker process
    root      4581  4069  0 15:44 pts/0    00:00:00 grep --color=auto nginx
     
    8. Nginx가 사용하는 데이터가 저장된 루트 디렉토리
    [root@master ~]# ls /usr/share/nginx/html/
    404.html  50x.html  index.html  nginx-logo.png  poweredby.png
     
    9. Nginx가 사용하는 로그 파일이 저장된 디렉토리
    [root@master ~]# ls /var/log/nginx/
    access.log  error.log
     
    10. Nginx 
    [root@master ~]# nginx -v
    nginx version: nginx/1.12.2
    cs


    c. 접속 확인

    Nginx  서버가 정상적으로 시작됐으므로 브라우저에서 접속을 시도하는데, 주 도메인으로 접속하면 다음과 같은 화면을 볼 수 있다.



    2.2 PHP 사용

    Nginx에서 PHP를 사용하는 방법은 다음과 같다. Apache 서버에서는 PHP를 사용하기 위해 mod_php 모듈을 사용했는데 Nginx 서버는 PHP-FPM을 사용한다.


    a. PHP-FPM 설정

    Nginx 서버에서는 PHP를 사용하기 위해 PHP-FPM 패키지를 사용하는데, 이는 PHP FastCGI Process Manager의 약어로서 PHP 스크립트를 웹 서버가 아닌 이 매니저를 통해 직접 관리하기 때문에 더 빠른 속도로 그 결과를 클라이언트에게 제공할 수 있다. 또한 Apache 서버의 mod_php보다 더 적은 메모리를 사용하기 때문에 그만큼 속도가 더 빠르다는 장점이 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    1. yum을 사용해 php 패키지를 설치
    [root@master ~]# yum install php php-mysql php-fpm -y
    [root@master ~]# rpm -qa | grep php
    php-fpm-5.4.16-43.el7_4.1.x86_64
     
    2. vim으로 설정 파일을 열어서
    [root@master ~]# vi /etc/php-fpm.d/www.conf
    listen = /var/run/php-fpm/php-fpm.sock    # FastCGI 요청을 받아들일 소켓의 위치를 지정
    listen.owner = nobody    # 소켓의 소유권자가 이 사용자와 이 그룹이름으로 변경    
    listen.group = nobody
    user = nginx    # 디렉토리와 로그 디렉토리에 접근할 사용자 이름을 apache에서 nginx로 변경
    group = nginx
     
    3. php-fpm 서비스를 시작
    [root@master ~]# systemctl start php-fpm
    [root@master ~]# systemctl enable php-fpm
    Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
     
    4. php-fpm 상태를 확인
    [root@master ~]# systemctl status php-fpm
    ● php-fpm.service - The PHP FastCGI Process Manager
       Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
       Active: active (running) since Wed 2018-05-09 15:55:27 UTC; 6s ago
     Main PID: 4736 (php-fpm)
       Status: "Ready to handle connections"
       CGroup: /system.slice/php-fpm.service
               ├─4736 php-fpm: master process (/etc/php-fpm.conf)
               ├─4738 php-fpm: pool www
               ├─4739 php-fpm: pool www
               ├─4740 php-fpm: pool www
               ├─4741 php-fpm: pool www
               └─4742 php-fpm: pool www
    May 09 15:55:27 master.chul.com systemd[1]: Starting The PHP FastCGI Process Manager...
    May 09 15:55:27 master.chul.com systemd[1]: Started The PHP FastCGI Process Manager.
     
    5. php-fpm의 프로세스를 확인
    [root@master ~]# ps -ef | grep php-fpm
    root      4736     1  0 15:55 ?        00:00:00 php-fpm: master process (/etc/php-fpm.conf)
    nginx     4738  4736  0 15:55 ?        00:00:00 php-fpm: pool www
    nginx     4739  4736  0 15:55 ?        00:00:00 php-fpm: pool www
    nginx     4740  4736  0 15:55 ?        00:00:00 php-fpm: pool www
    nginx     4741  4736  0 15:55 ?        00:00:00 php-fpm: pool www
    nginx     4742  4736  0 15:55 ?        00:00:00 php-fpm: pool www
    cs


    b. PHP 사용을 위한 Nginx 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    1. nginx 서버 설정을 열어서
    [root@master ~]# vi /etc/nginx/nginx.conf
            location ~ \.php$ {        # 확장자가 php로 끝나는 파일인 경우를 의미하는데, 틸드(~)는 대소문자 구별을 의미
                fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;    # php 스크립트 요청을 php-fpm 소켓이 처리하도록 설정
                fastcgi_index  index.php;    # 브라우저에서 URL가 '/'로 끝날 경우 실행되는 파일명
                # FastCGI가 사용할 수 있는 파라미터 값이 저장된 파일을 포함시키는데, 이 파일은 /etc/nginx/fastcgi_params를 의미
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;    
                include        fastcgi_params;
            }
     
    [root@master ~]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
     
    2. 변경 사항을 적용하기 위해 nginx 재시작
    [root@master ~]# systemctl restart nginx
     
    3. 테스트를 위해 php 정보를 출력해 줄 함수가 포함된 파일을 
    [root@master ~]# vim /usr/share/nginx/html/info.php
    <?php
    phpinfo();
    ?>
    cs


    c. PHP 테스트

    브라우저에서 www.192.168.80.5/info.php를 이용해 PHP 테스트를 진행하면 다음과 같다.





    3. Nginx CGI 사용


    Perl, 파이썬, 루비와 더불어 Node.js 기반의 자바스크립트를 사용하는 Ghost 프로그램을 설치하는 방법을 설명한다.


    3.1 CGI Perl 사용

    Perl은 현재 파이썬이나 루비 같은 다른 언어에 비해 많이 사용되지 않는 언어다.


    a. 스크립트 다운로드

    서비스 시작 Init 파일과 Perl 스크립트 요청을 처리할 Fastcgi파일을 다운로드한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    1. Perl에서 사용할 FastCGI 스크립트 파일을 명령어 wget을 사용해 다운로드하고 바이너리 디렉토리 /usr/bin으로 이동
    [root@master ~]# wget http://nginxlibrary.com/downloads/perl-fcgi/fastcgi-wrapper -O /usr/bin/fastcgi-wrapper.pl
    --2018-05-09 16:18:35--  http://nginxlibrary.com/downloads/perl-fcgi/fastcgi-wrapper
    Resolving nginxlibrary.com (nginxlibrary.com)... 192.30.252.153192.30.252.154
    Connecting to nginxlibrary.com (nginxlibrary.com)|192.30.252.153|:80... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 3133 (3.1K) [application/octet-stream]
    Saving to: ‘/usr/bin/fastcgi-wrapper.pl’
    100%[===================================================================================>3,133       --.-K/s   in 0s
    2018-05-09 16:18:36 (566 MB/s) - ‘/usr/bin/fastcgi-wrapper.pl’ saved [3133/3133]
     
    2. 다운로드한 파일을 실행 시키기 위한 시작 스크립트 파일을 명령어 wget로 다운로드하고 디렉토리 이동시킨다.
    [root@master ~]# wget http://nginxlibrary.com/downloads/perl-fcgi/perl-fcgi -O /etc/init.d/perl-fcgi
    --2018-05-09 16:18:59--  http://nginxlibrary.com/downloads/perl-fcgi/perl-fcgi
    Resolving nginxlibrary.com (nginxlibrary.com)... 192.30.252.154192.30.252.153
    Connecting to nginxlibrary.com (nginxlibrary.com)|192.30.252.154|:80... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 689 [application/octet-stream]
    Saving to: ‘/etc/init.d/perl-fcgi’
    100%[===================================================================================>689         --.-K/s   in 0s
    2018-05-09 16:18:59 (273 MB/s) - ‘/etc/init.d/perl-fcgi’ saved [689/689]
     
    3. 다운로드한 파일에 실행 권한을 부여
    [root@master ~]# chmod +x /usr/bin/fastcgi-wrapper.pl
    [root@master ~]# chmod +x /etc/init.d/perl-fcgi
     
    4. 스크립트 파일에 FastCGI사용자로 www-data가 정의돼 있어서 이 사용자를 생성한다. 사용자 nginx를 사용할 경우 이 스크립트를 열어서 변경
    [root@master ~]# useradd www-data
    [root@master ~]# vi /etc/init.d/perl-fcgi
    FASTCGI_USER=nginx 
    cs


    b. 서버 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    1. Nginx 설정을 열어서
    [root@master ~]# vi /etc/nginx/nginx.conf       
            location ~ \.pl$ {    # 확장자가 pl로 끝나는 perl 스크립트 파일을 찾지 못하면 404 에러 페이지가 보이게한다.
                try_files $uri =404;
                include        fastcgi_params;
                gzip off;
                # pl로 끝나는 Perl 스크립트 실행 요청이 들어오면 Nginx 서버는 이 요청을 로컬 호스트 8999번으로 보내 FastCGI가 
                # 이 요청에 응답하도록 한다. 이 포트 번호는 FastCGI 스크립트 파일에 정의돼 있다. 
                fastcgi_pass   127.0.0.1:8999;     
                fastcgi_index  index.pl;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                fastcgi_param  PATH_INFO $fastcgi_path_info;
            }
     
    2. 테스트를 위해 루트 디렉토리에 index.pl 파일을 생성
    [root@master ~]# vi /usr/share/nginx/html/index.pl
    #!/usr/bin/perl
    print "Content-type: text/html\n\n";
    print "<html>\n<body>\n";
    print "<div style=\"width: 100%; font-size: 80px; font-weight: bold; text-align:center;\">\n";
    print "Nginx Perl Test Page in www.jhjeong.com";
    print "\n</div>\n";
    print "</body>\n</html>\n";
     
    3. FastCGI 서비스를 시작
    [root@master ~]# service perl-fcgi start
     
    4. 부팅 이후 자동으로 시작되게 설정
    [root@master ~]# chkconfig perl-fcgi on
     
    5. 모든 설정이 적용되록 서버를 다시 
    [root@master ~]# systemctl restart nginx
    cs



    3.2 CGI Python 사용 (Web Server Gateway Interface)

    두 번째 CGI로서 Perl보다 사용자에게 더 인기 있는 파이썬(Python)을 사용하는 방법을 설명하는데, 파이썬을 사용하기 위해 먼저 알아야 할 간단한 용어를 설명한다.

    - WSGI : 웹 서버와 애플리케이션 사이의 인터페이스를 정의한 파이썬의 규격

    - uWSGI : 웹 애플리케이션을 개발하고 전개하기 위해 필요한 모든 요소를 제공하는 파이썬 애플리케이선 서버

    - uwsgi uWSGI : 애플리케이션 서버가 Nginx와 같은 웹 서버와 통신하기 위해 사용하는 프로토콜 이름


    a. uWSGI 설치와 테스트

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    1. yum을 사용해 파이썬 패키지 매니저 pip를 설치한다.
    [root@master ~]# yum install python-pip python-devel -y 
    [root@master ~]# yum groupinstall "Development Tools"
     
    2. pip을 사용해 파이썬 개발 환경을 사용할 수 있는 virtualenv 패키지를 설치한다.
    [root@master ~]# pip install virtualenv
     
    3. 파이썬 개발을 위해 사용할 디렉토리를 생성하고 이동한다.
    [root@master ~]# mkdir /opt/myproject
    [root@master ~]# cd /opt/myproject/
     
    4. virtualenv를 사용해 파이썬이 사용할 가상 환경을 env 이름으로 생성한다. 
    [root@master myproject]# virtualenv env
    New python executable in /opt/myproject/env/bin/python2
    Also creating executable in /opt/myproject/env/bin/python
    Installing setuptools, pip, wheel...done.
     
    5. 생성된 디렉토리를 확인
    [root@master myproject]# ls -l env/
    total 4
    drwxr-xr-x. 2 root root 248 May 13 18:28 bin
    drwxr-xr-x. 2 root root  23 May 13 18:28 include
    drwxr-xr-x. 3 root root  23 May 13 18:28 lib
    lrwxrwxrwx. 1 root root   3 May 13 18:28 lib64 -> lib
    -rw-r--r--1 root root  61 May 13 18:28 pip-selfcheck.json
     
    6. source를 사용해 이 가상 환경을 활성화한다. 
    [root@master myproject]# source env/bin/activate
     
     
    7. 파이썬 애플리케이션 서버로서 uWSGI 서버를 pip로 설치
    (env) [root@master myproject]# pip install uwsgi
    Collecting uwsgi
      Using cached https://files.pythonhosted.org/packages/98/b2/19b34b20662d111f7d2f926cdf10e13381761dd7dbd10666b9076cbdcd22/uwsgi-2.0.17.tar.gz
    Building wheels for collected packages: uwsgi
      Running setup.py bdist_wheel for uwsgi ... done
      Stored in directory: /root/.cache/pip/wheels/b9/31/54/2a68867224e983447b0194939a3905be99ee306fb159912110
    Successfully built uwsgi
    Installing collected packages: uwsgi
    Successfully installed uwsgi-2.0.17
     
    8. 설치한 uWSGI 서버의 버전 정보를 확인
    (env) [root@master myproject]# uwsgi -version
    *** Starting uWSGI 2.0.17 (64bit) on [Sun May 13 18:47:25 2018***
     
    9. 이 개발 환경에서 빠져나오기 위해 사용
    (env) [root@master myproject]# deactivate
     
    10. 파이썬 애플리케이션 테스트를 위해 파일을 생성
    [root@master myproject]# vim wsgi.py
    def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return ["<h1 style='color:blue'>UWSGI Testing Success!</h1>"]
     
    11. uWSGI 서버 테스트를 위해 프로토콜 HTTP를 사용해 위에서 생성한 애플리케이션 wsgi를 서버의 포트 8080번에서 사용하기
    설정하고 시작한다. 여기서 IP 0.0.0.0은 서버가 사용하는 모든 IP 주소로의 접속을 허용하기 위해 사용한다.
    (env) [root@master myproject]# uwsgi --socket 0.0.0.0:8080 --protocol=http -w wsgi
    *** Starting uWSGI 2.0.17 (64bit) on [Sun May 13 19:13:53 2018***
    compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-28) on 13 May 2018 18:46:31
    os: Linux-3.10.0-862.2.3.el7.x86_64 #1 SMP Wed May 9 18:05:47 UTC 2018
    nodename: master.chul.com
    machine: x86_64
    clock source: unix
    detected number of CPU cores: 1
    current working directory: /opt/myproject
    detected binary path: /opt/myproject/env/bin/uwsgi
    !!! no internal routing support, rebuild with pcre support !!!
    uWSGI running as root, you can use --uid/--gid/--chroot options
    *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
    *** WARNING: you are running uWSGI without its master process manager ***
    your processes number limit is 1856
    your memory page size is 4096 bytes
    detected max file descriptor number: 1024
    lock engine: pthread robust mutexes
    thunder lock: disabled (you can enable it with --thunder-lock)
    uwsgi socket 0 bound to TCP address 0.0.0.0:8080 fd 3
    uWSGI running as root, you can use --uid/--gid/--chroot options
    *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
    Python version: 2.7.5 (default, Apr 11 201807:36:10)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
    ...
    *** Operational MODE: single process ***
    WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1876910 pid: 13818 (default app)
    uWSGI running as root, you can use --uid/--gid/--chroot options
    *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
    *** uWSGI is running in multiple interpreter mode ***
    spawned uWSGI worker 1 (and the only) (pid: 13818, cores: 1)
    [pid: 13818|app: 0|req: 1/1192.168.80.1 () {34 vars in 649 bytes} [Sun May 13 19:13:55 2018] GET / => generated 50 bytes in 0 msecs (HTTP/1.1 2001 headers in 44 bytes (1 switches on core 0)
    [pid: 13818|app: 0|req: 2/2192.168.80.1 () {36 vars in 653 bytes} [Sun May 13 19:13:55 2018] GET /favicon.ico => generated 50 bytes in 0 msecs (HTTP/1.1 2001 headers in 44 bytes (1 switches on core 0)
    cs


    테스트를 위해 브라우저에서 http://192.168.80.5:8080 포트에 접속하면 아래와 같이 wsgi.py에 입력된 내용이 출력된다.


    b. uWSGI 서버 자동화

    uWSGI 서버를 사용하기 위해 수동으로 서비스를 시작했지만, 다음과 같은 설정 파일을 생성해 서비스를 자동으로 시작할 수 있다. 또한 Nginx 서버에서 이를 사용하기 위한 설정도 필요하다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    1. uwsgi 서비스가 사용할 설정 파일을  ㅐㅇ성
    [root@master myproject]# vim myproject.ini
    [uwsgi]
    module = wsgi:application
    master = true
    processes = 4
    uid = nginx
    socket = /run/uwsgi/myproject.sock    # 서비스가 시작할 때 생성되는 소켓 위치 지정
    chown-socket = nginx    # 디렉토리에 사용자 nginx가 접근 가능하기 설정
    chmod-socket = 660
    vcauum = true
    die-on-term = true
     
    2. uwsgi 서비스 자동 시작을 위해 사용할 서비스 파일을 생성
    [root@master myproject]# vim /etc/systemd/system/uwsgi.service
    [Unit]
    Description=uWSGI Emperor service
    After=syslog.target
     
    [Service]
    # uwsgi 서비스가 시작되기 전에 소켓을 저장할 디렉토리를 생성하고 그 소유권자를 nginx로 설정하도록 정의
    ExecStartPre=-/usr/bin/bash -'mkdir -p /run/uwsgi; chown nginx /run/uwsgi'
    # uwsgi 서비스가 시작될 때 파이썬 프로젝트 디렉토리로 이동해서 그 환경을 활성화하고 설정 파일을 사용해 uwsgi가 시작하도록 정의
    ExecStart=/usr/bin/bash -'cd /opt/myproject; source env/bin/activate; uwsgi --ini myproject.ini'
    Restart=always
    KillSignal=SIGQUIT
    Type=notify
    NotifyAccess=all
    StandardError=syslog
     
    [Install]
    WantedBy=multi-user.target
     
    3. 새로 생성한 uwsgi.service가 적용되도록 systemd 데몬을 다시 시작한 후에 uwsgi 서비스를 명령어로 시작
    [root@master ~]# systemctl daemon-reload
    [root@master ~]# systemctl start uwsgi
     
    4. systemctl을 사용해 상태를 확인하고 설정 파일에서 정의한 대로 4개의 worker 프로세스가 생성된 것을 확인
    [root@master ~]# systemctl status uwsgi
    ● uwsgi.service - uWSGI Emperor service
       Loaded: loaded (/etc/systemd/system/uwsgi.service; disabled; vendor preset: disabled)
       Active: active (running) since Mon 2018-05-14 17:04:21 UTC; 5s ago
      Process: 4442 ExecStartPre=/usr/bin/bash -c mkdir -/run/uwsgi; chown nginx /run/uwsgi (code=exited, status=0/SUCCESS)
     Main PID: 4445 (bash)
       Status: "uWSGI is ready"
       CGroup: /system.slice/uwsgi.service
               ├─4445 /usr/bin/bash -c cd /opt/myproject; source env/bin/activate; uwsgi --ini myproject.ini
               ├─4449 uwsgi --ini myproject.ini
               ├─4450 uwsgi --ini myproject.ini
               ├─4451 uwsgi --ini myproject.ini
               ├─4452 uwsgi --ini myproject.ini
               └─4453 uwsgi --ini myproject.ini
    May 14 17:04:21 master.chul.com bash[4445]: mapped 364520 bytes (355 KB) for 4 cores
    May 14 17:04:21 master.chul.com bash[4445]: *** Operational MODE: preforking ***
    May 14 17:04:21 master.chul.com bash[4445]: WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x22d03b0 p...t app)
    May 14 17:04:21 master.chul.com bash[4445]: *** uWSGI is running in multiple interpreter mode ***
    May 14 17:04:21 master.chul.com bash[4445]: spawned uWSGI master process (pid: 4449)
    May 14 17:04:21 master.chul.com bash[4445]: spawned uWSGI worker 1 (pid: 4450, cores: 1)
    May 14 17:04:21 master.chul.com bash[4445]: spawned uWSGI worker 2 (pid: 4451, cores: 1)
    May 14 17:04:21 master.chul.com bash[4445]: spawned uWSGI worker 3 (pid: 4452, cores: 1)
    May 14 17:04:21 master.chul.com bash[4445]: spawned uWSGI worker 4 (pid: 4453, cores: 1)
    May 14 17:04:21 master.chul.com systemd[1]: Started uWSGI Emperor service.
    Hint: Some lines were ellipsized, use -l to show in full.
     
    5. 서비스가 부팅 후에도 자동으로 시작되게 설정
    [root@master ~]# systemctl enable uwsgi
    Created symlink from /etc/systemd/system/multi-user.target.wants/uwsgi.service to /etc/systemd/system/uwsgi.service.
     
    6. nginx 서버 설정 파일을 열어서 기본 루트 도메인에 
    [root@master ~]# vim /etc/nginx/nginx.conf
            location / {
                include uwsgi_params;    # uwsgi 파라미터를 포함하고 
                # nginx 서버가 제공하는 기본 도메인으로 클라이언트가 접속하면 그 요청을 uwsgi의 소켓으로 보내라는 의미
                # 즉, 기본 도메인으로 접속하는 사용자들에게 uwsgi가 제공하는 파이썬 어플리케이션 파일의 내용을 출력하라는 의미
                uwsgi_pass unix:/run/uwsgi/myproject.sock;    
            }
     
    7. nginx 설정 파일의 문법 검사
    [root@master ~]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
     
    8. nginx 서버를 재시작
    [root@master ~]# systemctl restart nginx
    cs


    c. 테스트

    브라우저에서 서버의 도메인 또는 IP 주소로 접속하면 파이썬 어플리케이션 파일에 저장된 텍스트를 확인할 수 있다.



    3.3 루비온레일즈 사용

    세 번째 CGI로서 루비(Ruby)를 사용하는 방법을 설명하면 다음과 같다. 여기에선 루비온레일즈를 사용하는데, 이는 루비 언어를 사용해 동적인 웹 애플리케이션을 구현하기 위해 사용되는 웹 어플리케이션 개발 프레임워크다. 


    클라이언트 <=> Nginx 서버 <=> Unicorn <=> Rails 서버 <=> Ruby 파일


    웹 클라이언트가 웹 서버 Nginx 서버에게 루비로 작성된 애플리케이션을 요청하면 Nginx 서버는 이를 유니콘(Unicorn)에 전달하고 다시 이 요청은 Rails 서버에 전달돼 이 서버는 루비로 작성된 애플리케이션을 찾아 클라이언트에 응답하게 된다. 


    a. 패키지 설치

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    1. 루비를 다운로드하고 설치하기 위해 루비 버전 매니저로 사용되는 RVM(Ruby Version Manager)를 먼저 다운로드하기 위해 
    필요한 gpg 키를 설치한다. 이 키가 없으면  RVM이 정상적으로 설치되지 않는다. 
    [root@master ~]# gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
     
    2. 서버에서 데이터를 직접 전송하는 명령어 curl을 사용하면 RVM을 다운로드해서 설치하고 루비를 위한 시스템 환경을 생성한다.
    [root@master ~]# curl -L get.rvm.io | bash -s stable
     
    3. RVM을 설치하면 이 디렉토리에 모두 저장되는데, 명령어 source를 사용해 RVM의 스크립트 파일을 실행 가능하게 변경한다.
    이 명령어를 사용하지 않으면 RVM이 이 디렉토리에서 제공하는 명령어들을 사용할 수 없다.
    [root@master ~]# source /usr/local/rvm/scripts/rvm
     
    4. 명령어 rvm을 다시 시작하고
    [root@master ~]# rvm reload
    RVM reloaded!
     
    5. rvm을 이용해 루비 버전을 명시해서 설치한다.
    [root@master ~]# rvm install 2.3.0
     
    6. 루비 설치가 완료되면 그 버전 정보를 확인
    [root@master ~]# ruby -v
    ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
     
    7. 루비가 사용하는 라이브러리 관리 명령어 gem을 사용해 Rails와 의존 관계에 있는 bundler 패키지를 함께 설치
    [root@master ~]# gem install bundler rails
    Successfully installed bundler-1.16.1
    Parsing documentation for bundler-1.16.1
    Done installing documentation for bundler after 3 seconds
    Successfully installed rails-5.2.0
    Parsing documentation for rails-5.2.0
    Done installing documentation for rails after 0 seconds
    2 gems installed
     
    8. Rails 설치 후에 버전 정보를 확인한다.
    [root@master ~]# rails -v
    Rails 5.2.0
    cs


    b. Rails 서버 시작

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    1. rails가 애플리케이션 개발을 위해 사용할 디렉토리를 생성하고 그 디렉토리로 이동한 후에
    [root@master ~]# mkdir /opt/ruby
    [root@master ~]# cd /opt/ruby/
     
    2. 루비에서 Mysql or Mariadb 연결을 위해 사용할 패키지를 설치하기 위해 MariaDB 패키지를 설치하고 gem을 이용해 mysql2와 
    그 버전을 지정해서 설치한다. 버전을 지정하지 않으면 입력하라는 메시지를 볼 수 있다.
    [root@master ruby]# yum install mariadb-devel
    [root@master ruby]# gem install mysql2 -v '0.4.4'
    1 gem installed
     
    3. rails를 사용해 새로운 프로젝트 이름 SampleApp을 테스트를 위해 생성하는데, 이때 데이터베이스 MySQL을 사용한다.
    [root@master ruby]# rails new SampleApp -d mysql
    [root@master ruby]# cd SampleApp/
     
    4. rails가 사용할 데이터베이스 정보 수정을 하는데, 이 정보는 MariaDB 서버 접속 시의 사용자 패스워드, 소켓 위치를 의미
    [root@master SampleApp]# vim config/database.yml
    default: &default
      adapter: mysql2
      encoding: utf8
      pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
      username: root
      password: password
      socket: /var/lib/mysql/mysql.sock
     
    5. rails를 사용해 데이터베이스 생성
    [root@master SampleApp]# rails db:create
    Created database 'SampleApp_development'
    Created database 'SampleApp_test'
     
    6. rails를 사용해 테스트용 testapp 애플리케이션을 생성하는데, 이 애플리케이션은 name, title, body라는 세 가지 입력 상자로 구성돼 있고
    각각 텍스트를 입력할 수 있다. scaffold 옵션은 testapp에 대한 모델과 컨트롤러, views를 SamplApp/app 디렉토리에 동시에 생성해준다.
    [root@master SampleApp]# rails generate scaffold testapp name:string
    title:string body:text
     
    7. 현재 생성된 개발 환경에서 마이그레이션 작업을 실행해 기본 테이블을 생성
    [root@master SampleApp]# rails db:migrate
     
    8. rails 서버는 포트 3000번을 기본으로 시작되고, 브라우저에서 rails 서버로 접속할 수 있다. 서버를 멈추려면 Ctrl_C를 이용한다.
    [root@master SampleApp]# rails server --bindig=0.0.0.0
    => Booting Puma
    => Rails 5.2.0 application starting in development on http://0.0.0.03000
    cs

    설정한 Rails가 잘 동작하는지 테스트는 IP 주소와 포트 번호 http://192.168.80.5:3000/을  이용해 접속하면 된다.


    c. Unicorn과 Nginx 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    1. gem을 사용해 unicorn 패키지를 설치한다.
    [root@master SampleApp]# gem install unicorn
     
    2. Unicorn의 환경을 설정할 파일을 생성하는데, 개발 디렉토리, 프로세스 이름, 로그 파일, 소켓 파일, 프로세스 개수 및 타임아웃 정보 입력
    [root@master SampleApp]# vim config/unicorn.rb
    working_directory "/opt/ruby/SampleApp"
    pid "/opt/ruby/SampleApp/pids/unicorn.pid"
    stderr_path "/opt/ruby/SampleApp/log/unicorn.log"
    stdout_path "/opt/ruby/SampleApp/log/unicorn.log"
    listen "/opt/ruby/SampleApp/pids/unicorn.myapp.sock"
    work_processes 4
    timeout 30
    [root@master SampleApp]# mkdir pids
     
    3. 테스트를 위해 Unicorn를 시작하면 기본적으로 서버의 IP주소와 포트 8080번에서 확인할 수 있다. 
    [root@master SampleApp]# unicorn_rails
    I, [2018-05-15T20:09:05.629525 #22338]  INFO -- : listening on addr=0.0.0.0:8080 fd=12
    I, [2018-05-15T20:09:05.629666 #22338]  INFO -- : worker=0 spawning...
    I, [2018-05-15T20:09:05.630360 #22338]  INFO -- : master process ready
    I, [2018-05-15T20:09:05.631125 #22340]  INFO -- : worker=0 spawned pid=22340
     
    4. Nginx 서버의 설정을 위해 파일을 열어서
    [root@master SampleApp]# vi /etc/nginx/nginx.conf
            # 지시어 upstream을 사용해 "http:app;"에서 정의한 디렉토리로 오는 모든 요청을 아래 줄의 
            upstream app {
                    # unicorn 소켓으로 보내 처리하라는 의미다. fail_timeout=0은 소켓으로부터 유효한 응답이 올때까지 시도
                    server unix:/opt/ruby/SampleApp/pids/unicorn.myapp.sock fail_timeout=0;
            }
     
        server {
            listen       80;
            server_name  www.jeong.com;
            # Rails 서버가 사용하는 애플리케이션 디렉토리로 변경한다. 
            root /opt/ruby/SampleApp/public;
            # 클라이언트가 이 도메인으로 접속을 시도하면 위에서 정의한 디렉토리를 찾고, 찾으면 @app으로 보내라는 의미다. (@는 디렉토리 검색)
            try_files $uri/index.html $uri @app;
     
            # 위에서 정의한 디렉토리 이름인데, 이 디렉토리로 오는 요청을
            location @app {
                # Nginx 서버가 프록시로서 그 요청을 upstream에서 정의한 이름으로 보내라는 의미다. 유효한 디렉토리를 
                # 클라이언트가  요청하면 SampleApp 디렉토리에 저장된 애플리케이션이 응답하게 된다. 
                proxy_pass http://app;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
            }
    5. Unicorn 설정 파일을 사용해 데몬 모드로 시작하고 그 프로세스를 확인한다.
    [root@master SampleApp]# unicorn_rails -c config/unicorn.rb -D
    cs



    3.4 Ghost 설치

    Apache 서버에서 블로그 서비스를 제공하는 CMS WordPress를 설치하는 방법이 있는데, Ghost도 자바스크립트로 작성된 오픈소스 블로그 프로그램으로서 자바스크립트 플랫폼인 Node.js 기반에서 사용할 수 있다. Ghost는 온라인에서 개인 사용자들이 쉽게 블로그 서비스를 제공하기 위해 디자인된 무료 프로그램이다.


    a. Ghost 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    1. 자바스크립트를 사용하기 위해 nodejs와 그 패키지 관리 프로그램 npm을 설치한다.
    [root@master ~]# yum install nodejs npm -y
     
    2. Node.js 애플리케이션을 제어할 프로세스 매니저 pm2를 설치하는데, -g 옵션은 Global의 의미로서 현재 버전을 설치
    [root@master ~]# npm install pm2 -g
     
    3. Ghost를 설치할 디렉토리를 생성하고 이동
    [root@master ~]# mkdir /var/www/html/jeong
    [root@master ~]# cd /var/www/html/jeong/

    [root@master ~]# cp config.example.js config.js
    url : 'http://www.jeong.com',
     
    4. Ghost 최신 소스 파일을 다운로드
    [root@master jeong]# curl -L https://ghost.org/zip/ghost-latest.zip -o ghost.zip
     
    5. 압축 해제 후 소스 파일 삭제
    [root@master jeong]# unzip ghost.zip
    [root@master jeong]# rm ghost.zip
     
    6. npm을 사용해 설치
    [root@master jeong]# npm install -prodecution
     
    7. 프로세스 매니저 pm2을 사용해 기본 인덱스 파일과 함께 Ghost 서비스를 시작하는데, 콘솔을 닫거나 셸을 빠져 나가도 
    계속 실행되도록 NODE_ENV 변수를 사용한다.
    [root@master jeong]# NODE_ENV=production pm2 start index.js --name "Ghost"
                           -------------
    __/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
     _\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
      _\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
       _\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
        _\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
         _\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
          _\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
           _\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
            _\///______________\///______________\///__\///////////////__
     
    [PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
    [PM2] PM2 Successfully daemonized
    [PM2] Starting /var/www/html/jeong/index.js in fork_mode (1 instance)
    [PM2] Done.
    ┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
    │ App name │ id │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
    ├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
    │ Ghost    │ 0  │ fork │ 27165 │ online │ 0       │ 0s     │ 3%  │ 14.0 MB   │ root │ disabled │
     
    8. Ghost 서비스를 시작할 경우 사용
    [root@master jeong]# pm2 start Ghost
     
    9. 8. Ghost 서비스를 시작할 재시작 할 경우 사용
    [root@master jeong]# pm2 restart Ghost

    dcs


    b. Nginx 서버 설정

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    [root@master jeong]# vi /etc/nginx/nginx.conf
        # 지시어 upstream을 사용해 그 이름을 지정하고, 어떤 요청이 이 지시어로 들어오면 그 요청을 로컬 호스트의 
        # Ghost가 사용하는 포트 2368번으로 보내라는 의미다. 
        upstream ghost {
            server 127.0.0.1:2368;
            }
     
        server {
            listen       80 default_server;
            #listen       [::]:80 default_server;
            server_name  www.chul.com;
            root         /usr/share/nginx/html;
     
            # Load configuration files for the default server block.
            include /etc/nginx/default.d/*.conf;
     
            location / {
                # 사용자가 기본 도메인으로 접속하면 upstream에서 설정한 ghost로 보내라는 의미다.
                 proxy_pass http://ghost;
                 proxy_next_upstream error timeout invalid_header http_500;
                 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;
                 proxy_set_header   X-Forwarded-Proto https;
            }
     
    [root@master jeong]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
     
    [root@master jeong]# systemctl restart nginx
    cs


    c. Ghost 테스트

    Ghost를 직접 브라우저에서 접속해 보면, 기본 도메인이나 서버의 IP 주소로 접속하면 Ghost의 초기 화면을 볼 수 있다.

    댓글

작은거인's Blog / Designed by TISTORY