简体   繁体   中英

Deploying Node/Sequelize app to heroku - Issue with PORT

I'm building a Node/Postgres app that I'm deploying to heroku. I'm receiving a timeout error while trying to open the app in production. According to Heroku, the error I'm receiving comes from database or port connection issues. I believe my database connection is fine, I'm getting a log that the connection was successful. Unsure if my integration with postgres caused a PORT connection issue.

Here is the error on heroku logs (not very helpful)

2017-07-20T17:44:53.432603+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-20T17:44:53.314516+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2017-07-20T17:44:53.314641+00:00 heroku[web.1]: Stopping process with SIGKILL

// app.js

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const logger = require('morgan');
const pg= require('pg');


const index = require('./server/routes/index');
const users = require('./server/routes/users');
const rideRequests = require('./server/routes/riderequests');
const driveRequests = require('./server/routes/driverequests');
const notifications = require('./server/routes/notifications');
const trips = require('./server/routes/trips');
const email = require('./server/routes/mail');

const app = express();

pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
  if (err) throw err;
  console.log('Connected to postgres! Getting schemas...');

  client
    .query('SELECT table_schema,table_name FROM information_schema.tables;')
    .on('row', function(row) {
      console.log(JSON.stringify(row));
    });
});

app.set('views', path.join(__dirname, './dist'));
app.set('view engine', 'ejs');

app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, './dist')));

app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'POST, PUT, GET, PATCH, DELETE, OPTIONS');
  next();
});

app.use('/email', email);
app.use('/trip', trips);
app.use('/notifications', notifications);
app.use('/users', users);
app.use('/ride-request', rideRequests);
app.use('/drive-request', driveRequests);
app.use('/', index);


app.use('*', index);

module.exports = app;

// bin/www

#!/usr/bin/env node

var app = require('../app');
var debug = require('debug')('atlas:server');
var http = require('http');
var models = require('../server/models');

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.createServer(app);

models.sequelize.sync().then(function() {
  server.listen(port, function() {
    debug('Express server listening on port ' + server.address().port);
    });
  server.on('error', onError);
  server.on('listening', onListening);
});




function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}


function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

// config/config.json

{
  "development": {
    "username": "****",
    "password": "****",
    "database": "*_development",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "****",
    "password": "****",
    "database": "*_test",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "use_env_variable": "DATABASE_URL",
    "username": "****",
    "password": "****",
    "database": "*_test",
    "host": "*-*.herokuapp.com",
    "dialect": "postgres"
  }
}

All of the asterisks above contain the same sensitive information

// models/index.js

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Thanks!

**** Additional logs with successful connection to postgres upon deployment. I want to note this is not while trying to open the app, I am not receiving a anything form the server on postgres on app open.

2017-07-20T18:36:16.953360+00:00 app[web.1]: (node:17) DeprecationWarning: PG.connect is deprecated - please see the upgrade guide at https://node-postgres.com/guides/upgrading
2017-07-20T18:36:16.991855+00:00 app[web.1]: Connected to postgres! Getting schemas...

*****UPDATE

I believe this is a port issue. I placed a few logs in the js files and everything logs smoothly in models/index but I'm getting now logs on my www file. I believe that's where the issue lies.

My problem actually had nothing to do with sequelize or my app setup. My package.json file was using app.js instead of bin/wwww for npm start. Thus app.js and models/index was getting called but not the actual server in bin/www. Anyone looking to solve this issue with an immediate crash in heroku logs, here is my suggestion. Place a few console.log()'s in your app server or app files and see what gets called. When the calling stops, that's where your issue lies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM