在 GOOGLE 云平台上使用 **Docker** 和 **Kubernetes** 部署 AI 模型的分步指南

在 GOOGLE 云平台上使用 DockerKubernetes 部署 AI 模型的分步指南

欢迎阅读此分步指南,了解如何开始构建深度学习模型,将其作为Flask的REST API提供,并使用Docker 和 Kubernetes 在 Google Cloud Platform (GCP) 上进行部署。在这篇文章中,重点将放在成功部署AI 模型的步骤上。

B2_I15

对于那些听说过 Docker 和 Kubernetes 但还没有尝试过的人来说,这是一本指南。要了解有关使用 Docker 和 Kubernetes 部署 AI 模型的 DevOps 管道工作流程的更多信息,请阅读 使用 Docker 和 Kubernetes部署 AI 模型的管道工作流程概述中的相关文章

由于本指南使用GCP 中的 Docker 和 Kubernetes,您无需费心在系统上安装 Docker 和 Kubernetes。

第 0 步:需要 GCP 的 Google 帐户

B2_I2

  • 步骤 0.1:在 Google 上创建帐户

首先,我们需要一个 Google 帐户。一旦我们的谷歌帐户准备就绪,我们需要设置 GCP。

一旦我们的 GCP 准备就绪,我们需要在 GCP 上创建一个虚拟机来运行项目。

  • 步骤 0.2:在 GCP 上创建 VM 实例

要创建 VM 实例,您需要从屏幕左上角的导航栏导航到 Compute Engine,然后选择 VM 实例。

然后选择“创建”。接下来,我们将选择操作系统、计算能力、磁盘大小和其他一些规格。

B2_I3-1 B2_I4

现在点击“创建”。

  • 步骤 0.3:使用 SSH 终端访问 VM 实例。

让我们开始设置 VM 实例以使用 Docker 进行部署。单击“SSH”以打开 SSH 终端。

第 1 步:在 VM 实例上设置 Docker

步骤 1.1:

首先,我们将从我们的 VM 实例中删除现有的 Docker,以进行 Docker 的全新安装。注意:如果您选择 CentOS 7 以外的操作系统,这些命令可能会有所不同。

sudo yum remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-selinux docker-engine-selinux docker-engine

步骤 1.2:

安装 Docker

sudo yum install -y yum-utils device-mapper-persistent-data lvm2
sudo yum-config-manager –add-repo https://download.docker.com/linux/centos/docker-ce.repo

sudo yum install docker-ce

步骤 1.3:

启动 Docker 并检查 Docker 是否正常运行。Docker安装完成后,我们将启动Docker

检查 docker 是否正常运行

sudo systemctl start docker

sudo docker run hello-world

如果你得到如下输出,你就可以进入下一步了:

Hello from Docker!
This message shows that your installation appears to be working correctly.To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the “hello-world” image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal.

步骤 1.4:在此 VM Docker 实例上包含用于深度学习模型的 Flask API

首先,创建一个名为“docker_project”的新目录

确保更改目录并移至该文件夹

mkdir docker_project

cd docker_project

步骤 1.4.1:创建 app.py

现在,我们将创建 app.py,其中将包含我们的深度学习模型,作为 Flask 上的 REST API。

确保在调用 app.run() 时将主机指定为 ‘0.0.0.0’ ,如 app.run(host=‘0.0.0.0’)。它使我们的应用程序可以在 localhost 和外部 IP 上使用。

vim app.py

将以下代码复制粘贴到 app.py

from keras.applications import ResNet50
from keras.preprocessing.image import img_to_array
from keras.applications import imagenet_utils
from PIL import Image
import numpy as np
import flask
import io
import tensorflow as tf

# initialize our Flask application and the Keras model
app = flask.Flask(__name__)
model = None

def load_model():
	# load the pre-trained Keras model (here we are using a model
	# pre-trained on ImageNet and provided by Keras, but you can
	# substitute in your own networks just as easily)
	global model
	model = ResNet50(weights="imagenet")
	global graph
	graph = tf.get_default_graph()

def prepare_image(image, target):
	# if the image mode is not RGB, convert it
	if image.mode != "RGB":
		image = image.convert("RGB")

	# resize the input image and preprocess it
	image = image.resize(target)
	image = img_to_array(image)
	image = np.expand_dims(image, axis=0)
	image = imagenet_utils.preprocess_input(image)

	# return the processed image
	return image

@app.route("/predict", methods=["POST"])
def predict():
	# initialize the data dictionary that will be returned from the
	# view
	data = {"success": False}

	# ensure an image was properly uploaded to our endpoint
	if flask.request.method == "POST":
		if flask.request.files.get("image"):
			# read the image in PIL format
			image = flask.request.files["image"].read()
			image = Image.open(io.BytesIO(image))

			# preprocess the image and prepare it for classification
			image = prepare_image(image, target=(224, 224))

			# classify the input image and then initialize the list
			# of predictions to return to the client
			with graph.as_default():
				preds = model.predict(image)
				results = imagenet_utils.decode_predictions(preds)
				data["predictions"] = []

				# loop over the results and add them to the list of
				# returned predictions
				for (imagenetID, label, prob) in results[0]:
					r = {"label": label, "probability": float(prob)}
					data["predictions"].append(r)

				# indicate that the request was a success
				data["success"] = True

	# return the data dictionary as a JSON response
	return flask.jsonify(data)

