PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 1, 2022

[FIXED] How to run a express server using nginx in localhost?

 September 01, 2022     express, javascript, nginx, nginx-reverse-proxy, node.js     No comments   

Issue

I want to run the express server using Nginx in localhost. Is it possible? If it is possible how can I achieve that?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Server listening at http://localhost:${port}`))

Solution

If you want to use nginx as a reverse proxy for express you can configure your server as follow:

server {
    listen 80 default_server;
    server_name _;

location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:3000; #port where you are serving your express app.

  }
}

You should make your configuration in /etc/nginx/sites-available/default

After change the configuration file, check if there is no error in your script:

$sudo nginx -t

Expected result should be:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

After configuration is ok, you should restart your nginx instance, with command:

$sudo nginx -s reload

After proper reload assert your node/express server is running. Now if you access http://localhost you should see what's is listening in http://localhost:3000

Nginx should be serving your instance, when you stop your nodes / express you should see default error 502.



Answered By - Danizavtz
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing