Sunday, May 28, 2017

conetos 7 - execute python in nginx server

centos
Installing

yum groupinstall "Development Tools"
python-devel
python-pip
pip install virtualenv

mkdir wsgi
cd wsgi
virtualenv db_venv
mkdir app







source db_venv/bin/activate
 
 
 
 type deactivate to exit
pip install uwsgi















create wsgi application inside wsgi folder










def application(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["Hello!"]

To simply run uWSGI to start serving the application from wsgi.py, run the following:
uwsgi --socket 127.0.0.1:8080 --protocol=http -w wsgi
To run the server in the background, run the following:
uwsgi --socket 127.0.0.1:8080 --protocol=http -w wsgi &
Configuring Nginx, make sure to remove --protocol=http from the chain of arguments,
test:








Stopping the server with SIGINT
kill -INT [PID]

Configure a uWSGI Config File


Deactive from virtualenvironment

nano wsgi.ini

[uwsgi]
module = wsgi:application

master = true
processes = 5

socket = myapp.sock
chmod-socket = 664
vacuum = true
die-on-term = true






vacuum option, which will remove the socket when the process stops:
die-on-term so that uWSGI will kill the process instead of reloading it:

Create an Upstart File to Manage the App

sudo nano /etc/init/myapp.conf


description "uWSGI instance to serve myapp"

start on runlevel [2345]
stop on runlevel [!2345]

setuid demo
setgid www-data

script
    cd /home/demo/myapp
    . myappenv/bin/activate
    uwsgi --ini myapp.ini
end script

setuid and setgid
web server needs to be able to read and write to the socket that our .ini file will create:

sudo start myapp
sudo stop myapp

uwsgi --ini myapp.ini



Configure Nginx to Proxy to uWSGI

sudo nano /etc/nginx/sites-available/myapp
server {
    listen 80;
    server_name server_domain_or_IP;

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/home/demo/myapp/myapp.sock;
    }
}

No comments:

Post a Comment