Containerize RESTful API using Flask and MongoDB


Objective

Containerize a RESTful API using Flask web developement framwork and MongoDB. Flask is a micro web framework written in Python. Docker is used as the containerization tool.


Getting started

This article is the continuation of the flaskREST API application.

Prerequisites:

It is recommended to create virtual environment for the purpose of seperate project environment and clean code. To create python virtual environment in Linux and Windows platform, please follow the given link.

Library Command
Flask pip install flask
Flask-mongoengine pip install flask-mongoengine
BSON pip install bson
Docker --
Docker-compose --
MongoDB --

Install the prerequisites and run the command pip freeze > requirements.txt to list all the installed libraries in the python virtual environment. Run mongo --version, docker -v and docker-compose -v to check the libraries are installed in your machine.

File structure


flaskREST
|- app.py
|- Dockerfile
|- docker-compose.yaml
|- requirements.txt
|__database
	|- db.py
	|- models.py

Dockerfile definition

flaskREST/Dockerfile:


From python:3.8.5-alpine3.12
WORKDIR /usr/app
COPY requirement.txt ./
RUN pip install -r ./requirement.txt
COPY . .
EXPOSE 5000
CMD [ "flask", "run" ,"--host=0.0.0.0"]

Build flaskbackend image, run docker build -t flaskbackend:v2 .
The dot (.) at the end of the docker build command to indicate the Dockerfile. To check the built image, run docker images.

Docker-compose definition

flaskREST/docker-compose.yaml:


version: '3'
services:
  backend:
    container_name: flaskbackend
    image: flaskbackend:v2
    restart: always
    ports:
      - 5000:5000
    depends_on:
      - mongo

  mongo:
    container_name: mongo
    image: mongo:4.2.0
    ports:
      - 1048:27017

To start both services


docker-compose up -d 

Terminal output:
Creating mongo ... done
Creating flaskbackend ... done

After running the command, mongo image will be downloaded from the dockerhub, and both flaskbackend and mongo containers will be created.

The server is running on http://localhost:5000. Download (postman) OR use command line tool (curl) to execute the operations. The following link has the instructions to execute CRUD in both postman and curl.

Download code: Github