Docker Compose: Microservice Architecture for Python Application

Saurabhk
2 min readSep 17, 2021

--

Pic Credit: Joviton D’costa

Docker Compose allow to specify and run multi-container Dockerize applications in isolation, while also managing seamless interaction with each other. Compose file provides a way to document and configure all of the application’s service dependencies (databases, web service APIs, networking etc)

Microservices:

Microservice architecture is a nice way to abstract different module of the application, yet providing flexibility interms of choice to use different technology , programming language, backend infrastructure etc. This helps to avoid limitation encountered while developing monolithic applications like closely coupled design, scaling, maintenance, deployments & others.

In this blog lets look at a case on how to create docker compose file which manages communication among 2 containers.

Fig 1: Architecture

The 2 containers are:

  1. Web-App: A front end (Flask-App) i.e Entry point to the application.
    The Flask-App runs on 8000 port.
  2. API : API endpoints resources based of (FastAPI).
    The FastAPI runs on 5000 port.

Refer to my previous article to get started on Containerizing python application : https://saurabhk30.medium.com/docker-toolkit-dockerizing-flask-app-7b2cd9e93c4c

Microservice File Structure

Fast-api & Flask-app Folders: are containerized (Fig. 1)

Deploy.yaml: Docker compose file that holds the logic to bind these 2 container

build.sh: script to build the 2 Containers

Microservice Communication

To handle the communication here’s how Docker Compose (deploy.yaml ) file looks like. The Compose file manages the networking among the containers

The Fast-API (app-api:1.0) endpoints are consumed by the triggers in Flask-App code.

Flask-APP’s python script should register an API Call to Endpoint by mentioning container image name(app-api) as specified in deploy.yaml file (Like shown below in the code snippet)

import requestvalue = requests.post(url="http://app-api:5000/someEndpoint",json={"query":query})

Build.sh

The shell script here build & launches the 2 docker container

Run Bash Script

$ bash build.sh

To make it executable & run directly via terminal use:

$ chmod +x build.sh
$ build.sh

Launch App using Docker Compose Command

$ sudo docker-compose -f deploy.yaml up

This command would prompt local URL to launch Frontend FlaskApp where it can can seamlessly ping the endpoint resources of FastAPI app.

Terminate App using Docker Compose Command

$ sudo docker-compose -f deploy.yaml down

--

--

Saurabhk
Saurabhk

Written by Saurabhk

Data Science Enthusiast. Love Applied Research.

No responses yet