DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

Nodejs with NGINX

Node.js and Nginx are commonly used together to create a scalable and efficient web application infrastructure. Node.js is a JavaScript runtime used for server-side programming, while Nginx is a powerful web server and reverse proxy that can also act as a load balancer, handling various tasks including serving static files, SSL termination, and routing requests to Node.js applications.

Here's a basic setup using Node.js with Nginx acting as a reverse proxy:

Install Node.js:

  • You can download and install Node.js from the official website. Follow the installation instructions for your specific operating system.

Write a Node.js application:

  • Develop your Node.js application. Here's a simple example using Express.js:
// File: app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, this is your Node.js app!');

app.listen(3000, () => {
  console.log('App listening on port 3000');
Enter fullscreen mode Exit fullscreen mode

Install and configure Nginx:

  • Install Nginx on your server. The configuration file for your Node.js app could look something like this:
# File: /etc/nginx/sites-available/your-app-name

upstream nodejs_app {
  server; # Node.js app running on localhost:3000
  # Add more servers here if you're running multiple Node.js instances

server {
  listen 80;
  server_name; # Your domain name or server IP

  location / {
    proxy_pass http://nodejs_app;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
Enter fullscreen mode Exit fullscreen mode

Enable the Nginx configuration:

  • Create a symbolic link to enable the site and restart Nginx.
sudo ln -s /etc/nginx/sites-available/your-app-name /etc/nginx/sites-enabled/
sudo systemctl restart nginx
Enter fullscreen mode Exit fullscreen mode

Run your Node.js application:

  • Start your Node.js application by running node app.js (or whatever your Node.js entry file is named). Ensure it's running on the port specified in the Nginx configuration (in this case, port 3000).

Adjust firewall settings if needed:

  • Make sure your firewall settings allow traffic on the ports you're using (e.g., port 80 for HTTP).

This basic setup demonstrates how Nginx can act as a reverse proxy, forwarding incoming requests to your Node.js application. Adjust configurations according to your specific requirements, like SSL termination, load balancing multiple Node.js instances, or serving static files.

Top comments (2)

fenix profile image
Fenix • Edited

Namaste . Works like charm... Thanks, thanks, thanks

manthanank profile image
Manthan Ankolekar