Install Apache and Node.js: Ensure Apache and Node.js are installed. If not, refer to the previous steps to install them.
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
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}`);
});Run your Node.js application:
node app.js
Ensure your Node.js application is running on a specific port, e.g., 3000.
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 and3000
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>Enable the new virtual host:
sudo a2ensite yourdomain.com.conf
sudo systemctl reload apache2Adjust your firewall (if necessary): Ensure that traffic is allowed on HTTP and HTTPS ports:
sudo ufw allow 'Apache Full'
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
Install Certbot:
sudo apt install certbot python3-certbot-apache
Obtain an SSL Certificate:
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
Follow the prompts to complete the certificate installation.
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.