Caddy2 + Flask and Gunicorn
Install Python and python-venv:
sudo apt install python3-venv
Create a virtual environment to run your Flask project:
cd /home/username
python3 -m venv project_name
Install Gunicorn, Flask and other requirements:
source project_name/bin/activate
pip install wheel
pip install gunicorn flask
Create Flask APP file:
app_name.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Install supervisor for observe Gunicorn:
sudo apt install supervisor
Create supervisor conf file:
sudo nano /etc/supervisor/conf.d/project_name.conf
/etc/supervisor/conf.d/project_name.conf
[program:ProjectName]
directory=/home/username/project_name
command=/home/username/project_name/bin/gunicorn app_name:app -b 127.0.0.1:5000 --reload --max-requests 1 --access-logfile=- --error-logfile=-
autostart=true
autorestart=true
stderr_logfile=/var/log/HelloBot.err.log
stdout_logfile=/var/log/HelloBot.out.log
Reload conf file and restart supervisor:
sudo supervisorctl reread
sudo service supervisor restart
Install inotify-tools and Gunicorn will restart automatically when detect code changed:
sudo apt install inotify-tools
sudo service supervisor restart
Caddy Proxy Setting:
/etc/caddy/Caddyfile
example.com {
root * /var/www/html
handle /api/* {
# uri strip_prefix /api ## uncomment this line to strip prefix
reverse_proxy 127.0.0.1:5000
}
tls yourname@email.com
}
Finally, reload and restart Caddy:
sudo systemctl reload caddy
sudo systemctl restart caddy
Enjoy ~ 🙂