This tutorial demonstrates building and deploying a simple Flask application using Docker. We'll cover creating a Dockerfile, building the image, running a container, and even pushing the image to Docker Hub. For those unfamiliar with Docker fundamentals, check out this previous post:
Let's get started with a hands-on example:
Project Setup:
index.py
containing this simple Flask application:# index.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int("5000"), debug=True)
Dockerfile
(no extension) with the following content:FROM python:3.13.1-alpine3.21
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "index.py"]
requirements.txt
in the "flask-app" directory:Flask==2.3.2
Your directory structure should now look like this:
flask-app/
├── Dockerfile
├── index.py
└── requirements.txt
Building and Running the Docker Image:
docker build -t flask-app .
docker images
docker run --name my-flask-app -d -p 5000:5000 flask-app
docker ps -a
http://127.0.0.1:5000
in your browser or using curl
:curl http://127.0.0.1:5000
docker container rm -f my-flask-app
docker image rm -f flask-app
Pushing to Docker Hub:
Before pushing to Docker Hub, create an account if you don't have one already. Then:
omerbsezer
with your Docker Hub username):docker tag flask-app omerbsezer/dev-to-flask-app:latest
docker push omerbsezer/dev-to-flask-app:latest
You can then see your image on Docker Hub. A screenshot would be placed here.
Conclusion:
This practical example demonstrates a complete workflow for containerizing a simple Python application with Docker. For more Docker tutorials, AWS, Kubernetes, Linux, DevOps, Ansible, Machine Learning, Generative AI, and SAAS content, follow these links:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3