How To Deploy A Flask App On Digitalocean
Tags: cloud, docker, python, tutorial
Published: 2024-01-20 19:19:41

## Introduction

Flask is a python framework for building web applications. It’s a popular choice for building web apps because of its simplicity and flexibilty. Gunicorn(Green unicorn) is a Python WSGI HTTP server for unix. It acts as a middle layer which receives requests sent to the Web server from a client  and forwards them to the Python app. Nginx on other hand is a Web server and reverse proxy which helps in load balancing, caching and handling static files. Docker simplifies your deployment process, allowing you to package your application and its dependencies into a single container.

In this tutorial, we will deploy a flask app to a digitalocean droplet from an existing github repository, utilizing Gunicorn and Nginx and also containerize the app with Docker.

**Prerequisites**
To follow this tutorial, we will need the following:
Digitalocean account, required for deploying the application.
Git to clone the repository.
Gunicorn installed for running the web applications.
Nginx installed, following steps from Nginx Documentation.
Docker installed for creating and running your container.

## Part 1- Creating a Droplet and Installing Gunicorn
We will be deploying our application on digitalocean so you need to create an account.
### Step 1: Create a droplet on digitalocean.
The first step is to choose any region of your choice, image for your server, select a CPU option and an authentication method.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0vu0s8tnsrc33ufq680.png)
### Step 2: SSH into your droplet console, install python and clone your github repository of your existing flask application.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6sj8ovht5wtolsh5rqb.png)
``` 
sudo apt update
sudo apt install python3 python3-pip python3-venv 
```
This will also install the venv module.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lec5tgzzgwoqzcrkrm7b.png)
Clone the Github repo
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4r4q2h490mdubii75o7.png)
Navigate into your github repository:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73mq7ig51kn89vhsg0rm.png)
### Step 3: Create a python virtual environment on your server.(Optional)
Creating a python virtual environment is totally optional. It is used when you have multiple python versions installed on your server.
Make a new directory and navigate into it.
``` 
mkdir venv
cd venv
```

Now create a virtual environment and activate it as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kaugl4u06pepqrvyemgs.png)
Your prompt will change to indicate that you are operating inside a virtual environment.
To deactivate simply execute the command below(optional):
``` 
deactivate
```
### Step 4: Install Gunicorn
We need to install Gunicorn which will serve our flask app and we also install all requirements necessary for your Flask app from the requirements.txt in the repository.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/olhecmw9g42o6vc295hq.png)
```
pip install -r requirements.txt
```
We will now start your the flask app using the following command.
```
python app.py
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eq5a1z0zxnap66pthkmv.png)
 Visit your server’s ip address on your browser.(http://your_server_ip:port<route_if_any>).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwmhcl1d6hrnnaqq4x9z.png)
If we close our terminal, the flask app will stop running. To keep it running in the background, we need Gunicorn as a daemon. It operates as a background process, detaching from the terminal. If you close the terminal or logout without destroying the server the app won’t stop running because daemon continues to run in the background.
```
gunicorn -b 0.0.0.0:8000 app:app --daemon
```
Great job! You have successfully deployed your Flask app using Gunicorn.

## Part 2-Setting up and Configuring Nginx
Now that you have completed the first part of deploying your Flask app and making it accessible with Gunicorn a web server gateway interface(WSGI) for python applications on your web browser, the next part is to set up Nginx which is a web server for reserve proxy(a server that sits between the client devices and a backend server) handling request from clients and forwarding them to the appropriate backend server and takes the response back to the clients.

### Step 1: Install Nginx
Ngnix should be automatically registered as a systemd service and should be running.
```
sudo apt install nginx -y
```
To check the status of your nginx if it is running or not use the following command:
```
sudo systemctl status nginx
```
If it is not running then execute this command:
```
sudo systemctl start nginx
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mruybzczxyrrwj6mabsp.png)
Then you are good to go. For visual verification that everything is working properly, visit your server ip address again on your brower(http://your_server_ip), and you should see the Nginx default welcome page.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhp6qfuhwxx8lveoug2d.png)
### Step 2:  Configuring Nginx
Nginx configuration usually lives in the /etc/nginx directory with the Nginx configuration files ending with .conf extension inside. Navigate into this directory and list all the files:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uz6a83lq43lkskv9f3i5.png)
Let’s move the contents of the nginx.conf file into a new file and create a new configuration file for learning purposes to avoid editing the original nginx.conf file.
```
#rename file
sudo mv nginx.conf nginx.conf.backup

#create new file
touch nginx.conf
```
Open your newly created nginx.conf file using any text editor of your choice and write your new configurations. I will be using nano throughout this tutorial. :
``` 
sudo nano /etc/ngnix/nginx.conf
```
```
events {

}

http {

    server {

        listen 80;
        server_name tutorial.test;

        return 200 "Bonjour, mon ami!\n";
    }

}
```
### Step 3: Validate and reload the configuration file
Validate your configuration file to check for any syntax error. If you have a syntax error this command below will let you know.
``` 
sudo nginx -t
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwjbtb19alcurmii6vgt.png)
The next thing you have to do is to instruct nginx to reload the configuration file:
``` 
sudo nginx -s reload
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzik05j7hycyifbczqaa.png)
Once you have reloaded the file, simply reload your web browser again.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypxoz98grwf1b7lb0te3.png)
Congratulations on getting this far!

## Part 3- Containerize your App With Docker
One of the benefits about containerising your application(s) is that it allows you to package all dependencies, configuration, system tools and runtime necessary for your application into a single container and deploy it across different environments. In this tutorial we will use docker basic syntax to carry this out.We will only be taking a high level overview of how to use Docker.

### Step 1: Install Docker
The first step is to install docker, enable it and start it:
```
sudo apt install docker.io
sudo systemctl enable docker
sudo systemctl start docker
```
## Step 2: Create a dockerfile
Let's create a dockerfile which is used to build Docker Images. It is a simple text file that consists of a set of instructions or commands that is executed by an automated build process in steps from top to bottom. The dockerfile can be modified to meet your needs.
``` 
sudo touch Dockerfile 
sudo nano Dockerfile
```
```
FROM python:3.10

WORKDIR /app
COPY requirements.txt /app/

RUN python -m venv venv
Env PATH="/app/venv/bin:$PATH"

RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 80  

CMD ["python3.10", "app.py"]
```
## Step 3: Build and Run
Now that your dockerfile is ready, it is time to build an image and run it.
```
docker build -t tutorial .
docker run -d -p 8080:8000 tutorial
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tb86xwn7231kyiava9k2.png)
Nice job! Your app has successfully been containerized.

## Conclusion

In this tutorial, you learned how to deploy your Flask app and containerize it with docker. We first cloned an existing Flask App from Github into a Digitalocean droplet. Gunicorn was installed which was used to create a python web server gateway interface and also Nginx for reverse proxy which could also be used for caching and load balancing. Docker was used to containerize the app making it possible for you to deploy it in any environment without installing any dependency.

Deployment is essential in making your app operational and accessible by users to interact with it. It is an important step  in software deployment life cycle. Through deployment, your app becomes available on servers or cloud platforms, allowing users to access, experience, and benefit from its features, ultimately realizing the software's intended purpose. It is the bridge that connects the development phase to the end-users, ensuring that the app is ready for real-world usage, feedback, and continuous improvement. 

I hope you find this article helpful. Thank you🙂.