How to create a Server for a Flask application on DigitalOcean Droplet

  1. git clone your repo from github
   git clone [webapp github url]
  1. set a virtualenv for this app:
   virtualenv -p python3 myenv
  1. create a file wsgi.py in your flask app root folder with the following lines
from app import app

if __name__ == "__main__":
    app.run()
  1. remove debug mode from app.py:
if __name__ == "__main__":
    app.run()
  1. run python wsgi.py to check the configuration
python wsgi.py
  1. Dump your db from your previous server ( PostgreSQL )
pg_dump -d database_name -U username -h hostname  > filename.dump
  1. deactivate the virtualenv
deactivate
  1. create a service with the file : /etc/systemd/system/projectname.service

[Unit]
Description=Gunicorn instance to serve myproject
After=network.target

[Service]
User=username
Group=www-data
WorkingDirectory=/home/username/myproject
Environment="PATH=/home/maru/myproject/myenv/bin"
ExecStart=/home/maru/myproject/myenv/bin/gunicorn --workers 4 --bind unix:myproject.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target
  1. Start myproject
sudo systemctl start myproject
  1. Enable myproject
sudo systemctl enable myproject

You will see something like this:

Created symlink /etc/systemd/system/multi-user.target.wants/myproject.service → /etc/systemd/system/myproject.service.
  1. check status:
sudo systemctl status myproject
  1. Create the file /etc/nginx/sites-available/myproject
server {
    listen 80;
    server_name myproject.com www.myproject.com;
     location / {
        include proxy_params;
        proxy_pass http://unix:/home/username/myproject/myproject.sock;
        }
}
  1. Create a link like this:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
  1. check nginx with:
sudo nginx -t

If everything is OK the output looks like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
  1. restart nginx with:
sudo systemctl restart nginx
  1. Create a new subdomain in digitalocean droplet

  2. Create directory:

sudo mkdir -p /var/www/example.com/html
  1. Set permissons for that:
sudo chown -R $USER:$USER /var/www/example.com/html
  1. permission for the whole directory:
sudo chmod -R 755 /var/www
  1. Create the DB on your new local server

  2. If DB exists => dump and restore.

    Else => in the terminal run python and after import your app and run code:

$ python

>>>from app import db
>>>db.create_all()

© Copyright 2019 marumaker.com