[SOLVED] Port error on Google Cloud Run (GCP) when running a Python container service

Question

This Content is from Stack Overflow. Question asked by TheIronChef

I can’t get pyTelegramBot working on Google Cloud Run.

Disclaimer: I’m a noob. I’m relatively new to GCP, containers, and Python.

So I have a Python bot that I’ve written but I’ve simplified it down and its still not working.

Expected behaviour:

What I was trying to do was have a Python Telegram bot running constantly on Google Cloud Run and for it always to respond to requests. So that when I send messages to the bot on the Telegram app on my phone, it would always respond accordingly.

Observed behaviour:

After loading and running the code in a container (screenshot of my Cloud Run service setup options), it crashes after around a minute. During the time its running, it responds to requests properly and when I type /hi to the Telegram bot on my phone, I get a “Hello world” response, I can do this many times but after about 5 minutes (screenshot of what I see on Cloud Run) the container stops on Google Cloud Run with the following error (screenshot of error):

 The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information. Logs URL: https://console.cloud.google.com/logs/viewer?project=logical-fort-359211&resource=cloud_run_revision/service_name/telegram-test-bot/revision_name/telegram-test-bot-00001-jic&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22telegram-test-bot%22%0Aresource.labels.revision_name%3D%22telegram-test-bot-00001-jic%22  For more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start 

When I build and run the container locally, it works without problem, its stable and responds to all requests without problem.

