2017年2月6日 星期一

Django, uwsgi, nginx setup in Ubuntu 16


Video URL: https://www.youtube.com/watch?v=TYZfHn0MoXg

Detailed procedures:

apt install python
apt install python-pip
apt install nginx
pip install virtualenv
pip install virtualenvwrapper
pip install uwsgi

adduser deploy
su - deploy
## for virtualenv projects
mkdir projects
## for django webpages
mkdir web

## add virtualenv environment variables to user deploy
vi /home/deploy/.bashrc
...
export WORKON_HOME=~/projects
source /usr/local/bin/virtualenvwrapper.sh

mkvirtualenv p1
pip install django
cd ~/web/
django-admin.py startproject d1
cd d1
./manage.py migrate
vi d1/settings.py

ALLOWED_HOSTS = ['172.25.0.103']
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')


./manage.py collectstatic
./manage.py runserver 0.0.0.0:5000
##open web brower to test

## quit virtualenv
deactivate

## change back to root or sudo -i
## test uwsgi with django
uwsgi --master --http :5000 --home /home/deploy/projects/p1 --chdir /home/deploy/web/d1 --module d1.wsgi:application
## open web brower to test, and you will find the images and styles are gone, as uwsgi doesn't know where to service the static content from django.  We will get to that in nginx configuration part.

## create a service to start uwsgi automatically
vi /etc/systemd/system/uwsgi.service
[Unit]
Description=uWSGI Emperor

[Service]
ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown deploy:www-data /run/uwsgi'
ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target


## create config file for uwsgi
vi /etc/uwsgi/sites/p1.ini
[uwsgi]
uid = deploy
base = /home/%(uid)

chdir = %(base)/web/d1
home = %(base)/projects/p1
module = d1.wsgi:application

master = true
processes = 5

socket = /run/uwsgi/p1.sock
chown-socket = %(uid):www-data
chmod-socket = 660
vacuum = true


## start uwsgi service
systemctl restart uwsgi.service


## create nginx config file
/etc/nginx/sites-available/p1
server {
  listen 9090;
  server_name 172.25.0.103;
  location = /favicon.ico { access_log off; log_not_found off; }
  location /static/ {
    root /home/deploy/web/d1;
  }
  location / {
    include uwsgi_params;
    uwsgi_pass unix:/run/uwsgi/p1.sock;
  }
}

## sym-link to sites-enable
ln -s /etc/nginx/sites-available/p1 /etc/nginx/sites-enable/
systemctl restart nginx



沒有留言:

張貼留言