I make apps for other people

nginx, Python 3 pyvenv, uwsgi, Flask, and OS X with MacPorts

Posted by Chris Jones
On August 26th, 2014 at 14:53

Permalink | Trackback | Links In |

Comments Off on nginx, Python 3 pyvenv, uwsgi, Flask, and OS X with MacPorts
Posted in Python

Given a working Flask web application called RarToZip (served from the built in HTTP server), this is the configuration I used on my MacBook to get nginx working as a proxy for uWSGI and Flask.

  1. Make sure MacPorts is up to date

    sudo port selfupdate
    sudo port upgrade outdated
  2. Install nginx
    sudo port install nginx
    nginx will be installed in /opt/local/sbin/nginx and the configuration files will be in /opt/local/etc/nginx
  3. Configure /opt/local/etc/nginx/nginx.conf

    worker_processes 1;
    events {
       worker_connections 1024;
    http {
       include mime.types.default;
       default_type application/octet-stream;
       sendfile on;
       keepalive_timeout 65;
       server {
         listen 80;
         server_name localhost;
         charset utf-8;
         client_max_body_size 512M;
       location / {
         try_files $uri @RarToZip;
       location @RarToZip {
         include uwsgi_params.default;
         root /opt/local/www/RarToZip/static;
         index index.html;
         uwsgi_pass unix:/opt/local/www/RarToZip/RarToZip_uwsgi.sock;
       error_page 500 502 503 504 /50x.html;
       location = /50x.html {
         root share/nginx/html;
  4. Create your web app directory (which presumes /opt/local/www exists)

    sudo chown chris:everyone /opt/local/www
    cd /opt/local/www
    pyvenv RarToZip
    cd RarToZip
    source bin/activate
  5. Install your dependencies

    pip install flask
    pip install rarfile
    export CC=gcc
    pip install uwsgi
    ln -s /Library/Framework/Python.framework/Version/3.4/bin/uwsgi bin/

    Note that uwsgi installed into /Library/Framework/Python.framework/Version/3.4/bin/uwsgi.
  6. Copy your working app from your development directory (mine was in IdeaProjects/RarToZip)

    cp ~/IdeaProjects/RarToZip/RarToZip.py
    mkdir static
    cd static
    cp -a ~/IdeaProjects/RarToZip/static/* .
    cd ..
    mkdir templates
    cd templates
    cp -a ~/IdeaProjects/RarToZip/templates/* .
    cd ..
  7. Configure uwsgi to run your app (see nginx.conf, above)

    base = /opt/local/www/RarToZip
    app = RarToZip
    module = %(app)
    venv = %(base)
    pyhome = %(base)
    pythonpath = %(base)
    socket = /opt/local/www/RarToZip/%n.sock
    chmod-socket = 666
    callable = app
    logto = /opt/local/www/RarToZip/logs/%n.log
  8. Start nginx

    sudo /opt/local/sbin/nginx

    If all goes well and nginx doesn’t have any errors on startup, you should be able to browse to an error page at http://localhost/.
  9. Start uwsgi

    uwsgi --ini /opt/local/www/RarToZip/RarToZip_uwsgi.ini

Comments are closed.