Deploying an Express.js Application with Nginx

Deploying an Express.js Application with Nginx


Developing web applications is both fun and challenging for many developers. Express.js, a JavaScript-based framework, allows you to create performant and scalable web applications on Node.js. However, to publish these applications on the internet, we usually need a web server. This is where Nginx comes in.

Nginx, as a high-performance web server, is capable of serving static files faster and can also be used as a proxy server. In this article, we will examine step by step how we can publish a simple Express.js application with Nginx.

Step 1: Creating the Express.js Application

First, let's create an Express.js application. You can start a new project using the following commands:

mkdir my-express-app
cd my-express-app
npm init -y
npm install express

Then, create a simple server. Create a file named "index.js" and add the following code:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello, My Express.js Application!');
});

app.listen(PORT, () => {
  console.log(`Server is running on ${PORT}`);
});

Step 2: Deploying the Application

Installing Nginx

To deploy our application, we first need to install Nginx. On Debian and Ubuntu, you can install Nginx using the following command:

sudo apt update
sudo apt install nginx

Nginx Configuration

After Nginx is installed, you should edit the configuration file to direct to your Express.js application. Open the Nginx configuration file with the following command:

sudo nano /etc/nginx/sites-available/my-express-app

Add the following configuration to the file:

server {
    listen 80;
    server_name your_domain.com;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

After saving and closing the configuration file, restart Nginx:

sudo systemctl restart nginx

Conclusion

You have now published a simple Express.js application with Nginx. You can view the application in your browser by navigating to http://your_domain.com. Thanks to Nginx, your application becomes secure and scalable, while you also benefit from the ease of use of Express.js. Moreover, with this setup, you will have established the necessary foundation to take your application to higher levels in the future.

I hope this article has helped you publish your Express.js application with Nginx. If you have any questions, you can mention them in the comments!