내용으로 건너뛰기
GaramX
사용자 도구
로그인
사이트 도구
검색
도구
문서 보기
이전 판
역링크
최근 바뀜
미디어 관리자
사이트맵
로그인
>
최근 바뀜
미디어 관리자
사이트맵
현재 위치:
home
»
linux
»
django
»
ubuntu
»
uwsgi
추적:
linux:django:ubuntu:uwsgi
이 문서는 읽기 전용입니다. 원본을 볼 수는 있지만 바꿀 수는 없습니다. 문제가 있다고 생각하면 관리자에게 문의하세요.
====== Ubuntu 24.04 에서 uWSGI와 아파치 ====== 가상환경 <code bash> python3 -m venv maroenv </code> ===== uWSGI ===== [[http://uwsgi-docs.readthedocs.io/en/latest/|공식페이지]] WSGI란 Web Server Gateway Interface의 약자로, 웹서버와 웹어플리케이션이 어떤 방식으로 통신하는가에 관한 인터페이스를 의미, 이 WSGI 규격에 맞춘 코드를 실행해주는 프로그램이 uWSGI임. 이 외에 Gunicorn 같은 프로그램 또한 WSGI 규격 웹 애플리케이션을 배포할 때 쓰임 * 환경 변수를 적절히 변경하여 대상 URL에 따라 다른 애플리케이션 개체에 요청을 라우팅 * 동일한 프로세스에서 여러 애플리케이션 또는 프레임워크를 나란히 실행할 수 있도록 허용 * 네트워크를 통해 요청 및 응답을 전달하여 로드 밸런싱 및 원격 처리 * XSLT스타일을 적용하는 등의 콘텐츠 처리 수행 ==== uWSGI 설치 ==== build-essential gcc <code bash> apt install uwsgi sudo apt-get install uwsgi-plugin-python3 </code> ==== uWSGI 실행 ==== 서버 실행은 uwsgi 명령어를 통해 실행 가능하지만 간단한 스크립트를 만들어 실행해 보자. /etc/init 디렉토리에 있는 선언적 구성 파일을 기반으로 실행한다 === simple script (/etc/init/uwsgi.conf) === <code bash> # simple uWSGI script description "uwsgi tiny instance" start on runlevel [2345] stop on runlevel [06] respawn exec uwsgi --master --processes 4 --die-on-term --socket :3031 --wsgi-file /var/www/myapp.wsgi </code> ==== uWSGI 설정 ==== <code> uWSGI는 여러가지 포맷(ini,xml, yaml, json)을 지원한다. uwsgi --ini http://uwsgi.it/configs/myapp.ini # HTTP uwsgi --xml - # standard input uwsgi --yaml fd://0 # file descriptor uwsgi --json 'exec://nc 192.168.11.2:33000' # arbitrary executable </code> <code> .INI 파일은 많은 응용 프로그램에서 사용되는 사실상 표준 구성 형식이다. [section] key = value 쌍으로 구성된다. [uwsgi] socket = /tmp/uwsgi.sock socket = 127.0.0.1:8000 workers = 3 master = true 기본적으로 uWSGI는 [uwsgi] 섹션을 사용하지만 filename : section 구문과 함께 INI 파일을 로드하는 동안 다른 섹션 이름을 지정할 수 있다. uwsgi--ini myconf.ini:app1 </code> ==== 로깅 ==== <code> uWSGI에서 가장 기본적인 형태의 로깅은 요청, 오류 및 정보 메시지를 stdout / stderr 으로 생성한다. 로그 리다이렉션의 가장 기본적인 형태는 --logto / --logto2 / --daemonize 옵션으로, 로그를 파일로 정할 수 있다. ./uwsgi -s :3031 -w simple_app --daemonize /tmp/mylog.log ./uwsgi -s :3031 -w simple_app --logto /tmp/mylog.log ./uwsgi -s :3031 -w simple_app --uid 1001 --gid 1002 --logto2 /tmp/mylog.log stdout / stderr 대신 파일에 기록하려면 --logto를 사용하거나 uWSGI, - daemonize를 동시에 데몬을 실행하면 된다. </code> 로그 포맷 <code> uWSGI에는 사용자 정의 요청 로그 라인을 작성하기 위한 --logformat 옵션이 있다. • %(uri) -> REQUEST_URI • %(method) -> REQUEST_METHOD • %(user) -> REMOTE_USER • %(addr) -> REMOTE_ADDR • %(host) -> HTTP_HOST • %(proto) -> SERVER_PROTOCOL • %(uagent) -> HTTP_USER_AGENT (starting from 1.4.5) • %(referer) -> HTTP_REFERER (starting from 1.4.5) 다음 로그 형식을 사용하면 코드 정의 logvars에 액세스 할 수 있다. uwsgi --logformat 'worker id = %(worker_id) for request "%(method) %(uri) %(proto)" test = %(foo)' </code> ==== Python + Apache mod_wsgi 연동 ==== === Apache mod_wsgi란? === mod_wsgi의 목적은 Python WSGI 인터페이스를 지원하는 Python 응용 프로그램을 호스팅 할 수 있는 간 단한 ApacheModule을 구현하는 것이다. 이 모듈은 웹 호스팅 서비스에서 실행되는 고성능 운영 사이트뿐 만 아니라 고성능 프로덕션 웹 사이트 호스팅에도 사용하기에 적합하다. 지원 가능한 웹프레임워크 및 어플리케이션 * CherryPy * Django * Pylons * TurboGears * Pyramid * web.py * Werkzeug * Web2Py and Zope. === 아파치 설치 === <code bash> # apt-get install apache2 # apt-get install libapache2-mod-wsgi-py3 </code> === 아파치 wsgi 설정 === <code conf /etc/apache2/conf-available/wsgi.conf> WSGIScriptAlias /test_wsgi /var/www/html/test_wsgi.py </code> === 아파치 wsgi 설정 === $ a2enconf wsgi $ systemctl restart apache2 === test_wsgi.py 생성 === <code pyton /var/www/html/test_wsgi.py> # create new def application(environ,start_response): status = '200 OK' html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'mod_wsgi Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' response_header = [('Content-type','text/html')] start_response(status,response_header) return [html] </code> === test_wsgi 페이지 확인 === 웹브라우저에서 http://localhost/test_wsgi 접속하여 확인한다. ==== Apache mode_wsgi + Django 연동 ==== === 사전 환경 구축 === * virtualenv 설치 * django 설치 * Apache2 설치 * mod_wsgi 설치 === Django란? === Django는 안전하고 유지 관리 가능한 웹 사이트를 신속하게 개발할 수 있는 고차원적인 Python 기반 웹 프레임워크이다. 경험이 풍부한 개발자들에 의해 구축된 장고(Django)는 웹 개발의 번거로움을 해소할 수 있도록 하기 위해 고안되었다. 자유롭고 개방적이며 활발한 커뮤니티를 보유하고 있으며, 우수한 문서 및 유료 지원을 위한 다양한 옵션을 갖추고 있다. === virtualenv 설치 === 가상 작업환경인 virtualenv를 설치한다. <code bash> root@www:~# apt-get -y install python-virtualenv </code> === virtualenv 설정 === <code bash> ubuntu@www:~$ virtualenv venv # virtualenv 생성 ubuntu@www:~$ cd ~/venv ubuntu@www:~/venv$ source bin/activate (venv)ubuntu@www:~/venv$ pip install -U pip (venv)ubuntu@www:~/venv$ pip install django #django 설치 </code> === 테스트 프로젝트 생성 === <code bash> Ubuntu@www:~$ cd ~/venv Ubuntu@www:~/venv$ source bin/activate # create “testproject” (venv)ubuntu@www:~/venv$ django-admin startproject testproject (venv)ubuntu@www:~/venv$ cd testproject </code> === 데이터베이스 설정(SQLite) === <code bash> # configure database (default is SQLite) (venv)ubuntu@www:~/venv/testproject$ python manage.py migrate # create admin user (venv)ubuntu@www:~/venv/testproject$ python manage.py createsuperuser </code> === 서버 실행 === <code bash> # start server venv)ubuntu@www:~/venv/testproject$ python manage.py runserver 0.0.0.0:8000 </code> === Apache mode_wsgi + Django 연동 === views.py 작성 <code python testapp/views.py> # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def main(request): html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'Django Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' return HttpRestponse(html) # Create your views here. </code> <code python urls.py> """testproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('test app.urls')), ] </code> <code python testapp/urls.py> from django.conf.urls import url from . import views urlpatterns = [ url(r'^testapp/$', views.main, name='main'), ] </code> <code python testproject/settings.py> # add testapp like follows INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp', #추가 ) </code> ==== Apache mod_wsgi 설정 ==== Django Test page까지 확인했으면 이제 Apache mod_wsgi와 Django를 연동해본다. 연동을 위해 django.conf 파일을 생성하여 설정한다. <code conf /etc/apache2/conf-available/django.conf> # create new WSGIDaemonProcess test app python-path=/home/ubuntu/venv/testproject:/home/ubuntu/venv/lib/python2.7/site-packages WSGIProcessGroup test app WSGIScriptAlias /django /home/ubuntu/venv/testproject/wsgi.py <Directory /home/ubuntu/venv/testproject> Require all granted </Directory> </code> === Apache 재구동 === <code bash> root@www:~# a2enconf wsgi root@www:~# systemctl restart apache2 </code>
linux/django/ubuntu/uwsgi.txt
· 마지막으로 수정됨: 2025/04/19 03:49 저자
taekgu
문서 도구
문서 보기
이전 판
역링크
맨 위로