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:<code class="language-python"># 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)</code>
Dockerfile
(no extension) with the following content:<code class="language-dockerfile">FROM python:3.13.1-alpine3.21 WORKDIR /app COPY . /app RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "index.py"]</code>
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:
<code class="language-bash">docker build -t flask-app .</code>
<code class="language-bash">docker images</code>
<code class="language-bash">docker run --name my-flask-app -d -p 5000:5000 flask-app</code>
<code class="language-bash">docker ps -a</code>
http://127.0.0.1:5000
in your browser or using curl
:<code class="language-bash">curl http://127.0.0.1:5000</code>
<code class="language-bash">docker container rm -f my-flask-app</code>
<code class="language-bash">docker image rm -f flask-app</code>
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):<code class="language-bash">docker tag flask-app omerbsezer/dev-to-flask-app:latest</code>
<code class="language-bash">docker push omerbsezer/dev-to-flask-app:latest</code>
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!