How to Build a Containerised Python Web Application with Docker, Flask and uWSGI

CREATING A FLASK APP

$ python -m pip install flask
from flask import Flask, render_templateapp = Flask(__name__)
...@app.route('/', methods=['GET'])
def my_route_page_function():
return render_template('home.html')
<html>  <body>      <h1> Hello World! </h1>  </body></html>
$ set FLASK_APP='app.py'
$ flask run -p 5000

CONTAINERISING THE FLASK APP

#Use CentOS 7 as the container OSFROM centos:7
#Copy our files to the containerCOPY . ./app
#Install python and other programs required to run our appRUN yum install -y python-pip python36u python36u-libs python36-devel python36u-pip uwsgi which gcc#Change the working directory to /appWORKDIR /app#Changing the default python version from 2 to 3. We do this by first renaming the old python version and linking python filename to python3.6.RUN mv /usr/bin/python /usr/bin/python_oldRUN cd /usr/bin && ln -s python3.6 python#Install the required python packages listed in the requirements fileRUN python -m pip install -r requirements.txt#Run uwsgi with the configuration in the .ini fileCMD ["uwsgi","--ini","app.ini"]#Expose port 90 of the container to the outsideEXPOSE 90

USING uWSGI TO SERVE OUR FLASK APP

[uwsgi]wsgi-file = wsgi.pymaster = 5http = :90die-on-term = true
from app import app as application
if __name__ == "__main__": application.run()

RUNNING THE DOCKER CONTAINER

$ sudo docker build -t myapp:latest .
$ sudo docker run -p 9090:90 -t myapp:latest
$ sudo docker ps

--

--

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
Abdul Rahman

Abdul Rahman

37 Followers

Budding software engineer with experience in full-stack development and DevOps engineering. 📚 Love to code. ⌨️ Love to write.✒️