# if this is the main thread of execution first load the model and
# then start the server
if __name__ == "__main__":
	print(("* Loading Keras model and Flask starting server..."
		"please wait until server has fully started"))
	load_model()
	app.run(host='0.0.0.0')

image-20220917113619038

步骤 1.4.2:创建 requirements.txt

要安装我们的应用程序所需的依赖项,我们需要创建一个名为 requirements.txt 的文件。

该文件将包含我们的代码需要运行的包,例如 keras、flask 等。这样,无论我们将 Docker 容器运送到何处,底层服务器都将能够安装我们代码所需的依赖项。

vim requirements.txt

将以下内容复制到 requirements.txt 并像之前对 app.py 文件所做的那样保存并关闭

keras==2.2.4
tensorflow==1.14.0
flask
gevent
pillow
requests

步骤 1.4.3:创建 Dockerfile

Dockerfile 是一个文本文件,其中包含 Docker 守护程序在创建映像时调用的命令列表。Dockerfile 包含 Docker 运行应用程序所需知道的所有信息——要运行的基本 Docker 映像、项目代码的位置、它具有的任何依赖项以及启动时要运行的命令。这是一种自动化图像创建过程的简单方法。最好的部分是您在 Dockerfile 中编写的命令几乎与其等效的 Linux 命令相同。这意味着您实际上不必学习新语法来创建自己的 Dockerfile。

将以下内容复制到 Dockerfile 中。像以前一样保存并关闭(使用 ‘Esc’ 后跟 :x”)

Docker 读取这个文件来构建和运行项目。

vim Dockerfile

FROM python:3.6.10
COPY . /app
WORKDIR /app

RUN pip install -r requirements.txt

EXPOSE 5000

CMD ["python", "app.py"]
第 2 步:构建新的 Docker 映像

一旦你的Dockerfile准备好了。你可以继续构建你的 docker 容器。要构建我们的Docker 容器,请运行以下命令。

这指示 Docker 为位于我们当前工作主管“docker_project”中的代码构建一个容器。使用此命令,python 和 requitements.txt 中列出的包将安装在我们的Docker 容器中。

sudo docker build -t docker_project:latest .

第 3 步:运行测试

步骤 3.1:一旦构建了 Docker 镜像,我们将运行这个 docker 镜像并检查它是否工作。

检查容器的状态

sudo docker run -p 5000:5000 docker_project
sudo docker ps -a 

步骤 3.2:测试模型。

随着我们的模型运行,是时候测试它了。从 SSH 选项中B2_I6

  • 选择在 CLOUD SHELL 中运行。
  • 按原样执行第一个命令。

B2_I7

并运行以下命令:

curl -X POST -F image=@tiger.jpg 'http://localhost:5000/predict'

确保tiger.jpg 在您的当前目录中

你应该看到这样的结果:B2_I8

步骤 4.2:标记 Docker 容器(续…)

现在,让我们标记我们的容器。注意:根据您的图像 ID、Docker Hub ID 和项目名称更改突出显示的文本

sudo docker tag 79bf849d84c7 <Docker Hub ID> /docker_project

步骤 4.3:一旦我们的 docker 容器被标记,我们就可以将我们的容器推送到 Docker Hub。

(如果您导航到您的 Docker Hub 帐户,您应该会在您的存储库中看到 docker_project 应用程序)

sudo docker push <Docker Hub ID> /docker_project

第 5 步:创建 Kubernetes 集群以进行部署

步骤 5.1:导航到 GCP 中的 Kubernetes Engine

B2_I10

步骤 5.2:创建一个新的 Kubernetes 集群

B2_I11

之后点击“创建”。

要连接到此集群,请单击“连接”。

B2_I12

单击“在 Cloud Shell 中运行”。它将为 Kubernetes 集群打开一个新的控制台。

B2_I13

步骤 5.3:现在,我们在 Kubernetes 中运行 Docker 容器

让我们创建我们的应用程序的部署。

kubectl create deployment docker-project –image=<Docker Hub ID>/docker_project

第 6 步:运行 Kubernetes 服务

创建部署后,我们可以运行我们的应用程序。我们将使用 –port 指定我们希望在端口 5000 上运行我们的应用程序。

kubectl run docker-project –image=<Docker Hub ID>/docker_project –port 5000

第 7 步:公开部署

我们需要将 80 端口上的 pod 暴露给外界。

kubectl expose deployment docker-project –type=LoadBalancer –port 80 –target-port 5000

B2_I14

在任何 PC 上打开终端并运行以下命令:

curl -X POST -F image=@tiger.jpg ‘http://<External IP of your VM instance>/predict’

通过执行上述步骤,您现在已经成功构建了一个深度学习模型,将其作为 Flask 的 REST API 提供,并使用 Docker 和 Kubernetes 将其部署在 Google Cloud Platform (GCP) 上

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值