# Deploying 2-Tier Flask App on Docker Container

This is the simple flask-app that connect with MYSQL database.

### This app allows user to send messages and store them in MYSQL Database and shows that messages on front-end.

## Prerequisites

* Basic understanding of Flask and MySQL.
    
* Docker installed on your system.
    
* Docker Compose
    
* Git and Github
    
* AWS (Optional)
    

## Steps

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You can either use your local system or spin up an EC2 instance on AWS and install docker on it.</div>
</div>

### 1) Cloning the repository to your local machine or AWS EC2 (Docker Installed)

```bash
 git clone https://github.com/Mihir-Kumar13/two-tier-flask-app.git
```

### 2) Navigate to the repository and Create a .env file in the same directory to store MYSQL environment variables:

```bash
cd flaskapp
toucn .env   ## For storing the enivronment variables
```

### 3) Adding the MYSQL configuration in .env file

```bash
MYSQL_HOST=mysql
MYSQL_USER=your_username
MYSQL_PASSWORD=your_password
MYSQL_DB=your_database
```

## To Run the containers without docker compose

### 1) First create a docker image called flaskapp

```bash
   docker build -t flaskapp .
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Before starting the containers, Make sure that both backend and SQL database container can interact with each other. In order to make that happen, we need to create the network.</div>
</div>

### 1) Creating docker network

```bash
   docker network create twotier  # Creating docker network
```

### 2) Running both the containers

**i) MYSQL Container**

```bash
docker run -d \
    --name mysql \
    -v mysql-data:/var/lib/mysql \
    --network=twotier \
    -e MYSQL_DATABASE=mydb \
    -e MYSQL_ROOT_PASSWORD=admin \
    -p 3306:3306 \
    mysql:5.7
```

**ii) Backend Container**

```bash
docker run -d \
    --name flaskapp \
    --network=twotier \
    -e MYSQL_HOST=mysql \
    -e MYSQL_USER=root \
    -e MYSQL_PASSWORD=admin \
    -e MYSQL_DB=mydb \
    -p 5000:5000 \
    flaskapp:latest
```

## Docker compose

### 1) Start the containers using Docker compose

```bash
  docker-compose up --build
```

### 2) Access the Flask app in your web browser:

* Frontend: [http://localhost](http://localhost)
    
* Backend: [http://localhost:5000](http://localhost:5000)
    

### 3) Create the messages table in your MySQL database:

```sql
CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    message TEXT
);
```

**Thanks for Reading this Blog.  
Please share and let me know any Insights from your side.**

You can check my profile on [LinkedIn](https://www.linkedin.com/in/mihir-kumar-devops/)

**#DevOps #Jenkins #Flask #Python #automation #Docker #deployment #MySQL**
