ubuntunext.jsdevopsportforever

How to run a Next.js project on a specific port?


Here is the content of server.js file:

const express = require("express");
const path = require("path");
const next = require("next");

const dev = false;
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    // requests to /service-worker.js
    server.get(
      "/service-worker.js",
      express.static(path.join(__dirname, ".next"))
    );

    // all other requests
    server.get("*", (req, res) => {
      return handle(req, res);
    });
    server.listen(3002, (err) => {                            // this
      if (err) throw err;
      console.log("> Ready on http://localhost:3002");        // this
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

As I've highlighted, I'm running the project on port 3002. But after running forever start server.js, still http://<ip>:3002 is not reachable.

Also, when I run yarn start on the root of the project, it says:

Port 3000 is already in use.

enter image description here

Why it doesn't care about the port I specified inside server.js ?


Solution

  • As I've highlighted, I'm running the project on port 3002

    That's not what you did, you just made your server listening on PORT 3002 but when you run yarn start the project will start on the default port 3000

    you can change it this way in your package.json file:

    "scripts": {
    //...
    "dev": "next dev -p 3002",
    "start": "next start -p 3002",
    },
    

    You also need to check if the port itself is listening on the server(lsof | grep -i PORT) and then enable access on the firewall, use the following command to enable access in the firewall: sudo ufw allow 3002/tcp

    Just make sure ufw is installed & properly setup.