502 Bad Gateway in Kubernetes cluster after I added mongoDB connection code

7/30/2020

I was chugging along with my Kubernetes cluster project when after creating a User model to start creating users in my application, I get a 502 Bad Gateway error in my Postman client.

So I was so focused on my ingress-nginx yaml file, staring at it for typos, rewriting it, uninstalling, reinstalling and still getting that error, that I decided to take it the next step further.

Via the current user route handler:

import express from "express";

const router = express.Router();

router.get("/api/users/currentuser", (req, res) => {
  res.send("howdy!");
});

export { router as currentUserRouter };

I have always been able to go to my browser and successfully see howdy! rendered when I went to mywebsite.com/api/users/currentuser

but then I added some logic to index.ts file I did not particular care for from the https://expressjs.com/en/guide/routing.html:

app.all("*", async (req, res) => {
   throw new NotFoundError();
 });

Well, sure enough that killed my ability to go to mywebsite.com/api/users/currentuser and see howdy! rendered and instead I was getting a 502 Bad Gateway. So I said okay I will just leave that one out then.

But then I noticed a huge chunk of very important code was breaking my ability to visit that url as well:

// const start = async () => {
//   try {
//     await mongooose.connect("mongodb://auth-mongo-srv:27017/auth", {
//       useNewUrlParser: true,
//       useUnifiedTopology: true,
//       useCreateIndex: true,
//     });
//     console.log("Connected to MongoDB");
//   } catch (error) {
//     app.listen(3000, () => {
//       console.log("Listening on port 3000!!!!!");
//     });
//   }
// };

// start();

All of the above is what I need to connect to my local MongoDB server and start creating users.

So I started to even get more granular and slowly commenting code back in. Well, the app.all() is not a problem anymore, the problem seems to be throwing my mongoDB connection code inside of a try/catch statement, but I have no idea why that would have created the problem. Any ideas anyone?

So instead if I just run it like this:

const start = async () => {
  await mongooose.connect("mongodb://auth-mongo-srv:27017/auth", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  });
  console.log("Connected to MongoDB");

  app.listen(3000, () => {
    console.log("Listening on port 3000!!!!!");
  });
};

start();

It all works fine again.

-- Daniel
express
kubernetes
try-catch

0 Answers