What I’ve tried to do but haven’t really gotten anywhere:

  1. I’ve tried to start the container with different port settings settings: 80, 88, 443, 8080, 8443. No real change in behaviour.
  2. I built and ran the container locally on (Docker), got in via CLI, installed netstat and some other tools that I googled to see what specific port it listens on, but I couldn’t work it out. Googling pyTelegramBot for default ports also didn’t tell me what specific port I needed to open. If any. I’m guessing there must be some specific port that requests are coming in from to the bot but I couldn’t find an answer.
  3. I tried setting playing with the “`EVN PORT“ setting in the Dockerfile. But it also didn’t make much difference. I paired it up with what I had configured the container image through Google Cloud Run but no change in observed behaviour.

Code and logs:

telegram_test_bot.py:

import telebot

# I've intentionally starred this out
bot = telebot.TeleBot("5508342368:AAGTs5s-xuQBT5kbmhu_*********") 

@bot.message_handler(commands=['hi'])
def handle_command(message):
    bot.reply_to(message, "Hello world")
    
bot.polling()

Dockerfile:

FROM python:3

ADD telegram_test_bot.py /

RUN pip install pyTelegramBotAPI

CMD [ "python", "./telegram_test_bot.py" ]

Creating the container and having it be stored on Google Container Registry:

xxxxxxx@cloudshell:~/telegram_test_bot (logical-bank-359221)$ gcloud builds submit --tag gcr.io/logical-bank-359221/test_bot_image .
Creating temporary tarball archive of 2 file(s) totalling 338 bytes before compression.
Uploading tarball of [.] to [gs://logical-bank-359221_cloudbuild/source/1661579400.083045-20d26c4f7c23435d94ddaf6ed9d394ca.tgz]
Created [https://cloudbuild.googleapis.com/v1/projects/logical-bank-359221/locations/global/builds/2c92efa5-0669-4c99-a8cc-a7f350c50676].
Logs are available at [ https://console.cloud.google.com/cloud-build/builds/2c92efa5-0669-4c99-a8cc-a7f350c50676?project=518622666562 ].
------------------------------------------------------------------------------------------------------------------------------------------------------- REMOTE BUILD OUTPUT -------------------------------------------------------------------------------------------------------------------------------------------------------
starting build "2c92efa5-0669-4c99-a8cc-a7f350c50676"

FETCHSOURCE
Fetching storage object: gs://logical-bank-359221_cloudbuild/source/1661579400.083045-20d26c4f7c23435d94ddaf6ed9d394ca.tgz#1661579400971313
Copying gs://logical-bank-359221_cloudbuild/source/1661579400.083045-20d26c4f7c23435d94ddaf6ed9d394ca.tgz#1661579400971313...
/ [1 files][  470.0 B/  470.0 B]
Operation completed over 1 objects/470.0 B.
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
Sending build context to Docker daemon  3.072kB
Step 1/4 : FROM python:3
3: Pulling from library/python
1671565cc8df: Pulling fs layer
3e94d13e55e7: Pulling fs layer
fa9c7528c685: Pulling fs layer
53ad072f9cd1: Pulling fs layer
d6b983117533: Pulling fs layer
d8092d56ded5: Pulling fs layer
c71afc637d59: Pulling fs layer
864a10b3c704: Pulling fs layer
4334b2fe8293: Pulling fs layer
d8092d56ded5: Waiting
53ad072f9cd1: Waiting
d6b983117533: Waiting
c71afc637d59: Waiting
4334b2fe8293: Waiting
864a10b3c704: Waiting
3e94d13e55e7: Verifying Checksum
3e94d13e55e7: Download complete
fa9c7528c685: Verifying Checksum
fa9c7528c685: Download complete
1671565cc8df: Verifying Checksum
1671565cc8df: Download complete
53ad072f9cd1: Verifying Checksum
53ad072f9cd1: Download complete
d8092d56ded5: Verifying Checksum
d8092d56ded5: Download complete
864a10b3c704: Download complete
4334b2fe8293: Verifying Checksum
4334b2fe8293: Download complete
c71afc637d59: Verifying Checksum
c71afc637d59: Download complete
d6b983117533: Verifying Checksum
d6b983117533: Download complete
1671565cc8df: Pull complete
3e94d13e55e7: Pull complete
fa9c7528c685: Pull complete
53ad072f9cd1: Pull complete
d6b983117533: Pull complete
d8092d56ded5: Pull complete
c71afc637d59: Pull complete
864a10b3c704: Pull complete
4334b2fe8293: Pull complete
Digest: sha256:745efdfb7e4aac9a8422bd8c62d8bc35a693e8979a240d29677cb03e6aa91052
Status: Downloaded newer image for python:3
 d25a66380b10
Step 2/4 : ADD telegram_test_bot.py /
 b609762a1056
Step 3/4 : RUN pip install pyTelegramBotAPI
 Running in 7a3126f23a77
Collecting pyTelegramBotAPI
  Downloading pyTelegramBotAPI-4.7.0.tar.gz (210 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 210.7/210.7 kB 18.7 MB/s eta 0:00:00
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'done'
Collecting requests
  Downloading requests-2.28.1-py3-none-any.whl (62 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 kB 10.2 MB/s eta 0:00:00
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.12-py2.py3-none-any.whl (140 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.4/140.4 kB 22.0 MB/s eta 0:00:00
Collecting charset-normalizer<3,>=2
  Downloading charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Collecting certifi>=2017.4.17
  Downloading certifi-2022.6.15-py3-none-any.whl (160 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 160.2/160.2 kB 24.4 MB/s eta 0:00:00
Collecting idna<4,>=2.5
  Downloading idna-3.3-py3-none-any.whl (61 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.2/61.2 kB 10.3 MB/s eta 0:00:00
Building wheels for collected packages: pyTelegramBotAPI
  Building wheel for pyTelegramBotAPI (setup.py): started
  Building wheel for pyTelegramBotAPI (setup.py): finished with status 'done'
  Created wheel for pyTelegramBotAPI: filename=pyTelegramBotAPI-4.7.0-py3-none-any.whl size=192810 sha256=68ed7e6a9e295e69d53c1cde07f06da81bcd56fa7e784ce113b61d5ae3052721
  Stored in directory: /root/.cache/pip/wheels/66/e7/a6/1fd4c399389e73024eae09e705cf0554ab1706465ac0c6e913
Successfully built pyTelegramBotAPI
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests, pyTelegramBotAPI
Successfully installed certifi-2022.6.15 charset-normalizer-2.1.1 idna-3.3 pyTelegramBotAPI-4.7.0 requests-2.28.1 urllib3-1.26.12
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

[notice] A new release of pip available: 22.2.1 -> 22.2.2
[notice] To update, run: pip install --upgrade pip
Removing intermediate container 7a3126f23a77
 42605d43b39c
Step 4/4 : CMD [ "python", "./telegram_test_bot.py" ]
 Running in d944d85efa80
Removing intermediate container d944d85efa80
 9877e24eadcd
Successfully built 9877e24eadcd
Successfully tagged gcr.io/logical-bank-359221/test_bot_image:latest
PUSH
Pushing gcr.io/logical-bank-359221/test_bot_image
The push refers to repository [gcr.io/logical-bank-359221/test_bot_image]
498a8e9bfed3: Preparing
df7847f5e574: Preparing
bfc1deb8136e: Preparing
1f123186824c: Preparing
3d6eb1152931: Preparing
100796cdf3b1: Preparing
54acb5a6fa0b: Preparing
8d51c618126f: Preparing
9ff6e4d46744: Preparing
a89d1d47b5a1: Preparing
655ed1b7a428: Preparing
100796cdf3b1: Waiting
54acb5a6fa0b: Waiting
8d51c618126f: Waiting
9ff6e4d46744: Waiting
a89d1d47b5a1: Waiting
655ed1b7a428: Waiting
3d6eb1152931: Layer already exists
bfc1deb8136e: Layer already exists
1f123186824c: Layer already exists
8d51c618126f: Layer already exists
54acb5a6fa0b: Layer already exists
100796cdf3b1: Layer already exists
9ff6e4d46744: Layer already exists
a89d1d47b5a1: Layer already exists
655ed1b7a428: Layer already exists
df7847f5e574: Pushed
498a8e9bfed3: Pushed
latest: digest: sha256:3abc7582a687051656e262480bc6fc6db2e9b2cf761e18a84b4d98e6b6801c9f size: 2636
DONE
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ID: 2c92efa5-0669-4c99-a8cc-a7f350c50676
CREATE_TIME: 2022-08-27T05:50:02+00:00
DURATION: 40S
SOURCE: gs://logical-bank-359221_cloudbuild/source/1661579400.083045-20d26c4f7c23435d94ddaf6ed9d394ca.tgz
IMAGES: gcr.io/logical-bank-359221/test_bot_image (+1 more)
STATUS: SUCCESS
xxxxxxx@cloudshell:~/telegram_test_bot (logical-bank-359221)$

Google Cloud run log:

{
  "protoPayload": {
    "@type": "type.googleapis.com/google.cloud.audit.AuditLog",
    "status": {
      "code": 9,
      "message": "Ready condition status changed to False for Revision telegram-test-bot-00001-jic with message: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.nnLogs URL: https://console.cloud.google.com/logs/viewer?project=logical-bank-359221&resource=cloud_run_revision/service_name/telegram-test-bot/revision_name/telegram-test-bot-00001-jic&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22telegram-test-bot%22%0Aresource.labels.revision_name%3D%22telegram-test-bot-00001-jic%22 nFor more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start"
    },
    "serviceName": "run.googleapis.com",
    "resourceName": "namespaces/logical-bank-359221/revisions/telegram-test-bot-00001-jic",
    "response": {
      "metadata": {
        "name": "telegram-test-bot-00001-jic",
        "namespace": "518622666562",
        "selfLink": "/apis/serving.knative.dev/v1/namespaces/518622666562/revisions/telegram-test-bot-00001-jic",
        "uid": "23f46b3d-ca6e-427e-81bf-946848aa1177",
        "resourceVersion": "AAXnMt74Vh4",
        "generation": 1,
        "creationTimestamp": "2022-08-27T06:05:10.428910Z",
        "labels": {
          "serving.knative.dev/route": "telegram-test-bot",
          "serving.knative.dev/configuration": "telegram-test-bot",
          "serving.knative.dev/configurationGeneration": "1",
          "serving.knative.dev/service": "telegram-test-bot",
          "serving.knative.dev/serviceUid": "9ff9148c-f1e0-428c-967d-8d03ec384ca5",
          "cloud.googleapis.com/location": "us-central1"
        },
        "annotations": {
          "run.googleapis.com/client-name": "cloud-console",
          "serving.knative.dev/creator": "xxxxxxxx@gmail.com",
          "autoscaling.knative.dev/maxScale": "100",
          "run.googleapis.com/cpu-throttling": "true"
        },
        "ownerReferences": [
          {
            "kind": "Configuration",
            "name": "telegram-test-bot",
            "uid": "9625ff54-4278-46f4-a425-9b5de34be2f8",
            "apiVersion": "serving.knative.dev/v1",
            "controller": true,
            "blockOwnerDeletion": true
          }
        ]
      },
      "apiVersion": "serving.knative.dev/v1",
      "kind": "Revision",
      "spec": {
        "containerConcurrency": 80,
        "timeoutSeconds": 300,
        "serviceAccountName": "518622666562-compute@developer.gserviceaccount.com",
        "containers": [
          {
            "name": "test_bot_image-1",
            "image": "gcr.io/logical-bank-359221/test_bot_image@sha256:3abc7582a687051656e262480bc6fc6db2e9b2cf761e18a84b4d98e6b6801c9f",
            "ports": [
              {
                "name": "http1",
                "containerPort": 8080
              }
            ],
            "resources": {
              "limits": {
                "cpu": "1000m",
                "memory": "512Mi"
              }
            }
          }
        ]
      },
      "status": {
        "observedGeneration": 1,
        "conditions": [
          {
            "type": "Ready",
            "status": "False",
            "reason": "HealthCheckContainerError",
            "message": "The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.nnLogs URL: https://console.cloud.google.com/logs/viewer?project=logical-bank-359221&resource=cloud_run_revision/service_name/telegram-test-bot/revision_name/telegram-test-bot-00001-jic&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22telegram-test-bot%22%0Aresource.labels.revision_name%3D%22telegram-test-bot-00001-jic%22 nFor more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start",
            "lastTransitionTime": "2022-08-27T06:09:18.751262Z"
          },
          {
            "type": "Active",
            "status": "True",
            "lastTransitionTime": "2022-08-27T06:05:16.218844Z",
            "severity": "Info"
          },
          {
            "type": "ContainerHealthy",
            "status": "False",
            "reason": "HealthCheckContainerError",
            "message": "The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.nnLogs URL: https://console.cloud.google.com/logs/viewer?project=logical-bank-359221&resource=cloud_run_revision/service_name/telegram-test-bot/revision_name/telegram-test-bot-00001-jic&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22telegram-test-bot%22%0Aresource.labels.revision_name%3D%22telegram-test-bot-00001-jic%22 nFor more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start",
            "lastTransitionTime": "2022-08-27T06:09:18.751262Z"
          },
          {
            "type": "ResourcesAvailable",
            "status": "True",
            "lastTransitionTime": "2022-08-27T06:05:16.024073Z"
          },
          {
            "type": "Retry",
            "status": "True",
            "reason": "ImmediateRetry",
            "message": "System will retry after 0:00:00 from lastTransitionTime for attempt 0.",
            "lastTransitionTime": "2022-08-27T06:09:18.751262Z",
            "severity": "Info"
          }
        ],
        "logUrl": "https://console.cloud.google.com/logs/viewer?project=logical-bank-359221&resource=cloud_run_revision/service_name/telegram-test-bot/revision_name/telegram-test-bot-00001-jic&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22telegram-test-bot%22%0Aresource.labels.revision_name%3D%22telegram-test-bot-00001-jic%22",
        "imageDigest": "gcr.io/logical-bank-359221/test_bot_image@sha256:3abc7582a687051656e262480bc6fc6db2e9b2cf761e18a84b4d98e6b6801c9f"
      },
      "@type": "type.googleapis.com/google.cloud.run.v1.Revision"
    }
  },
  "insertId": "mrnhofc3ce",
  "resource": {
    "type": "cloud_run_revision",
    "labels": {
      "service_name": "telegram-test-bot",
      "project_id": "logical-bank-359221",
      "location": "us-central1",
      "revision_name": "telegram-test-bot-00001-jic",
      "configuration_name": "telegram-test-bot"
    }
  },
  "timestamp": "2022-08-27T06:05:18.487736Z",
  "severity": "ERROR",
  "logName": "projects/logical-bank-359221/logs/cloudaudit.googleapis.com%2Fsystem_event",
  "receiveTimestamp": "2022-08-27T06:09:19.760286025Z"
}

Somebody please help!! This is doing my head in! Let me know if there’s something else I can do to diagnose the issue. Remember, I a proper noob. Spoonfeed me please 🙂

Solution

Your difficulty is this. The user-provided container was unable to launch and begin listening on the port specified by the environment variable PORT=8080. Neither a TCP listener on port 8080 nor an HTTP server are launched by your container. Your application should be rewritten to accept HTTP requests and respond to them.


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of
CC BY-SA 2.5.
CC BY-SA 3.0.
CC BY-SA 4.0.

people found this article helpful. What about you?