How to deploy your Flask application on Ubuntu Server?

Deepak Radhakrishnan
()

Note

Before we get started, if you have an apache server up and running in your server, it is likely to create a conflict between Apache and Nginx servers. So, if you want them both to work together perfectly, have a look at “How to run apache2 and Nginx together?“.

Hello Folks, this tutorial will guide you on how to deploy a flask web application in a server, using Nginx and Gunicorn.Why use two components, right? That’s because Nginx takes care of the requests, response and static file. Wherein, gunicorn takes care of the python code.

Clearly, there are many other ways to deploy flask applications like WSGI, FastCGI, etc. But here we will deploy it professionally with the help of Nginx and Gunicorn.

I hope you have an active firewall enabled for you to control your incoming and outgoing traffic. To check if your flask application is running just fine, we need 5000 port to be permitted in firewall. I opt for the uncomplicated firewall because it is easy to use and manage when compared to iptables and other firewalls. You can make use of your own firewall, if it is already up and running, Or else, you can set up your own uncomplicated firewall from scratch. I have a tutorial on setting up an uncomplicated firewall from scratch. Throughout this tutorial, I will be employing ufw.

Contents

Open 5000 port for our application

Enable port 5000, for making sure that the Flask app is running just fine.

sudo ufw allow 5000

To enable firewall.

sudo ufw enable

Now, you can just check the status of your firewall to ensure port 5000 is enabled.

sudo ufw status

Copying our application to the server

Before, we copy our application to the server, we have to prepare the list of dependency packages of our application. Here comes the role of the virtual environment. If you are making use of a virtual environment for your application, it will be a matter of seconds for you to generate the requirements.txt file from the installed packages.

Generating the requirements file and running that file in server saves a lot of time and effort. All you have to do is, get inside of your virtual environment by activating it and type the following command.

pip freeze

“pip freeze” command, will list all the supportive packages you have installed for your application in the virtual environment. Now we have to generate the requirements.txt file. If you are a Linux or Mac user you can use the below command. Windows users have to copy pip freeze output and create a requirements.txt file yourself.

pip freeze > requirements.txt

All done. Now we have to copy our application files to the server.You can use filezilla,winscp or anything.I will be making use of secured copy , because I am comfortable with that.

scp -r your_application_folder_path  user@server_IP:~/myapp

Here you have to replace “your_application_folder_path” with your application folder path, “user” with the username you use to login your server, “server_IP” with your server’s public IP address. Once you are done hit enter and it will prompt your server’s password.

Setting up Virtual Environment in Server

Install python pip

sudo apt install python3-pip 

Install virtual environment

sudo apt install python3-venv

Now open your application folder and create a virtual environment. While copying, I specified “myapp” – so this will be my application folder with path “/home/user/myapp“. You have to replace with yours.

cd myapp
python3 -m venv venv

Activate virtual environment

source venv/bin/activate

Installing Requirements from requirements.txt

pip install -r requirements.txt

This command will install all your supportive packages that required for your application. “-r” is for recursive installation, that makes sure all the packages are installed.

Testing our application is running fine in server

Before you run your application, you need to make few changes. In app.run(debug=True) you have to remove debug=True as we are running it in production server. Add host=’0.0.0.0′ – so that it automatically takes our server IP address. The final code would look like this,

app.run(host='0.0.0.0')

Now you can test the app is running fine.

python3 app.py

Make sure it is running with port 5000 and host 0.0.0.0 “http://0.0.0.0:5000/”

Installing Nginx & Gunicorn

sudo apt update
sudo apt install nginx

Before you install Gunicorn, make sure that your are inside the virtual environment .

pip install gunicorn

Now we have to remove the default nginx file and create a new one.

sudo rm /etc/nginx/sites-enabled/default 

Create a new file for your flask application

sudo nano /etc/nginx/sites-enabled/myapp

Add the following lines to the file

server {
        server_name YOUR_SERVER_IP_HERE;

        location /static {
                alias /home/user/myapp/static;
        }
        location / {
                proxy_pass http://localhost:8000;
                include /etc/nginx/proxy_params;
                proxy_redirect off;
        }
}

Replace YOUR_SERVER_IP_HERE with your server ip and in location /static specify your static files path .

Make necessary changes in the firewall for the nginx to run smoothly . I am removing 5000 from the firewall as we don’t need it anymore.

sudo ufw allow http/tcp
sudo ufw delete allow 5000
sudo ufw enable
sudo systemctl restart nginx

You may get some error if the apache server is running as I told in the beginning. Run the below command if you getting any error.

sudo killall apache2

Running Flask application with Gunicorn

Running a flask application with gunicorn is simple. The syntax is “gunicorn -w 3 myapp: app”. I will explain the components in it.”myapp” is the name of my application, you can replace with yours. -w is workers and 3 is the number of workers. We have to add the number of workers according to the number of cores of your processor. The formula of deciding workers is “(2X no. of cores )+1”. In Linux, it is easy to find out the number of cores by running the below command.

nproc --all

MIne is 1 so ((2*1)+1)= 3. So the command will be

gunicorn -w 3 myapp:app

Type the server ip in browser , it will open your flask application.Go through the functionalities of your application and make sure it is working fine. Now press ctrl+c to quit, as we don’t want to run it in the foreground . For setting auto start , auto restart and error logging functionalities we need to install a software called supervisor. So that all the necessary functionalities will be taken care of, by the supervisor.

Installing Supervisor

sudo apt install supervisor

Once the setup is done, we need to do some configurations for our application.

sudo nano /etc/supervisor/conf.d/myapp.conf

Add the following lines inside the configuration file for your application .

[program:myapp]
directory=/home/user/myapp
command=/home/user/myapp/venv/bin/gunicorn -w 3 myapp:app
user=YOUR_USER_NAME_HERE
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stderr_logfile=/var/log/myapp/myapp.err.log
stdout_logfile=/var/log/myapp/myapp.out.log

Replace the parameters with your application’s.

Creating Log files

You need to create the folder and log files specified in supervisor configuration .

sudo mkdir -p /var/log/myapp
sudo touch /var/log/myapp/myapp.err.log
sudo touch /var/log/myapp/myapp.out.log

Make sure the name is same as you specified in the supervisor’s configuration file.

Restart supervisor

sudo supervisorctl reload

All done you can close your ssh connection and type the server IP in your browser you can see that your application in the background.

Do comment or contact me if you have any trouble deploying. Happy Coding 🙂

How useful was this post?

Click on a starts to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow me on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

%d bloggers like this: