Flask Series: Deployment
Tuesday, Jan 26, 2016 08:02 · 245 words · 2 minutes read
Flask Series
- Prepare the Environment
- Structure the Application
- Application Configuration
- Templating
- Model
- Testing
- Views and Web Forms
- Error Management
- Security
- Optimizations
- Healthcheck and Monitoring
- Internationalization
- Deployment
I will describe a setup with nginx as a web server on a Ubuntu environment. A web server cannot communicate directly with Flask, that’s why gunicorn will be used to act as a medium between the web server and the Flask application. Gunicorn is like application web server that will be running behind nginx, it is WSGI compatible. It can communicate with applications that support WSGI – Flask, Django.
Installation
sudo apt-get update
sudo apt-get install -y python python-pip nginx gunicorn
Setup
Create a directory to store the project
sudo mkdir /home/www && cd /home/www
Clone the project from the GitHub repository and copy the application to the /home/www directory.
git clone https://github.com/damyanbogoev/flask-bookshelf.git /tmp/
cd /tmp/flask-bookshelf
cp -r ./* /home/www/
Install the application requirements:
pip install -r requirements.txt
Nginx configuration
sudo /etc/init.d/nginx start
sudo rm /etc/nginx/sites-enabled/default
sudo touch /etc/nginx/sites-available/flask_bookshelf
sudo ln -s /etc/nginx/sites-available/flask_bookshelf /etc/nginx/sites-enabled/flask_bookshelf
sudo vim /etc/nginx/sites-enabled/flask_bookshelf
The gunicorn will use port 8000 and handle the incoming HTTP requests. You could add a separate configuration for the static files of the Flask application, because it is better to be served directly by nginx.
Restart the nginx to load the later configuration changes:
sudo /etc/init.d/nginx restart
Run the gunicorn on port 8000
/home/www/flask_bookshelf/
gunicorn --bind 0.0.0.0:8000 run:app
The complete demo application, described in this blog post, can be found here.