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}`))
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.
If any questions check this document as a resource.