I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn\'t let me write so much
From the heroku bash process, pass down the value of $PORT to your node app using an options parser like yargs.
Here is an example of how you might do that. On the scripts object, inside package.json, add a start method "node server --port $PORT".
In your server file, use yargs to get the value from the port option (--port $PORT) of the start method:
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.
});
Now when your app starts, it will bind to the dynamically set value of $PORT.
In my case I had two issues...
1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"
2) Case sensitive problem with 'Sequelize' instead of 'sequelize'
I have the same issue but my environment variables are set well and the version of npm and node is specified in package.json. I figured out it is because, in my case, Heroku needs "start" to be specified in package.json:
"scripts": {
"start": "node index.js"
}
After adding this to my package.json my node app is successfully deployed on Heroku.
Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this:
.listen(process.env.PORT || 5000)
That way it'll still listen to port 5000 when you test locally, but it will also work on Heroku.
You can check out the Heroku docs on Node.js here.
My problem was that when deploying to heroku I got an error:
Web process failed to bind to $PORT within 60 seconds of launch
when running heroku logs --tail
in the terminal. BUT the application would run as expected when I ran the server locally.
I had this in my index.js
file (server file)
const PORT = process.env.port || 4000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
But should have had this
const PORT = process.env.PORT || 4000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
Use process.env.PORT
, not process.env.port
, because port
is not the same as PORT
obviously.
Credit to gprasant.
The error happens when Heroku failed to bind the port or hostname at server.listen(port, [host], [backlog], [callback])
.
What Heroku requires is .listen(process.env.PORT)
or .listen(process.env.PORT, '0.0.0.0')
So more generically, to support other environments, use this:
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);
});