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__)

@app.route('/')
def hello():
    return 'Hello, World!' 

if __name__ == '__main__':
    app.run(host='0.0.0.0')

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
WORKDIR /app
COPY app.py .
RUN pip install flask  
EXPOSE 5000
CMD ["python", "app.py"]

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

Conclusion

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.

ย