Containerizing a Simple Python Flask App with Docker

Containerizing a Simple Python Flask App with Docker


1 min read

Creating the Python Flask App

First, we'll create a simple Python Flask app that returns "Hello, World!" at the root URL route ('/').

from flask import Flask
app = Flask(__name__)

def hello():
    return 'Hello, World!' 

if __name__ == '__main__':'')

This app creates a Flask instance, defines a route for the root URL, and returns "Hello, World!" when that route is accessed.

Building the Dockerfile

Next, we need to create a Dockerfile to build our image.

FROM python:3.7-alpine
RUN pip install flask  
CMD ["python", ""]

This Dockerfile starts from the official Python image, copies our app code into the /app directory, installs Flask, exposes port 5000, and sets the command to run our Flask app.

Building and Running the Docker Image

With the Dockerfile ready, we can now build the image:

docker build -t pyimage .

This will build the image and tag it as myimage.

Finally, we can run a container from this image:

docker run -p 8000:5000 pyimage


Containerizing this simple Python application was quick and straightforward with Docker. We created a Dockerfile, built an image, and ran a container all in just a few commands.