How to Configure Apache for Nodejs

How to Configure Apache for Nodejs

14 October 2023 0 By Anshul Pal

In this article, we’ll explore how to configure Apache for Node.js apps. We’ll not just talk about these benefits; we’ll also give you a thorough, easy-to-follow guide with a real example of code. This guide will help you learn how to set up Apache in a way that makes your Node.js app work better and stay secure.

Many websites, including major ones like Slack, The New York Times, and LinkedIn, use Apache, making it a highly popular software. People like it because it’s open-source and it makes websites work better and more secure.

Without a doubt, a website’s performance and the level of user engagement it achieves have a close connection that goes beyond industry boundaries. Regardless of the sector, we cannot overemphasize the importance of having a strong server solution. The capacity to seamlessly manage high volumes of incoming traffic, deliver rapid responses to user requests, and proactively safeguard against cyber threats is pivotal for not only ensuring customer satisfaction but also retaining and fostering user loyalty.

How to install and Start the Apache Server?

To install and start the Apache HTTP Server, you can follow these general steps. Please note that the specific commands and procedures may vary depending on your operating system. I’ll provide instructions for common systems:

For Ubuntu/Debian Linux:

  1. Open your terminal.
  2. Update your package list to ensure you have the latest information about available packages:
sudo apt update

Once your repository has been successfully updated, install Apache by running this command:

sudo apt install apache2

Now, You have to start the Apache service:

sudo systemctl start apache2

Enable Apache to start on boot:

sudo systemctl enable apache2

Check that Apache has been installed correctly by pasting http://127.0.0.1 into your browser. If the installation was successful, you should see the following default page:

To check the status of Apache:

sudo systemctl status apache2

How to install Apache in Windows?

The Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows. The goal of this project is to provide a secure, efficient and extensible server that provides HTTP services in sync with the current HTTP standards. The Apache HTTP Server (“httpd”) was launched in 1995 and it has been the most popular web server on the Internet since April 1996. The Apache HTTP Server is a project of The Apache Software Foundation.

Read this article for installing and setup of Apache in windows – how to install apache in windows

Setting up Node.js application

In this tutorial, we’ll work with a demonstration Node.js application that’s been created using the Express.js framework and incorporates a MongoDB database. Here’s what you need to do:

  1. Begin by cloning the repository from GitHub to your own computer. If you’re unsure about how to clone a repository, you can consult GitHub’s documentation for guidance. To clone any repository in your machine. You have to follow these steps:
    1. Create a Folder.
    2. Open your terminal in that particular directory.
    3. Now, type the given command in your terminal.
    4. git clone <Repository link>
  2. Next, open the Node application using your preferred code editor.
  3. Run the following command: npm install

Now, we can commence by examining the app.js file in the demonstration to understand its structure and functionality.

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const authRoute = require('./routes/auth.route');
const suggestionRoute = require('./routes/suggestion.route');
const documentationRoute = require('./routes/documentation.route');
const port = process.env.PORT || 3000;
const corsOptions = {
    "origin": "*",
    optionsSuccessStatus: 200
}
//middlewares
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(express.json());
//routes
app.use('/', documentationRoute);
app.use('/api', authRoute);
app.use('/api', suggestionRoute);
//Connection to mongoose
try {
    mongoose.connect(process.env.DB_CONNECTION, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true
    }, () => console.log('Connected to DB'));
} catch (error) {
    console.log(`connection failed!! ${error}`)
}

app.listen(port, () => console.log(`Server started on port ${port}`));

Changes in NodeJS Application

Within the “controllers” folder, we establish a route for handling documentation. Subsequently, we direct this route to respond to requests at the root level. Here is the structural layout of the Node application:

node-js-file-structure

  • The “controllers” folder contains the logic for handling various routes, including the “documentationRoute.”
  • The “documentationRoute” is defined within the “controllers” folder to specify how the application should respond to requests related to documentation.
  • This “documentationRoute” is then configured to handle requests originating from the root URL of the application.

Now, let’s navigate to the documentation.controllers.js file in the controllers folder and review the contents:

exports.documentation = (request, response) => {
 response.redirect("https://explore.postman.com/templates/15198/store"); }

The “exports.documentation” function within the code takes in an incoming request and generates a response that includes a link to the Node API documentation designed for use with Postman.

This Node application relies on MongoDB as its underlying database. To use MongoDB with the application, it’s necessary to set up a MongoDB cluster, which will provide us with a unique connection string (URI).

In the code editor, we create a “.env” text configuration file. This file’s purpose is to define a specific string labeled “DB_CONNECTION.” This string holds the connection details required for establishing a connection to our MongoDB database during the application’s runtime.

