Running Python Flask Application in a Docker Container

Python Flask applications can be deployed into Docker container but there a few steps you need to follow carefully

  1. Create a folder
  2. Place into this folder all your python code.
  3. Place into this folder a Dockerfile file (to be described below)
  4. Place in the folder a requirements.txt file (to be described below)
  5. build the Dockerfile 
    1. command: docker build -t <new image name>:<tag> .
    2. e.g. docker build -t flask-sample-server:latest .
  6. now run your image
    1. docker run -it -p <host port>:<container port> --name <host name> <new image name>:<tag>
    2. docker run -it -p 5002:5000 --name pyt flask-sample-server

Dockerfile

Dockerfile
FROM python:3

FROM ubuntu:latest
MAINTAINER Rajdeep Dua "dua_rajdeep@yahoo.com"
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD [ "python", "./db_ws_stream.py" ]


requirements.txt

requirements.txt
flask
flask_cors
mysql-connector-python==8.0.15


Python file

db_ws_stream.py
import time
from flask import Flask, Response
from flask_cors import CORS
from connect_to_db import DealTableLoader

app = Flask(__name__)
CORS(app)

@app.route('/')
@app.route('/index')
def index():
    return "Hello world"

@app.route('/streamTest')
def stream():
    def eventStream():
        while True:
            # wait for source data to be available, then push it
            yield get_message()+"\n"
    return Response(eventStream(), mimetype="text/event-stream")


def get_message():
    """this could be any function that blocks until data is ready"""
    time.sleep(1.0)
    s = time.ctime(time.time())
    return s

if __name__ == '__main__':
     app.run(port=5001, threaded=True, host=('0.0.0.0'))