Python Bottle+virtualenv+uWSGI+Nginx installation on Ubuntu 12.04.1 LTS


为了造福世界人民,我觉得还是用英语写吧 XD

Today I got a request to write a backend server to provide interface access from frontend. I determined to use Python and  RESTful api firstly . I hate writing Java code…

After some investigation, I picked up Bottle. It is very neat and small. And I also read that with nginx and uWSGI, the performance is good too.

My environment is Ubuntu 12.04.1 LTS; but after followed several posts, my environment still did not work. I want to share my findings to save others’ time:)

Let’s cut to the chase:

  • Note:

My application would be in below directory constructure, all following commands and configurations are based on below:
/var/www/myapp would be the root directory of my bottle app
/var/www/myapp/env would be the virtualenv for the app
/var/www/myapp/ would be main .py file of bottle

  • Install nginx and uwsgi:
sudo apt-get update
sudo apt-get install -y nginx uwsgi
sudo apt-get install uwsgi-plugin-python
  • Install pip to help install python modules
sudo apt-get install python-pip
  • Install virtualenv: virtualenv to seperate the Python environment for different deployments
sudo pip install virtualenv
  • Set up app virtualenv:
sudo mkdir -p /var/www/myapp
sudo virtualenv /var/www/myapp/env
source /var/www/myapp/env/bin/activate
pip install bottle
  • Change the permission of the app directory so that uWSGI can read it and Python can write in it
sudo chown -R www-data:www-data /var/www/myapp
  • OK, the most important part: the configuration of nginx and uWSGI. These two recipes would worth some money XD

1. nginx config:

sudo gedit /etc/nginx/sites-enabled/default

copy below config in opend file:

server {

     listen   80;
     charset utf-8;
     root /var/www/myapp;
     server_name localhost;

location / {
     include uwsgi_params;
     uwsgi_pass unix:/tmp/uwsgi.myapp.socket;
     uwsgi_param UWSGI_PYHOME /var/www/myapp/env;
     uwsgi_param UWSGI_CHIDIR /var/www/myapp;
     uwsgi_param UWSGI_SCRIPT index; # this should be the .py file name without suffix that your bottle will use to launch

2.uWSGI config:

sudo gedit /etc/uwsgi/apps-enabled/uwsgi.ini

copy below config in opend file:

  • Now we are one step to success. In order to verify the setup, we need a sample file ( the file name must be consistent with the one in UWSGI_SCRIPT in nginx config).

Put under /var/www/myapp

#!/usr/bin/env python
from bottle import route, run, default_app
def index():
    return "Aloha, world~"

if __name__ == "__main__":
    run(host="localhost", port=8081)
    application = default_app()
  • Finally, Restart/start nginx and uWSGI services:
sudo service nginx restart
sudo service uwsgi restart

Now “it’s the moment to witness the miracle!” 😀  Access http://localhost/ in your browser, you should  see “Aloha, world~”.  If not, comment below:)