为啥 Heroku 服务器在几分钟后关闭?

Posted

技术标签:

【中文标题】为啥 Heroku 服务器在几分钟后关闭?【英文标题】:Why the heroku server shut downs after few minutes?为什么 Heroku 服务器在几分钟后关闭? 【发布时间】:2021-11-25 10:51:43 【问题描述】:

我为一个项目开发了一个 REST API,并尝试将其上传到 Heroku。在我启动应用程序的那一刻,它会运行几分钟并崩溃。

任何帮助都是有用的,在此先感谢。 ????

我使用的一些数据、表格和变量是西班牙语,抱歉。 :/

结构

node_modules requests(一些要测试的 http 请求) .gitignore app.js package-lock.json package.json

enter image description here

代码

这是我在项目中使用的唯一的 JavaScript 文件。 PS:为了安全起见,我更改了连接信息

const express = require('express');
const mysql = require('mysql');
const bcrypt = require('bcrypt');

const bodyParser = require('body-parser');

const PORT = process.env.PORT || 3050;

const app = express();
app.use(express.json());

//MySql
var cnx = mysql.createConnection(
    host: 'any_host',
    user: 'any_user',
    password: 'any_password',
    database: 'any_database'
);

//rutas
app.get('/', (req, res) => 
    res.send('Bienvenido a mi API');
);

app.get('/usuarios', (req, res) => 
    const sql = 'SELECT * FROM usuario';
    cnx.query(sql, (error, results) => 
        if (error) throw error;

        if(results.length > 0)
            res.json(results);
        else
            res.send('No hay resultados')
        
    );
);

app.get('/usuarios/:id', (req, res) => 

    const  id  = req.params;
    const sql = `SELECT * FROM usuario WHERE idusuario = $id`;

    cnx.query(sql, (error, result) => 
        if (error) throw error;

        if (resul.length > 0) 
            res.json(result);
        else
            res.send('No hay resultados');
        
    );
);

app.post('/add', (req, res) => 
    const sql = 'INSERT INTO usuario SET ?';

    const saltRounds = 10;
    const contraseñaHash = bcrypt.hash(req.body.contraseña, saltRounds);
    const usuarioObj = 
        cuenta: req.body.cuenta,
        contraseña: contraseñaHash,
        nombre: req.body.nombre,
        apellido: req.body.apellido
    ;

    cnx.query(sql, usuarioObj, error => 
        if (error) throw error;
        res.send('Usuario creado');
    );
);

app.put('/update/:id', (req, res) => 
    const  id  = req.params;
    const  cuenta, contraseña, nombre, apellido  = req.body;
    var sql = mysql.format(
        'UPDATE usuario SET cuenta = ?, contraseña = ?, nombre = ?, apellido = ? WHERE idusuario = ?',
        [cuenta, contraseña, nombre, apellido, id]
    );

    cnx.query(sql, error => 
        if(error) throw error;
        res.send('Usuario actualizado!');
    );
);

app.delete('/delete/:id', (req, res) => 
    const  id  = req.params;
    var sql = `DELETE FROM usuario WHERE idusuario = $id`;

    cnx.query(sql, error =>
        if(error) throw error;
        res.send('Usuario eliminado!');
    );
);

// Check connect
cnx.connect(error => 
    if (error) throw error;
    console.log('Corriendo base de datos');
);

app.listen(PORT, () => console.log(`El servidor esta corriendo en el puerto $PORT`));

这是 package.json


  "name": "api_madison",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": 
    "start": "node app.js"
  ,
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": 
    "nodemon": "2.0.12"
  ,
  "dependencies": 
    "bcrypt": "5.0.1",
    "body-parser": "1.19.0",
    "mysql": "2.18.1",
    "express": "4.17.1"
  

这是 .gitignore

/node_modules/

HEROKU

API 可以正常工作几分钟,然后停止工作。

API 运行良好

enter image description here

API 下降

enter image description here

CLI HEROKU

当我启动命令heroku logs --tail 时,会出现这种情况

enter image description here

