cloudbuild.yaml 在 gcloud 计算引擎上为 python flask 应用构建管道

cloudbuild.yaml build pipeline for python flask app on gcloud compute engine

我有一个 Python Flask 应用程序,它需要一个未预装在 Gcloud 计算实例上的库 libsndfile1 — 这也是我无法通过应用程序引擎 运行 的原因。我已经设置了一个云构建管道,所以我的 cloudbuild.yaml 每次在我的存储库上推送到 master 时都会触发。

这是我的 2 个问题:

  1. cloudbuild.yaml 在哪里执行它的指令?
  2. 如何让 cloudbuild.yaml 执行 apt-get install libsndfile1 python3 python3-pip 然后执行 pip3 install requirements.txt 其中 requirements.txt 是存储库中触发云构建的文件?

免责声明:我是 docker 的超级新手,但如果您认为 docker 是唯一的方法,那么请解释如何做到这一点。

如果您对 App Engine 感兴趣,我的建议是将您的应用程序迁移到 Google App Engine Flexible 环境,您可以在其中为您的 Flask 应用程序选择 Custom runtime。只需在 Docker 文件中添加一个步骤即可安装所需的库。它看起来应该类似于:

FROM python:3.7
WORKDIR /app
COPY . /app
RUN apt-get update &&\
    apt-get install -y libsndfile1
RUN pip install -r requirements.txt
EXPOSE 8080
CMD ["gunicorn", "main:app", "-b", ":8080", "--timeout", "300"]

在此上下文中,您可以按照 documentation.

的相关部分,以相当简单的方式使用 Cloud Build 来自动化您的部署

现在关于你的问题。

(1) cloudbuild.yaml在哪里执行它的指令?

在这里您可以找到有关 Cloud Build 如何工作的所有相关信息 here 并回答您的第一个问题 Cloud Build 是一项单独的服务,并在 Docker 容器中运行构建的每个步骤在 Google 的基础设施中。

(2) 如何让 cloudbuild.yaml 执行 apt-get install libsndfile1 python3 python3-pip 然后执行 pip3 install requirements.txt 其中 requirements.txt 是触发云构建的 repo 中的文件。

请注意,Cloud Build 更适合与其他产品一起使用,例如 Cloud 运行、GKE、Cloud Functions 等。而且我看到 Cloud Build 在Compute Engine 的上下文将是 build VM images using Packer. In which case you'll need to create a custom image,所有依赖项都已安装在您的应用程序中。

解决方案的细节会因您的 Compute Engine 实例的 OS 而异。但您基本上需要执行以下操作:

  1. 将安装 libsndfile1 的启动脚本以及 requirements.txt 文件中指定的所有依赖项上传到云存储中的存储桶。
  2. 利用您可以使用 gcloud apply a startup script to running instances 的方式类似于。
gcloud compute instances add-metadata example-instance \
    --metadata startup-script-url=gs://bucket/file

还有 cloud builder for gcloud 3. 构建一个使用 2. 的 cloudbuild.yaml 文件并重启实例(如果您的应用程序正在生产中则不推荐,因为它会导致停机),方式类似于:

cloudbuild.yaml

steps:
- name: gcr.io/cloud-builders/gcloud
  args: ['compute', 'instances', 'add-metadata', 'example-instance','--metadata startup-script-url=gs://bucket/file']
- name: gcr.io/cloud-builders/gcloud
  args: ['compute', 'instances', 'reset', 'example-instance']
  1. 为云构建服务帐户提供足够的权限来执行该任务 (Compute Admin and Storage Admin)。
  2. 运行 构建。

我分享了前面的步骤,旨在回答您的具体问题,但我坚持认为我的建议是将应用程序迁移到具有自定义运行时的 App Engine 灵活环境,如前所述。