google-cloud-run

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


I built my container image, but when I try to deploy it from the gcloud command line or the Cloud Console, I get the following error: "Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable."


Solution

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

    Or you might not have a start script and modules setup on your package.json if you are using Node.js.

    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:

    // index.js
    const port = process.env.PORT || 8080;
    app.listen(port, () => {
      console.log('Hello world listening on port', port);
    });
    
    
    
    // package.json
        "engines": {
            "node": "16.x"
        },
        "scripts": {
            "start": "node index.js"
        },
    

    In Go:

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

    In python:

    app.run(port=int(os.environ.get("PORT", 8080)),host='0.0.0.0',debug=True)