redpip redpip - 15 days ago 4
Python Question

Quickest way to deploy a Flask app on ubuntu

im aware of flask deployment options, but all those options seems overkill to me for such a simple flask app that i wrote. it works just fine with flask's own builtin server.

workon kittapp
python run.py // runs the webserver at configured port, everything's fine


heres my run.py file

from kittapp import app

if __name__ == '__main__':
app.run(host=app.config['HOST'], port=app.config['PORT'], debug=app.config['DEBUG'])


first problem is, the server stops as soon as i exit my ssh session, so i tried to push the task to background using one-time
cron
jobs,
at now
or
nohup
commands. it works fine but the second problem is that after a few hours the python process (which was pushed to bg) is not running anymore and the webapp is down.

i know that i need to write a daemon-like startup script for this eventually. just wanted to see if there's any other simple yet reliable solution to deploy a flask app on a ubuntu machine?

Answer

You might be looking for Supervisor.

Supervisor is a process control tool for Unix-like systems. It provides an easy-to-use interface to build and manage daemon-like supervised processes using just config files.

You can create a simple config file for your Flask app, add it to Supervisor, start it and you're done. Here's how:

# Install supervisor
sudo apt install supervisor -y # Or pip install supervisor 

# Start supervisor service
sudo service supervisor start

# Create your config file
# I'll add a sample kittapp.conf later on...
sudo vim /etc/supervisor/conf.d/kittapp.conf

# Add and start your job
sudo supervisorctl add kittapp
sudo supervisorctl start kittapp

Easy right? But there's a little gotcha when utilizing virtualenvs, which you are. Please note that workon is a shell function, not an executable in PATH. Supervisor does not source your ~/.bash* or ~/.zsh* files before running jobs. It has no idea about them. As a result, workon won't be available. Instead, we need to set the python path correctly to point to our venv's bin/ directory. It can be done using the environment directive.

Here's a minimal Supervisor config file:

[program:kittapp]
environment=PATH="/home/user/virtualenvs/kittapp/bin"    # Point it to the bin/ directory of your venv
command=python run.py                                    # Here's the actual command that supervisor needs to run in order to start the server
directory=/var/www/kittapp                               # Instructs supervisor to cd into this directory before running the command
stdout_logfile=/var/www/kittapp/logs/supervisor.log      # Write logs to this file
redirect_stderr=true                                     # Redirect errors to supervisor output, so you'll have your errors in the log file  

Well, that's all there is to it.

And you might want to have a look at this Laracasts lesson on Supervisor:
https://laracasts.com/lessons/supervise-this