"Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable."

"Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable."

我正在尝试构建一个容器映像,稍后我将使用它来更新虚拟机内部的代码。 docker 图像工作正常,因为我可以在我的终端内构建和 运行 它。但是,当我尝试将其部署到云 运行 时,我一直收到错误消息:“云 运行 错误:容器无法启动。无法启动,然后监听 PORT 环境变量定义的端口”我该如何解决这个错误?

构建日志包含以下内容:

Deploying container to Cloud Run service [SERVICE] in project [PROJECT_ID] region [REGION]
Deploying...
Creating Revision.......................................................................................................................................................................failed
Deployment failed
ERROR: (gcloud.run.deploy) Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.

修订日志包含以下内容:

{
  "protoPayload": {
    "@type": "type.googleapis.com/google.cloud.audit.AuditLog",
    "status": {
      "code": 9,
      "message": "Ready condition status changed to False for Revision {REVISION_NAME} with message: Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.\n\nLogs URL:{URL_LINK}"
    },
    "serviceName": "run.googleapis.com",
    "resourceName": "{REVISION_NAME}",
    "response": {
      "metadata": {
        "name": "{REVISION_NAME}",
        "namespace": "{NAMESPACE}",
        "selfLink": "{SELFLINK}",
        "uid": "{UID}",
        "resourceVersion": "{RESOURCEVER}",
        "generation": 1,
        "creationTimestamp": "{TIMESTAMP}",
        "labels": {
          "serving.knative.dev/route": "{SERVICE}",
          "serving.knative.dev/configuration": "{SERVICE}",
          "serving.knative.dev/configurationGeneration": "15",
          "serving.knative.dev/service": "{SERVICE}",
          "serving.knative.dev/serviceUid": "{SERVICE_UID}",
          "cloud.googleapis.com/location": "{REGION}"
        },
        "annotations": {
          "run.googleapis.com/client-name": "gcloud",
          "serving.knative.dev/creator": "{NAMESPACE}@cloudbuild.gserviceaccount.com",
          "client.knative.dev/user-image": "gcr.io/{PROJECT_ID}/{IMAGE}",
          "run.googleapis.com/client-version": "357.0.0",
          "autoscaling.knative.dev/maxScale": "100"
        },
        "ownerReferences": [
          {
            "kind": "Configuration",
            "name": "{SERVICE}",
            "uid": "{UID}",
            "apiVersion": "serving.knative.dev/v1",
            "controller": true,
            "blockOwnerDeletion": true
          }
        ]
      },
      "apiVersion": "serving.knative.dev/v1",
      "kind": "Revision",
      "spec": {
        "containerConcurrency": 80,
        "timeoutSeconds": 300,
        "serviceAccountName": "{NAMESPACE}-compute@developer.gserviceaccount.com",
        "containers": [
          {
            "image": "gcr.io/{PROJECT_ID}/{IMAGE}",
            "ports": [
              {
                "name": "h2c",
                "containerPort": 8080
              }
            ],
            "resources": {
              "limits": {
                "cpu": "1000m",
                "memory": "512Mi"
              }
            }
          }
        ]
      },
      "status": {
        "observedGeneration": 1,
        "conditions": [
          {
            "type": "Ready",
            "status": "False",
            "reason": "HealthCheckContainerError",
            "message": "Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.\n\nLogs URL:{LOG_LINK}",
            "lastTransitionTime": "{TIME}"
          },
          {
            "type": "Active",
            "status": "Unknown",
            "reason": "Reserve",
            "lastTransitionTime": "{TIME}",
            "severity": "Info"
          },
          {
            "type": "ContainerHealthy",
            "status": "False",
            "reason": "HealthCheckContainerError",
            "message": "Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.\n\nLogs URL:{LOG_LINK}",
            "lastTransitionTime": "{TIME}"
          },
          {
            "type": "ResourcesAvailable",
            "status": "True",
            "lastTransitionTime": "{TIME}"
          },
          {
            "type": "Retry",
            "status": "True",
            "reason": "ImmediateRetry",
            "message": "System will retry after 0:00:00 from lastTransitionTime for attempt 0.",
            "lastTransitionTime": "{TIME}",
            "severity": "Info"
          }
        ],
        "logUrl": "{LOG_LINK}",
        "imageDigest": "gcr.io/{PROJECT_ID}/{IMAGE_SHA}"
      },
      "@type": "type.googleapis.com/google.cloud.run.v1.Revision"
    }
  },
  "insertId": "{ID}",
  "resource": {
    "type": "cloud_run_revision",
    "labels": {
      "location": "{REGION}",
      "configuration_name": "{SERVICE}",
      "service_name": "{SERVICE}",
      "project_id": "{PROJECT_ID}",
      "revision_name": "{REVISION_NAME}"
    }
  },
  "timestamp": "{TIME}",
  "severity": "ERROR",
  "logName": "projects/{PROJECT_ID}/logs/cloudaudit.googleapis.com%2Fsystem_event",
  "receiveTimestamp": "{TIME}"
}

这是我的 cloudbuild.yaml:

steps:
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t', 'gcr.io/PROJECT_ID/IMAGE', '.']
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/PROJECT_ID/IMAGE']
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  entrypoint: gcloud
  args: ['run', 'deploy', 'SERVICE-NAME', '--image', 'gcr.io/PROJECT_ID/IMAGE', '--region', 'REGION', '--port', '8080']
images:
- gcr.io/PROJECT_ID/IMAGE

这是我的 Dockerfile:

FROM python:3.9.7-slim-buster

WORKDIR /app

COPY . .

CMD [ "python3", "hello.py" ]

这是hello.py中的代码:

print("Hello World")

当 Cloud 运行 启动您的容器时,会向容器发送健康检查。您的容器没有响应健康检查。因此,Cloud 运行 确定您的服务失败。

云 运行 要求容器提供 service/process/program 侦听和响应 HTTP 请求。

您的 hello.py 文件仅将消息打印到标准输出。您的程序没有启动进程来侦听请求。

将您的示例转换为工作程序的一个非常简单的示例:

import os

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
        return "Hello world"

if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))

注意:您需要将文件 requirements.txt 添加到您的构建中以包含 Flask。在与 Dockerfile.

相同的位置创建 requirements.txt

requirements.txt:

Flask==2.0.1