Dockerizing a Python Flask App with MongoDB: Building a Full-Stack App
Last Updated :
28 Nov, 2023
In this article, we are going to build a stack Flask application with the database MongoDB and then we will Dockerize that Flask app with Mongo DB. As it is a Dockerized Full stack application it can run without any system environment setup. In this case, we are going to build a Student's Information Web application, this app can view student information from MongoDB and also can take input of student information using the HTML form to store it in MongoDB database.
Primary Terminologies
- Flask: It is REST API Micro Services Web Framework used for the development of web applications in Python programming language.
- MongoDB: MongoDB is a NoSQL database that can store data in JSON (JavaScript Object Notation) format.
- pymongo: It is a Python library that allows Python web applications to perform CRUD (Create Read Update Delete) operations on MongoDB's databases.
- Full Stack Web Application: The Web application is fully responsive and contains a Front-end (Browser side) and Back-end (server side) is called as Full Stack Web Application.
- Dockerization: Packing the Dependencies of Application into the single or multiple containers. so, that the application can run without dependence on the system Environment.
System Requirements
- Operating System: Linux(ubuntu)/Windows.
- Languages: Python (pymongo, Flask), HTML, yaml.
- Softwares: Docker, Vscode.
Step by Step Process
1. Build Full Stack Web Application
Now we are going to build Student's Information Full Stack Web application. For that create the directories:
Student_information:
├── templates
├── index.html
├── app.py
app.py:
Python
from flask import Flask, request, render_template, redirect, url_for
from pymongo import MongoClient
app = Flask(__name__)
# MongoDB connection setup
client = MongoClient(host='test_mongodb', port=27017,
username='root', password='pass', authSource="admin")
db = client.mytododb
students_collection = db.students
@app.route('/')
def home():
students = students_collection.find()
return render_template('index.html', students=students)
@app.route('/add_student', methods=['POST'])
def add_student():
if request.method == 'POST':
student_data = {
'name': request.form['name'],
'roll_number': request.form['roll_number'],
'grade': request.form['grade']
}
students_collection.insert_one(student_data)
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
inside template folder index.html:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h1>Student Information</h1>
<form method="POST" action="/add_student">
<label for="name">Name:</label>
<input type="text" name="name" required>
<br>
<label for="roll_number">Roll Number:</label>
<input type="text" name="roll_number" required>
<br>
<label for="grade">Grade:</label>
<input type="text" name="grade" required>
<br>
<button type="submit">Add Student</button>
</form>
<br>
<h2>Students:</h2>
<ul>
{% for student in students %}
<li>{{ student.name }} (Roll Number: {{ student.roll_number }}, Grade: {{ student.grade }})</li>
{% endfor %}
</ul>
</body>
</html>
now we have successfully build Python Flask App with MongoDB.
2.Dockerization of Web App
create Dockerfile, docker-compose.yml and requirements.txt inside the Student_information folder and the folder Structure look like this:
Student_information:
├── templates
├── index.html
├── app.py
├── Dockerfile
├──docker-compose.yml
├──requirements.txt
Folder Structure in VsCode will looks like this:

Dockerfile
FROM python:3.6
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt
docker-compose.yml:
web:
build: .
command: python -u app.py
ports:
- "5000:5000"
volumes:
- .:/app
links:
- db
db:
image: mongo:latest
hostname: test_mongodb
environment:
- MONGO_INITDB_DATABASE=Student_db
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=pass
ports:
- 27017:27017
requirements.txt
pymongo
flask
Project in Vs code for reference3. Build Docker Containers
Enter the following command in the terminal to build and run the docker containers.
docker-compose up --build
Containers Building
containers are running successfullyIf you are getting following error while building docker image by running the command docker-compose up --build:
ERROR: for f34991c8d0bc_student_info_db_1 Cannot start service db: driver failed programming external connectivity on endpoint student_info_db_1 (4a25c142988bf13040049dd935f93873fdb8cffe814d9c8f575072aa3885 3465): Error starting userland proxy: listen tcp4 0.0.0.0:27017: bind: address already in use.ERROR: for db Cannot start service db: driver failed programming external connectivity on endpoint student_info_db_1 (4a25c142980bf13040849dd935f93873fdb8cffe814d9c8f575872aa38853465): Error starting userla nd proxy: listen tcp4 0.0.0.0:27017: bind: address already in use ERROR: Encountered errors while bringing up the project.

Then change the port number from 27017 to 27018 in the docker-compose.yml:
ports:
- 27018:27017
This error will get resolved.
4. Run Web Application on Browser
Go to Flask server URL: http://172.17.0.3:5000/ this URL is not same for every system. It changes according to system's IP address and port number where Flask application is running.
Test the Web application:
Running Web applicationAll set, our Dockerized Full Stack Flask Web application with Database MongoDB is up and running.
Similar Reads
DevOps Tutorial DevOps is a combination of two words: "Development" and "Operations." Itâs a modern approach where software developers and software operations teams work together throughout the entire software life cycle.The goals of DevOps are:Faster and continuous software releases.Reduces manual errors through a
7 min read
Introduction
What is DevOps ?DevOps is all about automating and streamlining the software development lifecycle so that code moves from development to production quickly, reliably, and securely.Here is how the DevOps model flow works:Stages of DevOps are:Build Stage1. Developers write and organize code, using version control to
6 min read
DevOps LifecycleThe DevOps lifecycle is a structured approach that integrates development (Dev) and operations (Ops) teams to streamline software delivery. It focuses on collaboration, automation, and continuous feedback across key phases planning, coding, building, testing, releasing, deploying, operating, and mon
10 min read
The Evolution of DevOps - 3 Major Trends for FutureDevOps is a software engineering culture and practice that aims to unify software development and operations. It is an approach to software development that emphasizes collaboration, communication, and integration between software developers and IT operations. DevOps has come a long way since its in
7 min read
Version Control
Continuous Integration (CI) & Continuous Deployment (CD)
Containerization
Orchestration
Infrastructure as Code (IaC)
Monitoring and Logging
Microsoft Teams vs Slack Both Microsoft Teams and Slack are the communication channels used by organizations to communicate with their employees. Microsoft Teams was developed in 2017 whereas Slack was created in 2013. Microsoft Teams is mainly used in large organizations and is integrated with Office 365 enhancing the feat
4 min read
Security in DevOps