Skip to main content

Configure Domain To Port Using Apache

· 2 min read
Sivabharathy
To configure a Node.js project to run as a domain using Apache on Ubuntu, you will use Apache as a reverse proxy to forward requests to your Node.js application. Here are the steps to achieve this:
  1. Install Apache and Node.js: Ensure Apache and Node.js are installed. If not, refer to the previous steps to install them.

  2. Install mod_proxy and related modules:

    sudo apt install libapache2-mod-proxy-html libxml2-dev
    sudo a2enmod proxy
    sudo a2enmod proxy_http
    sudo systemctl restart apache2
  1. Create a Node.js application: Create a simple Node.js application or use your existing one. For example:

    // app.js
    const express = require('express');
    const app = express();

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

    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
    });
  2. Run your Node.js application:

    node app.js

    Ensure your Node.js application is running on a specific port, e.g., 3000.

  3. Configure Apache as a reverse proxy: Create a new Apache virtual host configuration file for your domain. For example:

    sudo nano /etc/apache2/sites-available/yourdomain.com.conf

    Add the following content, replacing yourdomain.com with your actual domain name and 3000 with the port your Node.js app is running on:

    <VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com

    ProxyRequests Off
    ProxyPreserveHost On

    <Proxy *>
    Order allow,deny
    Allow from all
    </Proxy>

    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/

    ErrorLog ${APACHE_LOG_DIR}/yourdomain.com-error.log
    CustomLog ${APACHE_LOG_DIR}/yourdomain.com-access.log combined
    </VirtualHost>
  4. Enable the new virtual host:

    sudo a2ensite yourdomain.com.conf
    sudo systemctl reload apache2
  5. Adjust your firewall (if necessary): Ensure that traffic is allowed on HTTP and HTTPS ports:

    sudo ufw allow 'Apache Full'
  6. Test the configuration: Open your web browser and navigate to http://yourdomain.com. You should see your Node.js application being served.

Optional: Secure Your Site with HTTPS

  1. Install Certbot:

    sudo apt install certbot python3-certbot-apache
  2. Obtain an SSL Certificate:

    sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

    Follow the prompts to complete the certificate installation.

  3. Verify HTTPS: Open your web browser and navigate to https://yourdomain.com. You should see the secure version of your site.

By following these steps, you will have configured Apache to serve your Node.js application under a specific domain.