Search code examples
javascriptnode.jsmongodbmongooseheroku

How to fix Heroku "State changed from up to crashed" (Mongoose connection error)


I'm deploying a Node.js/MongoDB app to Heroku, and it crashes with the following error:

MongooseServerSelectionError: connection <monitor> to
104.155.184.217:27017 closed

Here's the relevant part of my logs:

2022-07-10T23:36:17.323791+00:00 heroku[web.1]: Process exited with status 1
2022-07-10T23:36:17.574484+00:00 heroku[web.1]: State changed from up to crashed
... 
2022-07-10T23:36:51.593762+00:00 app[web.1]: MongooseServerSelectionError: connection <monitor> to
104.155.184.217:27017 closed
... 

Code:

server.js

const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const connectDB = require('./config/db')
const passport = require('passport')
const bodyParser = require('body-parser')
const routes = require('./routes/index')


connectDB()

const app = express()

if(process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'))
}

app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(routes)
app.use(passport.initialize())
require('./config/passport')(passport)

const PORT = process.env.PORT || 3000

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`))

package.json:

  "dependencies": {
    "bcrypt": "^5.0.1",
    "body-parser": "^1.20.0",
    "connect-mongo": "^4.6.0",
    "cors": "^2.8.5",
    "cross-env": "^7.0.3",
    "express": "^4.18.1",
    "jwt-simple": "^0.5.6",
    "mongoose": "^6.4.4",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.19",
    "passport": "^0.6.0",
    "passport-jwt": "^4.0.0"
  }

Procfile:

web:node server

Things I've tried:

enter image description here

If I type heroku restart into the command prompt, it works.

enter image description here

And if I type heroku logs --tail into the command prompt, it shows me the initial image again; it doesn't work.

Question: How can I resolve this error and keep my Heroku app running without crashing?


Solution

  • I'm assuming you are using mongodB atlas. You need to whitelist your IP address. To do that, head over to your network access tab, and include an IP address 0.0.0.0/0. This is a wild card IP address that would allow all IP addresses with the correct credentials to access your DB.

    As such: enter image description here

    Note: This whitelists all IP addresses. It's alright when testing. But when going into production, you might want to whitelist only IP addresses that should have access to the cluster...for security purposes.