안녕세계

[Linux] Apache(CentOS)와 Django 연동 본문

[Linux] Apache(CentOS)와 Django 연동

Junhong Kim 2018. 4. 10. 18:28
728x90
반응형

Apache(CentOS)와 Django 연동

본 포스팅에서는 Apache Django를 연동하는 방법을 알아봅니다.

  • Linux: CentOS v7.4.1708
  • Web Server: Apache v2.4.6

1. Apache 설치

이미 설치하셨을 경우 Skip 하셔도 됩니다.

$ yum install httpd

ym 패키지 업데이트

$ yum update

Linux 개발환경 구성 (optional)

$ yum groupinstall "Development Tools"

2. pip 설치

yum으로 pip를 설치하려면 EPEL repository가 설치되어 있어야 합니다.

$ rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm $ yum install python-pip

pip 업그레이드

$ pip install --upgrade pip

3. django 설치

$ pip install django

4. mod_wsgi 설치

웹 서버에서 받은 요청을 django같은 python application으로 전달해주는 interface 역할을 하는 패키지입니다. django와 웹 서버(포스팅에서는 Apache) 연동을 위해 가장 많이 사용되는 패키지 중 하나입니다.

$ yum install mod_wsgi

5. django 프로젝트 생성 (또는 기존 django 프로젝트 가져오기)

apache django를 연동하기 위해 새로운 django 프로젝트를 생성합니다.
원하는 경로에서 다음 명령어를 실행해주세요. ㅡ 예제에서는 /opt디렉토리에 tutorial 장고 프로젝트 생성

$ cd /opt $ django-admin startproject tutorial

django 프로젝트 구조

/opt └── tutorial ├── tutorial │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py

6. Apache 설정

/etc/httpd/conf.d 디렉토리에 설정 파일을 생성합니다.

Note:
/etc/httpd/conf/httpd.conf 파일에 IncludeOptional 설정이 되어있어야합니다.
httpd.conf를 수정하지 않으셨다면 기본적으로 설정되어 있습니다.

설정 파일을 분리하지 않고 httpd.conf 파일에 설정 내용을 작성해도 되지만,
파일 관리가 쉽도록 conf.d 디렉토리에 설정 파일을 분리하는 것이 좋습니다.

$ vi /etc/httpd/conf.d/vhost.conf

vhost.conf 파일을 열어서 다음 내용을 작성합니다.

<VirtualHost *:80> ServerName localhost WSGIScriptAlias / /opt/tutorial/tutorial/wsgi.py WSGIDaemonProcess tutorial python-path=/opt/tutorial/tutorial <Directory /opt/tutorial/tutorial> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> </VirtualHost>
  • WSIGIScriptAlias: 요청 url의 / 아래 모든 요청은 /opt/tutorial/tutorial/wsgi.py를 호출합니다.
    • wsgi.py는 django 프로젝트 생성시 자동으로 생성됩니다.
    • wsgi.py 파일의 모든 접근 권한을 allow 합니다.
  • ServerName: 주 도메인(연결한 도메인 이름으로 이는 DNS에 연결되어 있어야합니다.)
  • ServerAlias: 부 도메인
  • ErrorLog: 에러 로그 경로
  • CustomLog: 접속 로그 경로
  • DocumentRoot: 홈 디렉토리 경로

Note:
jpg/png, JS, CSS 같은 static 파일이 있을 경우 conf 파일에 static 파일 경로 추가하여 쉽게 처리할 수 있습니다. django는 기본적으로 static 파일에 대한 접근을 허용하지 않으므로 따로 static 파일을 settings.py에 설정하여 관리합니다. 하지만, static 파일은 wsgi를 통해 django로 오지 않아도 되므로 static 파일은 웹서버에서 처리하는게 성능상 좋습니다.

아래와 같이 vhost.conf static 파일에 대한 설정을 해주면 됩니다.
static 파일을 저장할 디렉토리는 /opt/tutorial/tutorial/static/처럼 새로 만들어서 설정하시면 됩니다.

