简体   繁体   中英

trouble deploying node.js app to heroku because of hard coded port number

I am having trouble deploying the angular-seed app ( https://github.com/angular/angular-seed ) to Heroku. I believe the problem to be that the port number is hard coded into the server starting scripts when heroku needs to dynamically assign the port through the process.env.PORT variable. Looking through the heroku logs confirms that: Starting up http-server, serving ./ on port: 8000 . My Procfile contains web: npm start , and my package.json file contains

"scripts": {
  "prestart": "npm install",
  "start": "http-server -a localhost -p 8000"
}

How can I change that so that my server will still work properly in a local dev environment with foreman start , however dynamically assign a port when using heroku? I want it so that when I type foreman start on my local dev environment, a server will be created at localhost:8000, but when I deploy the app to heroku, the port will be chosen by Heroku.

I am not a Node developer, but why don't you use the PORT number provisioned by Heroku in your start script?

ie. "start": "http-server -a localhost -p $PORT"

Then it will run on Heroku. If you're running locally, just export PORT=8000 , or put PORT=8000 in your .env file if you run using foreman , and you're good to go.

You can also probably add bash magic to set a PORT if none is set by replacing $PORT with ${PORT-8000} .

(Untested)

Having the same issue. So far got it resolved with help of express.

  1. Added Procfile:

     web: node web.js 
  2. Added web.js

     var port = Number(process.env.PORT || 8000); var express = require('express'); var app = express(); app.use(express.static(__dirname + '/app')); var server = app.listen(port, function() { console.log('Listening on port %d', server.address().port); }); 
  3. Added "express": "3.x" in dependencies section of package.json

  4. Replaced

     "start": "http-server -a localhost -p 8000" 

    with

     "start": "node web.js" 
  5. Then commit, run git push heroku master and after it finishes heroku open

If you wish to solve it without express, using only node http-server module, here what you need in your package.json :

{
  "dependencies": {
    "http-server": "*"
  },
  "scripts": {
    "start": "http-server ./ -p ${PORT:=5000} -c-1"
  }
}

Explanation

  • Added http-server in your dependencies (should not be in dev dependencies)
  • -p ${PORT:=8000} binds the server to the port available for you heroku instance which is found on the environment variable. If no environement variable exists with that name (eg locally) it defaults to 8000
  • Removed the -a localhost which is not compatible with heroku

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