2021-10-05T06:03:15.581449+00:00 heroku[router]: at=info method=GET path="/usuarios" host=apimadison.herokuapp.com request_id=6deca321-588c-411d-b81a-e231eacb6eaf fwd="190.42.207.86" dyno=web.1 connect=0ms service=38ms status=200 bytes=2352 protocol=https
2021-10-05T06:04:15.512510+00:00 app[web.1]: events.js:377
2021-10-05T06:04:15.512519+00:00 app[web.1]: throw er; // Unhandled 'error' event
2021-10-05T06:04:15.512519+00:00 app[web.1]: ^
2021-10-05T06:04:15.512520+00:00 app[web.1]:
2021-10-05T06:04:15.512521+00:00 app[web.1]: Error: Connection lost: The server closed the connection.
2021-10-05T06:04:15.512521+00:00 app[web.1]: at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:112:13)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:94:28)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:526:10)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at Socket.emit (events.js:412:35)
2021-10-05T06:04:15.512522+00:00 app[web.1]: at endReadableNT (internal/streams/readable.js:1334:12)
2021-10-05T06:04:15.512523+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:82:21)
2021-10-05T06:04:15.512524+00:00 app[web.1]: Emitted 'error' event on Connection instance at:
2021-10-05T06:04:15.512526+00:00 app[web.1]: at Connection._handleProtocolError (/app/node_modules/mysql/lib/Connection.js:423:8)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol.emit (events.js:400:28)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol._delegateError (/app/node_modules/mysql/lib/protocol/Protocol.js:398:10)
2021-10-05T06:04:15.512527+00:00 app[web.1]: at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:116:8)
2021-10-05T06:04:15.512528+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:94:28)
2021-10-05T06:04:15.512528+00:00 app[web.1]: [... lines matching original stack trace ...]
2021-10-05T06:04:15.512529+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:82:21) 
2021-10-05T06:04:15.512529+00:00 app[web.1]: fatal: true,
2021-10-05T06:04:15.512529+00:00 app[web.1]: code: 'PROTOCOL_CONNECTION_LOST'
2021-10-05T06:04:15.512529+00:00 app[web.1]: 
2021-10-05T06:04:15.525602+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2021-10-05T06:04:15.525824+00:00 app[web.1]: npm ERR! errno 1
2021-10-05T06:04:15.530954+00:00 app[web.1]: npm ERR! api_madison@1.0.0 start: `node .`
2021-10-05T06:04:15.531050+00:00 app[web.1]: npm ERR! Exit status 1
2021-10-05T06:04:15.531156+00:00 app[web.1]: npm ERR!
2021-10-05T06:04:15.531244+00:00 app[web.1]: npm ERR! Failed at the api_madison@1.0.0 start script.
2021-10-05T06:04:15.531322+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2021-10-05T06:04:15.540307+00:00 app[web.1]:
2021-10-05T06:04:15.542432+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-10-05T06:04:15.542504+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2021-10-05T06_04_15_531Z-debug.log
2021-10-05T06:04:15.709436+00:00 heroku[web.1]: Process exited with status 1
2021-10-05T06:04:15.760747+00:00 heroku[web.1]: State changed from up to crashed
2021-10-05T06:07:24.606771+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/usuarios" host=apimadison.herokuapp.com request_id=231283ff-9748-4690-bd38-9f6e358673fe fwd="190.42.207.86" dyno= connect= service= status=503 bytes= protocol=https

顺便说一句,使用heroku restart,API 可以再次工作,但有同样的问题。

感谢您的宝贵时间????

【问题讨论】:

您的连接似乎有问题。您在第一次查询时遇到错误(method=GET path="/usuarios")。所以你可以检查你的数据库连接信息和设置。 第一行是关于/usuarios的负载并返回status = 200。但我会检查数据库。 ???? 【参考方案1】:

我怀疑连接超时。这里的最佳做法是为每个查询创建一个新连接并在之后关闭它,而不是只有一个连接。

【讨论】:

也许每个端点都有cnx.end() 行。我会试试看。 ?

以上是关于为啥 Heroku 服务器在几分钟后关闭?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我托管在 heroku 上的不和谐机器人随机关闭?

为啥我应该将 Heroku 之类的 PaaS 服务用于 SaaS 应用程序? [关闭]

jar 文件的 Systemd 服务在几分钟后出现“操作超时”错误或保持“激活模式”

Heroku dyno 如何在被子下睡觉和醒来?

“由于远程桌面服务正忙,因此无法完成你尝试执行的任务,请在几分钟后重试,其他用户应该任然能够登录,

Heroku - 旋转起来