DB_CONNECTION =

Now, it’s time to conduct a test to confirm that the application has connected to the database and is running as expected.

To do this:

You need to initiate the Node application by launching it. This action will start the application and make it accessible for testing and use.

npm start

The Node application has established a connection to the database and is currently operational, listening on port 3000. Now, we’ll proceed to set up the Apache server to host and serve the Node application.

Configuring Apache for Nodejs

We’re going to adjust the settings of the Apache server so that it listens on port 80 and forwards all incoming requests to the Node application, which is currently running on port 3000. Here’s the sequence of steps to configure the Apache server for this purpose:

  1. First, ensure that the Apache server is up and running.
  2. Create a configuration file for Apache that specifies how it should handle requests for the Node application.
  3. Activate the proxy and proxy_http modules in Apache. These modules are responsible for forwarding requests to other servers.
  4. Apply the new configuration to Apache so that it takes effect.
  5. Finally, perform a test to make sure the configuration is working as intended, ensuring that requests made to the Apache server are correctly redirected to the Node application.

Confirming Status of Apache Server

Let’s get started by initiating the Apache server. If you’ve been following the steps outlined in this tutorial, the Apache server should already be up and running. In this scenario, you can simply execute the following command:

sudo systemctl status apache2

Paste localhost into the browser. If Apache is running successfully, the following will be displayed:

apache install page

Creating the Apache Configuration file

Now, let’s move on to the creation of the configuration file. The “apache2.conf” file holds the configuration settings for the Apache server, and to create specific configurations for our purposes, we’ll use the “sites-available” directory. To do this, follow these steps:

  1. Open a new terminal tab or window to work with this new configuration.
  2. Navigate to the “sites-available” directory by using the “cd” command. This is the location where we can create the configuration files that Apache will utilize.
cd /etc/apache2/sites-available

Now, run the ls command:

apache_file_screenshot

Next, we’ll open the 000-default.conf default configuration file in order to make edits:

sudo nano 000-default.conf

Here’s the open default configuration file:

apache-default-configuration-file

In simpler terms, VirtualHost is a feature in Apache that allows it to serve multiple websites or domains from the same server. To customize this behavior, you need to make changes within the VirtualHost configuration section. For more details, consult the official Apache documentation.

The Apache VirtualHost configuration resides in the 000-default.conf file and is set up to listen for incoming requests on port 80. We will adjust this configuration to redirect all incoming requests on port 80 to a Node application running on port 3000. This adjustment involves using ProxyPass, which connects the root URL to http://localhost:3000.

ProxyPass / http://localhost:3000/

Copy the following into the 000-default.conf file:

apache-default-configuration-file-2

Next, use the Control+X command to save and exit.

Enabling the proxy and proxy_http modules

To make ProxyPass function correctly, it’s necessary to activate the proxy and proxy_http modules, which essentially act as intermediaries for managing the request flow. These modules enable the server to forward requests.

Apache uses two important directories: “sites-available” and “sites-enabled.” In “sites-available,” you define various configuration files for your websites. However, the Apache server reads and applies configurations from the “sites-enabled” directory, where you create symbolic links to the files in “sites-available.”

In the context of configuring Apache for Node.js, both the “sites-enabled” and “sites-available” directories play crucial roles.

To proceed, navigate to the “sites-enabled” directory and execute the following command:

sudo a2enmod

The command “a2enmod” stands for “Apache2 enable module.” Running this command provides a list of modules that can be enabled within Apache. After executing the command, it will prompt you to enter the name of the module you want to activate.

apache2-module

We enter proxy at the prompt to enable the proxy module:

enable-proxy-module

Next, we enter proxy_http at the prompt to enable the proxy_http module:

enabling-proxy-http-module

It’s crucial to understand that we employed the “sudo” command to execute the “a2enmod” script. When you run the “a2enmod” script without “sudo,” you’ll encounter a “Permission denied” error.

apache-permission-error

Applying Configuration

Since we’ve made changes to the configuration file, it’s necessary to refresh or “reload” the Apache server to ensure those changes take effect. To do this, navigate to the “sites-enabled” directory and use the following command to reload the Apache2 server:

sudo systemctl reload apache2

Now, use this command to start the apache2 server:

sudo systemctl start apache2

Testing the Configuration

To confirm whether the Apache configuration is correct, paste “http://localhost:80” into the address bar of your web browser. If the configuration has been successful, you will observe the Node application displayed in your browser.

node-application-display

Congrats! You successfully Configure Apache Web Server for Node JS Application.

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.