ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Flask, Gunicorn, Nginx, EC2 Ubuntu Server 5] Gunicorn & Nginx
    Development Note/H891: YouTube Playlist Application 2023. 12. 30. 01:47

    지난번에는 git을 설치하고, ssh 세팅을 완료했다.

     

    Flask 서버를 돌리면, 이런 메세지가 빨간색으로 나온다.

     

    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

    WSGI 서버를 사용하라는 경고이다. 왜일까?

     

    Request(요청)이 많아지면, 서버에는 병목 현상이 생기게 된다. gunicorn과 같은 WSGI는 여러개의 Thread를 생성해서 요청을 병렬로 처리해주기 때문에, 여러 유저가 플레이리스트 생성을 동시에 요청했을 때, 기본 flask서버를 사용할때마다, 뛰어난 성능으로 대응할 수 있다.

     

    그렇다면 nginx는 왜 사용하나? 이 nginx는 Web Server 또는 Proxy Server역할을 맡는다. 사용자가 내 서비스에 연결하려고 하면, 내 서버에 직접 연결하는게 아니라, Proxy 서버인 nginx가 요청을 받아서 내 서버에 연결을 해서 다시 client에 response를 전달해주는 식이다. 

     

    정리해보자면,

    1. 클라이언트가 요청을 보내면 Nginx가 그 요청을 받는다.

    2. unix socket을 이용해서 nginx와 gunicorn(uwsgi)이 연결된다.

    3. flask 앱이 실행되고, response가 gunicorn으로 전달된다.

    4. nginx가 그 response를 받아서, 외부 클라이언트에게 response를 전달한다.

     

    Gunicorn

    자, 그럼 이제 설치해준다.

    # gunicorn 설치
    pip install gunicorn

     

    gunicorn이 잘 설치 되었는지 확인해보자.

    gunicorn -b 0.0.0.0:5000 youtube_api:app

     

    gunicorn이 컴퓨터가 재부팅 하더라도 작동할 수 있도록 설정해보자. systemd를 사용해본다.

     

    systemd는 Linux의 부팅 관리자로서, EC2 인스턴스가 재시작하거나 다른 이유로 재부팅해야 할 경우 Gunicorn을 관리하는 데 사용된다. /etc/systemd/system 폴더에 .service 파일을 생성하고 시스템 재부팅 시 Gunicorn에 대한 동작을 지정한다. service 파일에는 다음 세 부분을 추가하게 됩니다.

    • Unit (단위): 이 섹션은 프로젝트에 대한 설명과 일부 종속성(dependencies) 정보를 포함한다.
    • Service (서비스): 이 부분에서는 어떤 사용자/그룹에서 이 서비스를 실행할 것인지 지정한다. 또한 실행 파일과 명령어에 대한 정보도 제공한다.
    • Install (설치): 이 부분은 systemd에게 부팅 프로세스 중 언제 이 서비스를 시작할지 알려준다.

    이렇게 /etc/systemd/system 디렉토리에 단위 파일(unit file)을 생성하면, systemd를 사용하여 Gunicorn 서비스를 시작, 중지 및 관리할 수 있게 된다.

     

    sudo vim /etc/systemd/system/ytapi.service

     

    그리고 아래 내용을 파일에 쓰고 저장한다.

    [Unit]
    Description=Gunicorn instance for h891 YouTube API
    After=network.target
    [Service]
    User=ubuntu
    Group=www-data
    WorkingDirectory=/home/ubuntu/h891-youtube-api
    ExecStart=/home/ubuntu/h891-youtube-api/venv/bin/gunicorn -b 0.0.0.0:5000 youtube_api:app
    Restart=always
    [Install]
    WantedBy=multi-user.target

     

    이제, 이 서비스를 enable 시켜보자.

    sudo systemctl daemon-reload
    sudo systemctl start ytapi
    sudo systemctl enable ytapi

     

    이제 이 앱이 잘 돌아가는지 확인해보자

    curl localhost:5000

     

    아주 잘 된다!

    (venv) ubuntu@ip-172-31-34-15:~/h891-youtube-api$ curl localhost:5000
    https://www.youtube.com/playlist?list=PL_A2Ex0h1WChzcMQoWfryIQ2Mdj9PAARl

     

     

     

    Nginx

    이제 Nginx를 설치해보자!

    sudo apt-get install nginx

     

    이제 nginx 서버를 실행하고,

    sudo systemctl start nginx
    sudo systemctl enable nginx

     

    default 세팅을 조금 변경해보자.

    sudo vi /etc/nginx/sites-available/default

     

    맨위에 아래와 같이 추가해주고

    upstream flaskytapi {
    	server 127.0.0.1:5000;
    }

     

    그리고 location에 다음 라인을 추가해준다.

    location / {
        proxy_pass http://flaskytapi;
    }

     

    최종 파일은 다음과 같다.

    upstream flaskytapi {
    	server 127.0.0.1:5000;
    }
    # Default server configuration
    #
    server {
    	listen 80 default_server;
    	listen [::]:80 default_server;
        
    	root /var/www/html;
    
    	# Add index.php to the list if you are using PHP
    	index index.html index.htm index.nginx-debian.html;
    
    	server_name _;
    
    	location / {
    		# First attempt to serve request as file, then
    		# as directory, then fall back to displaying a 404.
    		proxy_pass http://flaskytapi;
    		try_files $uri $uri/ =404;
    	}
    }

     

    자 이제, nginx 서버를 재시작해보자.

    sudo systemctl restart nginx

     

    서버가 잘 도는지 확인해보자. 로컬 인터넷 창에서 아래처럼 publicIP:port 를 입력해보자.

    http://54.180.92.29:5000/

     

    잘 동작한다.

     

     

    이렇게 Python Flask, Gunicorn, 그리고 Nginx를 이용해서 YouTube API와 소통하는 서버를 띄웠다.

     

     

     

    참고: 해당 인스턴스는 이 글 작성 후 Terminate 시켰다.

    Reference

    https://blog.devgenius.io/serve-python-app-on-nginx-6bc57ceaed4c

    댓글

Designed by Tistory.