Python code as service in Docker

File Name: calc.py

#This runs as service.

from flask import Flask
app = Flask(__name__)

@app.route("/sum/<int:a>/<int:b>/")
def sum(a,b):
    sum = int(a) + int(b)
    #print "sum is", sum
    return str(sum)

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0')
    

————
File Name: requirements.txt

flask==0.12.1
————

File Name: Dockerfile

# Use an official Python runtime as a base image. Get this version from local system with >python –version
FROM python:2.7.10

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt. These are packages used in python script.
RUN pip install -r requirements.txt

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Define environment variable
ENV NAME calc

# Run calc.py when the container launches
ENTRYPOINT [“python”, “calc.py”]

————
>docker build -t calc .

>docker run -p 5000:5000 -it calc

In browser
http://localhost:5000/sum/1/2/
3

Note: Remove debug=true and run in background mode in real time.
————–
1. This makes easy to integrate with docker.
2. Load balancing need to be taken care separately.
3. Scaling is easy based on demand
4. Easy to deploy/redeploy patches
All advantages of micro services.
-o-

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s