Let us create a simple API in Python and serving it using Nginx.
In this example we will use
Debian 9
as a distro for the server.
Alright, let's write some code.
We will create an API that will serve an array of fruits.
Let's create a
__main__.py
file:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/fruits')
def fruits():
return jsonify([
'apple',
'banana',
'pear',
'orange'
])
if __name__ == '__main__':
app.run(debug=True)
Save the file.
You can now start the application right away by executing:
python __main__.py
The application should now be available at: http://localhost:5000
We need to configure the sever to be able to run the application.
apt-get install python-pip python-virtualenv nginx uwsgi uwsgi-plugin-python
rm /etc/nginx/sites-available/default
rm /etc/nginx/sites-enabled/default
To make it compatible with Nginx, you will need these three files:
- yourapp.ini - uwsgi config
- yourapp.service - systemd service
- yourapp.nginx - nginx configuration
[uwsgi]
wsgi-file = __main__.py
virtualenv = venv
plugin = python
callable = app
master = true
processes = 5
socket = /var/run/yourapp.sock
chmod-socket = 660
vacuum = true
logto = /var/log/yourapp.log
die-on-term = true
[Unit]
Description=uWSGI instance to serve yourapp
[Service]
User=someuser
ExecStart=/bin/bash -c 'cd /path/to/yourapp; uwsgi --ini yourapp.ini 2>&1 >> /tmp/yourapp.log'
[Install]
WantedBy=multi-user.target
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name yourapp.com;
client_max_body_size 300M;
location / {
include uwsgi_params;
uwsgi_pass unix:/var/run/yourapp.sock;
}
}
Place
yourapp.ini
next to your__main__.py
file and placeyourapp.service
in/etc/systemd/system/.
yourapp.nginx
should be placed in/etc/nginx-sites-available/.
. You will also need to symlink the nginx file like this:
ln -s /etc/nginx/sites-available/yourapp.nginx /etc/nginx/sites-enabled/.
A good practice is to run the application from a python-virtualenv.
cd /path/to/yourapp
virtualenv -p /usr/bin/python2.7 ./venv
source ./venv/bin/activate
In our case, all we need is flask:
pip install flask
Alright, we are ready to start everything.
systemctl restart nginx
systemctl start yourapp.service
To see errors, please look at these log files:
cat /var/log/nginx/error.log
cat /var/log/yourapp.log
journalctl -u yourapp.service
Common errors:
- wrong permissions on /var/run/yourapp.sock
- no runnable app found in application
- lack of dependencies