Create and run a Flask app using Docker

In this article, we will see how to create a Flask app, run the containerized Flask app using Docker and finally push the Docker images into DockerHub.

Create a Flask app

  1. Create a Flask app directory

     mkdir flask-app
     cd flask-app
    
  2. Create a Python virtual environment and activate it.

     python3 -m venv venv
     source venv/bin/activate
    
  3. Install Flask app

     pip install flask
    
  4. Create the requirements.txt file with the installed packages under the current environment.

     pip freeze > requirements.txt
    
  5. Create the app.py file

     # Import flask module
     from flask import Flask
    
     app = Flask(__name__)
    
     @app.route('/')
     def index():
         return "<h1> This is a flask app containerized with Docker. </h1>"
    
     # main driver function
     if __name__ == "__main__":
        app.run()
    
  6. The Flask app is ready. Now run using this script with Python

     flask run --host 0.0.0.0 --port 5000
    

Create a docker file for the Flask app

  1. Create a Dockerfile under the project directory.

    vim Dockerfile

     FROM python:3.10-slim-buster
    
     MAINTAINER Anjali
    
     # Create app directory
     WORKDIR /flask-app
    
     # Bundle app source
     COPY . .
    
     # Install the required dependencies
     RUN pip install -r requirements.txt
    
     EXPOSE 5000
    
     CMD [ "flask", "run","--host","0.0.0.0","--port","5000"]
    
  2. Create a docker image from this file. It will be created in the local image registry.

     docker build -t flask-app .
    
  3. Run the docker container

     sudo docker run -d -p 5000:5000 --name flask-app flask-app
    
  4. Now verify your container

     docker containers ls
    

Push the docker image to Dockerhub

  1. Login to docker hub with the username and password.
docker login
  1. Tag the local docker image with the docker hub username

     docker tag flask-app:latest <your_dockerhub_username>/flask-docker-app-img:latest
    
  2. Push the tagged image to docker hub

     docker push <your_dockerhub_username>/flask-docker-app-img:latest
    

We have seen how to create a simple flask app then create a docker image using Dockerfile and finally push the docker image to docker hub.

Keep Learning :)