📅  最后修改于: 2023-12-03 14:41:13.420000             🧑  作者: Mango
If you are a Python developer looking to deploy your Flask application using Docker, this guide is for you!
Flask is a Python web framework that allows developers to build web applications quickly and easily. It is lightweight and flexible, making it a popular choice among developers.
Docker is a platform that allows developers to build, package, and deploy applications as containers. Containers are a lightweight and portable way to run applications, making them ideal for deployment in diverse environments.
By using Docker to deploy your Flask application, you can ensure that your application is running consistently across different environments. It also makes it easier to scale your application and deploy it to cloud-based services.
If you are new to Docker, start by downloading and installing the Docker Desktop app for your operating system. Here's a link to the download page.
To create a new Flask application, you should have Flask installed on your system. You can install Flask using pip
command.
pip install flask
After installation of Flask, create a new file app.py
and add the following code to it.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask Docker!"
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0")
This creates a simple Flask application that displays a message when you visit the homepage.
Next, create a Dockerfile
in the same directory as your app.py
file. This file will tell Docker how to build your application.
Add the following code to your Dockerfile
.
FROM python:3.8
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
This Dockerfile tells Docker to use a base Python 3.8 image, and copies all the files in your current directory to the /app
directory in the container. It then sets the working directory to /app
, installs the dependencies listed in requirements.txt
, and runs the app.py
file.
Now, build and run your Docker container with the following commands:
docker build -t flask-docker .
docker run -p 5000:5000 flask-docker
This builds and runs your Docker container. The -t
flag provides a name for your container, and the -p
flag maps the host port 5000
to the container port 5000
.
Visit http://localhost:5000
in your web browser to view your Flask application running in a Docker container!
Congratulations! You have successfully deployed a Flask application with Docker. This provides a consistent and portable way to deploy your application.