Heroku + nodo.error js (El proceso web no pudo vincularse a PORT PORT dentro de los 60 segundos posteriores al lanzamiento)


Tengo mi primer nodo.aplicación js (funciona bien localmente) - pero no puedo implementarlo a través de heroku (primera vez w/ heroku también). El código está abajo. ASÍ que no me deja escribir tanto código, así que solo diría que la ejecución del código localmente, así dentro de mi red no muestra ningún problema.

 var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');

Alguna idea ?

Author: user428900, 2013-03-29

15 answers

Heroku asigna dinámicamente a tu app un puerto, por lo que no puedes establecer el puerto en un número fijo. Heroku agrega el puerto al env, para que puedas sacarlo de allí. Cambia tu escucha a esto:

.listen(process.env.PORT || 5000)

De esa manera todavía escuchará el puerto 5000 cuando lo pruebes localmente, pero también funcionará en Heroku.

Puedes consultar los documentos de Heroku en el nodo.js aquí.

 723
Author: redhotvengeance,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-28 22:41:52

Tuve el mismo problema al usar el proyecto generado por angular-fullstack de yeoman y eliminar el parámetro IP funcionó para mí.

He reemplazado este código

server.listen(config.port, config.ip, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

Con

server.listen(config.port, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
 24
Author: vinesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-02 20:06:06

El error ocurre cuando Heroku no pudo enlazar el puerto o el nombre de host en server.listen(port, [host], [backlog], [callback]).

Lo que Heroku requiere es .listen(process.env.PORT) o .listen(process.env.PORT, '0.0.0.0')

De manera más genérica, para soportar otros entornos, use esto:

var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
    console.log('Listening on port %d', server_port);
});
 20
Author: Royce Lee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-21 05:35:27

Vale la pena mencionar que si su código no especifica un puerto, entonces no debería ser un proceso web y probablemente debería ser un proceso worker en su lugar.

Por lo tanto, cambie su Procfile para leer (con su comando específico completado):

worker: YOUR_COMMAND

Y luego también ejecutar en CLI:

$ heroku scale worker=1

 12
Author: zthomas.nc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-28 17:56:37

En mi caso, estaba usando el ejemplo de https://hapijs.com /

Para solucionar el problema he reemplazado

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

Con

server.connection({
    port: process.env.PORT || 3000 
});
 8
Author: nexuzzz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 05:55:32

Para aquellos que están pasando tanto un puerto como un host, tenga en cuenta que Heroku no se unirá a localhost.

Debes pasar 0.0.0.0 para el anfitrión.

Incluso si está utilizando el puerto correcto. Tuvimos que hacer este ajuste:

# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;

# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;

Luego puede iniciar el servidor, como de costumbre:

app.listen(port, host, function() {
  console.log("Server started.......");
});

Puedes ver más detalles aquí: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

 6
Author: gregb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 18:56:02

En mi caso, estaba usando Babel con el complemento babel-plugin-transform-inline-environment-variables. Al parecer, Heroku no establece la variable PORT env al hacer una implementación, por lo que process.env.PORT será reemplazado por undefined, y su código recurrirá al puerto de desarrollo del que Heroku no sabe nada.

 1
Author: Edgar Ortega,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-07 17:20:08

Los siguientes pasos resolvieron mi solución:

Editando el paquete .json as:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

Y Servidor.js as:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...
 1
Author: Naveen Kumar V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 11:54:33

De todas las soluciones que he intentado que nadie trabaje como se esperaba, estudio heroku por defecto.el archivo env debe mantener el PUERTO de la convención, el proceso.env.PUERTO, heroku por defecto buscará la palabra clave PUERTO.

Cancele cualquier cambio de nombre como APP_PORT= en su lugar use PORT= en su archivo env.

 1
Author: delino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-09 11:45:06

Tuve el mismo problema y cambié mi puerto de escucha de 3000 a (process.env.PORT / / 5000) solucionado el problema!!

 1
Author: Akshata Dabade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-26 13:22:54

Tuve el mismo problema que pude resolver el problema con reemplazar 'localhost' con IP que es '0.0.0.0'

 0
Author: Damith Asanka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-16 18:55:27

No se puede establecer un número fijo para el puerto, heroku lo asigna dinámicamente usando process.env.PORT. Pero se pueden agregar ambos, así process.env.PORT || 5000. Heroku usará el primero, y tu localhost usará el segundo.

Incluso puede agregar su función de devolución de llamada. Mira el siguiente código

app.listen(process.env.PORT || 5000, function() {
    console.log("Server started.......");
});
 0
Author: Aminu Kano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-07 06:48:31

Desde el proceso de heroku bash, pasa el valor de PORT PORT a tu aplicación node usando un analizador de opciones como yargs.

Aquí está un ejemplo de cómo usted podría hacer eso. En el objeto scripts, dentro del paquete.json, agrega un método de inicio "node server port port PORT PORT".

En su archivo de servidor, use yargs para obtener el valor de la opción port (port port PORT PORT) del método start:

const argv = require('yargs').argv;
const app = require('express')();

const port = argv.port || 8081;

app.listen(argv.port, ()=>{
    console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});

Ahora, cuando se inicie la aplicación, se vinculará al valor dinámicamente establecido de PORT PORT.

 0
Author: Aori Nevo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 03:25:48

Si, como yo, estás configurando Heroku para ejecutar un script desde tu archivo package.json en deploy, ¡asegúrate de no haber codificado el valor de PORT en ese script! Si lo haces, terminarás como yo y pasarás una hora tratando de averiguar por qué estás recibiendo este error.

 0
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-13 16:49:12

Tuve el mismo problema pero con express y apollo-server. La solución de aquí:

La única consideración especial que debe hacerse es permitir heroku para elegir el puerto en el que se despliega el servidor. De lo contrario, puede haber errores, como un tiempo de espera de solicitud.

Para configurar apollo-server para usar un puerto definido por Heroku en tiempo de ejecución, la función listen en su archivo de configuración se puede llamar con un puerto definido por el entorno PORTUARIO variable:

> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => { 
> console.log(`Server ready at ${url}`); });
 0
Author: Antony Petrocelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 18:52:28