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:<code>Flask==2.3.2</code>
Your directory structure should now look like this:
<code>flask-app/ ├── Dockerfile ├── index.py └── requirements.txt</code>
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:
The above is the detailed content of Docker Hands-on: Learn Dockerfile, Container, Port Forwarding with Sample Flask Project. For more information, please follow other related articles on the PHP Chinese website!