MicroServices using Docker Compose — a Tiny Demonstration

Here is a super quick way to launch two services, one running a Python based Docker Container application and the other running a Docker Container running Redis Server. Docker compose create a custom bridge network allowing these two micro services to be able to discover and each other without having to expose ports.

Image for post

Here is the Dockerfile

FROM python:2.7-slim
ADD . /app
RUN pip install --trusted-host pypi.python.org Flask Redis
CMD ["python", "app.py"]

And here is the Python application app.py in the same folder (build context).

from flask import Flask
from redis import Redis, RedisError
import os
import socket
redis = Redis(host="redis-server", db=0, socket_connect_timeout=2, socket_timeout=2)app = Flask(__name__)@app.route("/")
def hello():
visits = redis.incr("counter")
except RedisError:
visits = "<i>cannot connect to Redis server to count</i>"
html = "<h3>Hello World!</h3>\n" \
"<b>Hostname:</b> {hostname}<br/>\n" \
"<b>Visits:</b> {visits}\n"
return html.format(hostname=socket.gethostname(), visits=visits)if __name__ == "__main__":
app.run(host='', port=80)

Note that the above application listens to port 80 which is also exposed in the Dockerfile and it expects the Redis Server’s hostname to be “redis-server” Let us test this.

Now let us create the docker-compose.yml file as below.

version: "3"
image: redis:alpine
- "6379"
- mynet
build: app
- "8080:80"
- mynet
- redis

Folder/file structure should look like this and you should be the top folder which has the docker-compose.yml file.

├── app
│ ├── Dockerfile
│ └── app.py
└── docker-compose.yml

Let us now launch the application.

docker-compose up -d

This will build the Python application image first before creating the container and use redis:alpine image to launch the Redi-Server.

Above assumes that port 8080 is free on the host machine. Let us now test this.

curl localhost:8080
<h3>Hello World!</h3><b>Hostname:</b> b3f2f3a731a6<br/><b>Visits:</b> 1
curl localhost:8080
<h3>Hello World!</h3><b>Hostname:</b> b3f2f3a731a6<br/><b>Visits:</b> 2

Notice that our app container is able to discover the IP address of the Redis Server using the host name “redis-server” as referred in the app.py

Thanks for your time. Please follow me for more such tiny demo snippets!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store