<VirtualHost *:80> ServerName localhost WSGIScriptAlias / /opt/tutorial/tutorial/wsgi.py WSGIDaemonProcess tutorial python-path=/opt/tutorial/tutorial <Directory /opt/tutorial/tutorial> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> Alias /static /opt/tutorial/tutorial/static/ <Directory /opt/tutorial/tutorial/static> Order allow,deny Allow from all </Directory> </VirtualHost>

django 프로젝트의 /opt/tutorial/tutorial/wsgi.py 파일을 수정해야합니다.

import os import sys from django.core.wsgi import get_wsgi_application path = '/opt/tutorial' if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tutorial.settings") application = get_wsgi_application()

Apahce를 재시작하여 설정 내용을 적용하세요.

# service httpd restart

웹 브라우저에 접속하면 아래 내용의 페이지가 출력됩니다.
이는 정상적으로 Apache가 실행되었다는 것을 말합니다.

Testing 123.. This page is used to test the proper operation of the Apache HTTP server after it has been installed. If you can read this page it means that this site is working properly. This server is powered by CentOS.



또는, 아래와 같은 퍼미션 에러가 발생할 수 있습니다.

Forbidden You don't have permission to access / on this server.

우리가 원하는건 장고 기본프로젝트의 It worked! 페이지입니다.
/etc/httpd/conf/httpd.conf 파일을 열어서 권한을 허용하도록 합시다.

<Directory /> AllowOverride none # Require all denied Require all granted </Directory>
  • 모든 요청 허가

    • Apache 2.2 configuration:
      Order allow,deny
      Allow from all

    • Apache 2.4 configuration:
      Require all granted

  • 모든 요청 거부

    • Apache 2.2 configuration:
      Order deny,allow
      Deny from all

    • Apache 2.4 configuration:
      Require all denied

Apache를 재시작하여 설정 내용을 적용하세요.

# service httpd restart

웹 브라우저에 IP 주소를 입력하고 접속하면 장고 기본 페이지가 잘 뜨는것을 확인하실 수 있습니다! 

Tip:
Apache로 웹 프로그래밍을 하다보면 에러 로그를 봐야하는 경우가 자주 생깁니다.
특히 운영 중인 서버인 경우 어떠한 에러들과 경고들이 있었는지 확인하고 문제를 해결하는 것이 중요합니다.

기본적으로 설정을 바꾸지 않은 Apache 서버의 로그 위치는 아래와 같습니다.

  • RHEL / Red Hat / CentOS / Fedora Linux Apache
    /var/log/httpd/error_log
  • Debian / Ubuntu Linux Apache
    /var/log/apache2/error.log
  • FreeBSD Apache
    /var/log/httpd-error.log

설정이 바뀌었을 경우에는 httpd.conf 파일을 찾아서 검색해보면 됩니다. 아래 3가지 위치 중 하나에 있을 확률이 높습니다.

grep ErrorLog /usr/local/etc/apache22/httpd.conf
grep ErrorLog /etc/apache2/apache2.conf
grep ErrorLog /etc/httpd/conf/httpd.conf

logs/error_log 인 경우 logs 디렉토리가 다른 곳으로 링크가 되어있는지 확인해보면 로그의 위치를 확인할 수 있습니다.

  • 로그 확인할 때 유용한 vi 단축키 2가지
    • :e 파일을 최신버전으로 새로고침
    • G 파일의 가장 아래로 이동

[참고]
http://bluese05.tistory.com/m/40
https://www.lesstif.com/pages/viewpage.action?pageId=22052913
https://www.lesstif.com/pages/viewpage.action?pageId=6979743
https://m.blog.naver.com/PostView.nhn?blogId=jskorl&logNo=220620346746&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F

http://develop.sunshiny.co.kr/960
http://bluese05.tistory.com/40
https://stackoverflow.com/questions/36210686/importerror-no-module-named-mysite-settings-django
http://unikys.tistory.com/248
http://idlecomputer.tistory.com/7

728x90
반응형

'Infra > Linux' 카테고리의 다른 글

[Linux] 쉘 스크립트로 간편하게 SSH 접속하기  (0) 2018.05.09
[Linux] Apache(CentOS) 설치  (0) 2018.04.10
[Linux] CentOS 명령어  (0) 2018.04.10
[Linux] CentOS 설치  (0) 2018.04.10
[Linux] hosts 파일  (0) 2018.04.02
Comments