Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable code example

Example: cloud run error: container failed to start. failed to start and then listen on the port defined by the port environment variable.

In your code, you probably aren't listening for incoming HTTP requests, or you're listening for incoming requests on the wrong port.

As documented in the Cloud Run container runtime contract, your container must listen for incoming HTTP requests on the port that is defined by Cloud Run and provided in the $PORT environment variable.

If your container fails to listen on the expected port, the revision health check will fail, the revision will be in an error state and the traffic will not be routed to it.

For example, in Node.js with Express, you should use :

const port = process.env.PORT || 8080;
app.listen(port, () => {
  console.log('Hello world listening on port', port);
});
In Go:

port := os.Getenv("PORT")
if port == "" {
        port = "8080"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))

Tags:

Misc Example