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
Create a Flask app directory
mkdir flask-app cd flask-app
Create a Python virtual environment and activate it.
python3 -m venv venv source venv/bin/activate
Install Flask app
pip install flask
Create the requirements.txt file with the installed packages under the current environment.
pip freeze > requirements.txt
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()
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
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"]
Create a docker image from this file. It will be created in the local image registry.
docker build -t flask-app .
Run the docker container
sudo docker run -d -p 5000:5000 --name flask-app flask-app
Now verify your container
docker containers ls
Push the docker image to Dockerhub
- Login to docker hub with the username and password.
docker login
Tag the local docker image with the docker hub username
docker tag flask-app:latest <your_dockerhub_username>/flask-docker-app-img:latest
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 :)