Skip to content

Deploying Python Flask App With PM2 on Ubuntu Server 18.04

Here I am showing you how to deploy your Flask app on a machine running Ubuntu Server 18.04… I am assuming that you have Python 3 and pip installed on your machine and npm installed on your remote server.

First we have to create our working directory:

$ mkdir flask-app && cd flask-app
flask-app$ nano app.py

We created a file named app.py and opened it with nano. Write the code below:

flask-app/app.py :

from flask import Flaskapp = Flask(__name__)@app.route('/')
def hello():
    return "Hello, World!"if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, debug=True, threaded=True)

Save the file with ctrl+o , press enter and exit with ctrl+x . Now we need to install virtual environment and create one for our app to make it run anywhere we want:

flask-app$ pip install virtualenv
flask-app$ virtualenv --python=python3 venv
flask-app$ source venv/bin/activate

After that install Flask in our environment:

(venv)flask-app$ pip install Flask

Now we are ready to go. But we have to upload our files to the server. We can do it with scp:

(venv)flask-app$ deactivate venv
flask-app$ cd ..
$ scp -r /flask-app user@remotehost:/var/www

Now connect to your remote server with ssh and install pm2:

$ ssh user@remotehost
user@remotehost:~$ npm install pm2@latest -g

Now activate virtual environment and start pm2:

user@remotehost:~$ cd /var/www/flask-app
user@remotehost:/var/www/flask-app$ source venv/bin/activate
(venv) user@remotehost:/var/www/flask-app$ pm2 start app.py --name flask-app --interpreter=python3

Thats it. Now you can access your app from http://remoteip:8080 .

Some usefull commands for pm2:

TO LIST YOUR APPS:
pm2 listTO RESTART YOUR APP:
pm2 start your_appTO STOP YOUR APP:
pm2 stop your_appTO START YOUR APP:
pm2 start your_appTO SEE LOGS OF YOUR APP:
pm2 log your_appTO DELETE YOUR APP:
pm2 delete your_app