Containerizing Python Flask App, and Deploy it into Openshift
Lets say for example i have a very simple python code, the goal is only to construct an html page and display it to user.
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template('index.html', message="Hello World..!!") if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)
An HTML template file,
<!DOCTYPE html> <html> <head> <title>Hello World Python</title> </head> <body> <h1> {{ message }} </h1> </body> </html>
And requirements.txt
flask
Above Python code can be build into a container image by using a simple Dockerfile,
FROM registry.access.redhat.com/ubi8/python-39:latest WORKDIR /deployment COPY app.py /deployment COPY templates/* /deployment/templates/ COPY requirements.txt /deployment RUN pip3 install -r requirements.txt EXPOSE 5000 CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
And make sure that the folder structure will be like below,
. +--- app.py +--- Dockerfile +--- README.md +--- requirements.txt +--- templates | +--- index.html
Now the next thing to do is deploying this app into Openshift, we can start by running below command in the code’s folder.
$ oc new-build --strategy docker --binary --name=containerized-hello-world-python $ oc start-build containerized-hello-world-python --from-dir=. --follow --wait $ oc new-app containerized-hello-world-python --name=containerized-hello-world-python $ oc create route edge --service=containerized-hello-world-python
Code can be accessed in below git repository
https://github.com/edwin/containerized-hello-world-python
Have fun with Python.