<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manos Kakarakis on Medium]]></title>
        <description><![CDATA[Stories by Manos Kakarakis on Medium]]></description>
        <link>https://medium.com/@manos_kakarakis?source=rss-47e2f5148496------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GTijh5ibiAYOaYALGYQYcg.jpeg</url>
            <title>Stories by Manos Kakarakis on Medium</title>
            <link>https://medium.com/@manos_kakarakis?source=rss-47e2f5148496------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:04:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manos_kakarakis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python Flask scalable microservices using docker-compose and Nginx load balancer]]></title>
            <link>https://medium.com/@manos_kakarakis/python-flask-scalable-microservices-using-docker-compose-and-nginx-load-balancer-e20d421b1ad6?source=rss-47e2f5148496------2</link>
            <guid isPermaLink="false">https://medium.com/p/e20d421b1ad6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Manos Kakarakis]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 00:24:41 GMT</pubDate>
            <atom:updated>2022-10-17T11:27:20.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JGU_NQRashmnPCRpt-c1w.jpeg" /></figure><h3>Introduction</h3><p>Let’s build a web application with Python’s Flask web framework and use Docker and docker-compose to take the best out of the benefits that they provide in the microservices world. On top of that we will use Nginx load balancer to serve our application.</p><p>We will create a main Api that will be our server and that will communicate with two microservices that will be responsible for the news and weather information that the client will request. Everything will be packaged into docker containers and deployed with docker-compose to take advantage of the scaling that it provides for our app. Will also make use of the threading that the Flask has built in as a feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVdFmS5KjV0L7b2tB_TzsA.png" /></figure><h3>Step 1 — Create the Flask Services</h3><p>Let’s create our project directory that will be named as python_service and cd into it</p><pre>mkdir python_service<br>cd python_service</pre><p>Create the three python files <em>master_assistant.py weather.py </em>and <em>news.py</em> and add the following code to the respective files</p><p>master_assistant.py</p><pre>from flask import Flask, request<br>from flask_restful import Api<br>import requests</pre><pre>app = Flask(__name__)<br>api = Api(app)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/weather&#39;)<br>def weather():<br>    city = request.args.get(&#39;city&#39;)<br>    if city.isdigit():<br>        res = &quot;City name must be string e.g. &#39;Amsterdam, Berlin&#39;&quot;<br>        return res<br>    response = requests.get(&quot;<a href="http://weather:3002/weather?city=">http://weather:3002/weather?city=</a>&quot;+ city)<br>    return response.json()</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/news&#39;)<br>def news():<br>    country_name = request.args.get(&#39;country&#39;)<br>    if country_name.isdigit() or len(country_name) &gt; 2 :<br>        resp = &quot;Country name must be string. Choose from below: \n\nThe 2-letter ISO 3166-1 code of the country you want to get headlines for.\nPossible options: ae ar at au be bg br ca ch cn co cu cz de eg fr gb gr hk hu id ie il in it jp kr lt lv ma mx my ng nl no nz ph pl pt ro rs ru sa se sg si sk th tr tw ua us ve za&quot;<br>        return resp<br>    response = requests.get(&quot;<a href="http://news:3003/news?country=">http://news:3003/news?country=</a>&quot;+ country_name)<br>    return response.json()</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&quot;0.0.0.0&quot;,port=3001,debug=True,threaded=True)</pre><p>news.py</p><pre>from flask import Flask, request<br>from flask_restful import Api<br>import json<br>import requests</pre><pre>app = Flask(__name__)<br>api = Api(app)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/news&#39;)<br>def news():<br>    country_name = request.args.get(&#39;country&#39;)<br>    api_key = &quot;70dcd1c6a0d24ebdb57ff071ff9b8ddc&quot;<br>    base_url = &quot;<a href="http://newsapi.org/v2/top-headlines">http://newsapi.org/v2/top-headlines</a>?&quot;<br>    complete_url = base_url + &quot;country=&quot; + country_name + &quot;&amp;apiKey=&quot; + api_key<br>    response = requests.get(complete_url)<br>    return response.json()</pre><pre>if __name__ == &#39;__main__&#39;:<br>     app.run(host=&quot;0.0.0.0&quot;,port=&#39;3003&#39;,threaded=True,debug=True)</pre><p>weather.py</p><pre>from flask import Flask, request<br>from flask_restful import Api<br>import json<br>import requests</pre><pre>app = Flask(__name__)<br>api = Api(app)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/weather&#39;)<br>def weather():<br>    city_name = request.args.get(&#39;city&#39;)<br>    api_key = &quot;deb96cff96df7c74e93e62661b91c3c2&quot;<br>    base_url = &quot;<a href="http://api.openweathermap.org/data/2.5/weather">http://api.openweathermap.org/data/2.5/weather</a>?&quot;<br>    complete_url = base_url + &quot;appid=&quot; + api_key + &quot;&amp;q=&quot; + city_name<br>    response = requests.get(complete_url)<br>    return response.json()</pre><pre>if __name__ == &#39;__main__&#39;:<br>     app.run(host=&quot;0.0.0.0&quot;,port=&#39;3002&#39;,threaded=True,debug=True)</pre><p>As we see, in the master_assistant we have two endpoints, one for the weather request and one for the news request. For every time, the master_assistant will decide from which microservice to request the respective information.</p><p>At every service at the bottom of the code we define in which port it will listen and we enable the multithreading of the Flask server. As there is not anything shared that needs lock or an external db, the multithreading in this situation makes things faster and safe.</p><p>Create a file requirements.txt and add:</p><pre>aniso8601==8.1.0<br>blinker==1.4<br>certifi==2020.12.5<br>chardet==4.0.0<br>click==7.1.2<br>Flask==1.1.2<br>Flask-Jsonpify==1.5.0<br>flask-requests==0.0.14<br>Flask-RESTful==0.3.8<br>Flask-SQLAlchemy==2.4.4<br>idna==2.10<br>itsdangerous==1.1.0<br>Jinja2==2.11.2<br>MarkupSafe==1.1.1<br>pampy==0.3.0<br>pytz==2020.4<br>requests==2.25.1<br>six==1.15.0<br>SQLAlchemy==1.3.20<br>urllib3==1.26.3<br>Werkzeug==1.0.1</pre><h3>Step 2 — Building Nginx server</h3><p>Create out Nginx’s conf file named nginx.conf and add:</p><pre>events {}</pre><pre># Define which servers to include in the load balancing scheme.</pre><pre>http {<br>    upstream app {<br>        server master;<br>        server python_service_master_1:3001;<br>        server python_service_master_2:3001;<br>     }</pre><pre># This server accepts all traffic to port 80 and passes it to the upstream.</pre><pre>server {<br>         listen 80;<br>         server_name app.com;<br>         location / {<br>              proxy_pass <a href="http://app/">http://app</a>;<br>          }<br>     }<br>}</pre><p>Load balancing with Nginx uses a round-robin algorithm by default if no other method is defined. With round-robin scheme each server is selected in turns according to the order we set them in the Nginx.conf file. This balances the number of requests equally between our to two <em>master</em> instances.</p><h3>Step 3 — Dockerize everything</h3><p>We will create the Dockerfiles for our services.</p><p>Dockerfile</p><pre>FROM python:3.8-slim-buster</pre><pre># Install dependencies:<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>EXPOSE 3001</pre><pre>COPY master_assistant.py .</pre><pre># Run the application:<br>CMD python master_assistant.py</pre><p>Dockerfile.news</p><pre>FROM python:3.8-slim-buster</pre><pre># Install dependencies:<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>EXPOSE 3003</pre><pre>COPY news.py .</pre><pre># Run the application:<br>CMD python news.py</pre><p>Dockerfile.weather</p><pre>FROM python:3.8-slim-buster</pre><pre># Install dependencies:<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>EXPOSE 3002</pre><pre>COPY weather.py .</pre><pre># Run the application:<br>CMD python weather.py</pre><p>Dockerfile.nginx</p><pre># using Nginx base image<br>FROM nginx</pre><pre># delete nginx default .conf .file<br>RUN rm /etc/nginx/conf.d/default.conf</pre><pre># add the .conf file we have created<br>COPY nginx.conf /etc/nginx/nginx.conf</pre><h4>Time for docker-compose magic:</h4><p>Create a file named docker-compose.yml. Now we will add the configurations of Nginx and our services containers by adding the following code.</p><pre>version: &quot;3.9&quot;<br>services:<br>  nginx:<br>    container_name: nginx<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.nginx<br>    ports:<br>        - 80:80<br>    depends_on:<br>        - master<br>  master:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>  weather:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.weather<br>  news:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.news</pre><p>With the dockerfile command we specify the Dockerfile to build from, and with the ports we specify the nginx’s port to be 80 so it we be accessible by the clients.</p><p>Docker-Compose API creates an internal network in which the containers can communicate with each other using the container’s name. For example, the Nginx container can interact with the master container by using the following hostname: <a href="http://flask_tutorial_app:5000/ping">http://python_service_master:3001/</a> (The given name for each container by docker-compose is in this format: &lt;project directory name&gt;_&lt;service name&gt;). that’s why in the above steps when we have configured our Nginx server we could set our app endpoint to http://python_service_master&lt;instance number&gt;:3001.</p><h3>Step 4 — Deploy and scale</h3><p>We will deploy and scale our app with docker-compose with the following command:</p><pre>docker-compose up --build --scale master=2</pre><p>Docker-compose creates a container with our Nginx server, a container for each of the news and weather services and two instances of our main Api master(server).</p><p>We can check if everything is running with:</p><pre>docker ps --format &#39;{{.Names}}&#39;</pre><p>We must see the following containers running:</p><pre>nginx<br>python_service_master_2<br>python_service_master_1<br>python_service_news_1<br>python_service_weather_1</pre><p>Now time to check how the load balance works. Open two separate terminals and run:</p><p>First:</p><pre>docker logs python_service_master_1 -f</pre><p>Second:</p><pre>docker logs python_service_master_2 -f</pre><p>Now open Postman or your browser and navigate to <a href="http://localhost/news?country=gr">http://localhost/news?country=gr</a> or <a href="http://localhost/weather?city=amsterda">http://localhost/weather?city=amsterda</a>m for example.</p><p>We will use the free external apis for weather and news <strong>api.openweathermap.org</strong> &amp; <strong>newsapi.org</strong></p><p>If you look at the logs of the first terminal you will see that request was redirected to it.</p><p>Refresh or make the request again and you will see that the request will be redirected to the second terminal.. And on and on..</p><p>And that’s it!</p><p>Code on github where you can find the README file with further help on running and installing docker:</p><p><a href="https://github.com/manos-fr/News_Weather_Services_Python_Docker.git">GitHub - manos-fr/News_Weather_Services_Python_Docker: The architecture of python microservices using Docker. Client -&gt; Nginx -&gt; mainApi -&gt; microservices.. The respective service accepts the request, communicates with the database and returns the result to the main api and then to the client.</a></p><p><em>Enjoy </em>🚀🚀🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e20d421b1ad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>