Question

I can't deploy mern stack application, on node.js server

Posted April 5, 2021 192 views
NginxUbuntuNode.jsLEMPReact

Hello,
I’m trying to deploy, my mern stack app, but it seems that something goes wrong, it is my first website, so can anyone help?

My server runs on the following ports:

API: localhost://5000
Frontend: localhost://3000
My server.js file looks like this:

const __dirname = path.resolve()
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

if(process.env.NODE_ENV === 'production'){

  app.use(express.static(path.join(__dirname, '/frontend/build')))  

  app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
  })
} else {
   app.get('/', (req, res) => {
     res.send('App Is Running...')
   })
}


app.use(notFound)
app.use(errorHandler)

const PORT = process.env.PORT || 5000

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.listen(5000, () => {
    console.log(`Server Is Running In ${process.env.NODE_ENV} Mode  On Port ${PORT}`.yellow.bold)
})

When I deploy it, it doesn’t deploy successfully.

I Bought a node.js server and following the instructions that gave me a digital ocean,

When starting the server.js file:

root@obstacle-sports-node:~/Obstacle-Sports# pm2 start backend/server.js
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /root/Obstacle-Sports/backend/server.js in fork_mode (1 instance)
[PM2] Done.
root@obstacle-sports-node:~/Obstacle-Sports# 

This is my NGINX configuration:

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name hellonode;

        location ^~ /assets/ {
                gzip_static on;
                expires 12h;
                add_header Cache-Control public;
  }

        location / {
                proxy_http_version 1.1;
                proxy_cache_bypass $http_upgrade;

                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;

                proxy_pass http://localhost:5000;
        }

but when I am visiting IP address, I get This error

502 Bad Gateway
nginx/1.17.10 (Ubuntu)

please help :)

edited by MattIPv4
Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!