How to deploy django apps?

Create a lxc container

lxc-create -n jessie -t debian

Configure network

lxc.include = /usr/share/lxc/config/debian.common.conf
lxc.tty = 4
lxc.arch = amd64
lxc.network.type = veth
lxc.network.link = lxcbr0
lxc.network.flags = up
lxc.network.hwaddr = 00:16:3e:59:4b:71
lxc.network.ipv4 = 10.0.3.101/24
lxc.network.ipv4.gateway = 10.0.3.1
lxc.rootfs = /var/lib/lxc/jessie/rootfs
lxc.rootfs.backend = dir
lxc.utsname = jessie
lxc-start -n jessie
lxc-attach -n jessie
adduser user

How to install pyenv

Read instruction from here

apt-get install curl
apt-get install git
apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils
  • login as user and continue instructions:
su user
  • download installer and run it using bash:
curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

after install pyenv you must add paths to .bash_profile

vim ~/.bash_profile
export PATH="/home/user/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
  • install python 3.5.2 using
pyenv update
pyenv doctor
env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install -fkv 3.5.2

create a virtual env

pyenv virtualenv 3.5.2 webapp

Install app’s requirements

pyenv shell webapp
pip install --upgrade pip
pip freeze
pip install -r requirements.txt
pip install uwsgi
pip install django

How to deploy application?

pyenv shell webapp
python manage.py collectstatic

How to create uwsgi service?

vim /etc/systemd/system/myapp.service
[Unit]
Description=uWSGI Emperor service

[Service]
User = user
ExecStart=/home/user/.pyenv/versions/webapp/bin/uwsgi --http 127.0.0.1:8080 --wsgi-file /home/user/webapp/webapp/wsgi.py --chdir /home/user/webapp/
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target
systemctl start myapp
systemctl enable myapp

Install nginx and configure it

aptitude install nginx

vim /etc/nginx/site-enabled/default
server {
	listen 80 default_server;
	location /static/ {
		expires 30d;
		root /home/user/webapp/;
	}
	server_name _;
	location /{
		proxy_pass http://127.0.0.1:8080;
	}
}

notes:

  • your STATIC_ROOT in setting.py is:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

Some usefull links

Digital Ocean


Previous post: Headless Selenium Testing With Python and PhantomJS

Next post: Cowsay and fortune