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
Dockerizing a Python Flask Application with a Database Applications are packaged, distributed, and run via Docker within Docker containers throughout the process of "dockerizing". The exact environment and dependencies must be installed in order to run that application on another local machine when it is developed under a specific environment and depend
5 min read
Dockerizing a Python Flask Application with a Database Applications are packaged, distributed, and run via Docker within Docker containers throughout the process of "dockerizing". The exact environment and dependencies must be installed in order to run that application on another local machine when it is developed under a specific environment and depend
5 min read
Load Balancing Flask Application using Nginx and Docker Load balancing means efficiently distributing the incoming traffic to different server instances. Nginx is open-source software that can be used to apply load balancing to backend systems. Nginx also can be serve services such as reverse proxy, caching, web server, etc.Docker is a tool that gives a
4 min read
Build an Application Like Google Docs Using React and MongoDB In this article, we will create applications like Google Docs Made In React and MongoDB. This project basically implements functional components and manages the state accordingly. The user uses particular tools and format their document like Google Docs and save their work as well. The logic of Goog
6 min read
Deploy MERN Stack on AWS EC2 with Docker via GitHub Actions EC2 stands for Elastic Cloud Computing and is a service that AWS offers for running applications, hosting websites, processing data, and performing other computing operations. How will we deploy our MERN application?We will push our MERN project frontend and backend into two different repositories o
15+ min read
Sending Data from a Flask app to MongoDB Database This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use. MongoDB is an open-source database that stores data
5 min read