How to containerize your Python Flask Server in 5 Minutes

Maximilian Ott
DevopSquare

--

Ever planned to dockerize your server to make it portable and scalable? Here is how to put your Flask Server into a container in less than 5 minutes.

Photo by frank mckenna on Unsplash

First, you need your Flask server. I am using a hello-world Flask server for demonstration. If you start from scratch then just follow my code example. If you already have a running application or just implemented code, you can use it as well. To make it work with the below introduced Dockerfile you would need to call the main file of the Flask server flask_app.py.

from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def
hello_world():
return 'Hello, World!'
if __name__ == '__main__':
print('Starting app')
app.run(host='0.0.0.0', debug=True)

As best practice already tells you should have a requirements.txt file for every python application you write. In this case you should at least have flask mentioned:

Flask==2.0.1

After having this, you can start with dockerizing the application. Please create on root level another file and name it Dockerfile. In the this file you specify what is supposed to happen when the docker image is built. For our case, we can start with some basic instructions:

FROM alpine:3.14RUN apk add --no-cache python3 py3-pipCOPY ./requirements.txt /app/requirements.txtWORKDIR /appRUN pip install -r requirements.txtCOPY . /appENTRYPOINT [ "python3" ]CMD [ "flask_app.py" ]

This is all you need to be able to dockerize your Flask server. Remember, in this case all the files flask_app.py, requirements.txt and Dockerfile are all on the same level.

To build the Docker image you would call this in your terminal after navigating to the level of your files.

docker build -t flask-tutorial:latest .

Afterwards you could either push it into your registry or directly run the Docker container to test your application. As Flask uses port 5000 per default, this port is exposed in the Docker container.

docker run -d -p 5000:5000 flask-tutorial

By simply calling localhost:5000/hello the dockerized Flask Server can be tested.

--

--

Avid Pragmatist trying to solve Business Problems — do you want to help?