Deploy a Node.js app on Linux with a bash script /
Save time with a simple bash script

20/02/2024

Sure, here’s an improved and corrected version of your text:

If you want to swiftly deploy a Node.js app on Linux with Apache2 as a proxy, here’s a basic Bash script that I’ve found to be very efficient. It automates the process of creating an Apache2 configuration and restarting the server, getting a fresh SSL certificate, saving you time

You can find the Bash script below if you want to speed up the process.

#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script as root."
  exit 1
fi

# Prompt for the domain name and directory
read -p "Enter the domain name for your website (e.g., example.com): " domain
read -p "Enter the path to the Node.js application directory (e.g., /var/www/nodeapp): " app_dir
read -p "Enter the Node.js application port (e.g., 3000): " app_port

# Create the Node.js application directory
mkdir -p $app_dir
chown -R www-data:www-data $app_dir
chmod -R 755 $app_dir

# Create a new Apache configuration file
config_file="/etc/apache2/sites-available/$domain.conf"
touch $config_file

# Define the Apache VirtualHost configuration with reverse proxy
cat > $config_file <<EOL
<VirtualHost *:80>
    ServerAdmin webmaster@$domain
    ServerName $domain

    # ProxyPass for Node.js application
    ProxyPass / http://127.0.0.1:$app_port/
    ProxyPassReverse / http://127.0.0.1:$app_port/

    DocumentRoot $app_dir
    ErrorLog \${APACHE_LOG_DIR}/$domain_error.log
    CustomLog \${APACHE_LOG_DIR}/$domain_access.log combined

    <Directory $app_dir>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
EOL

# Enable the site configuration
a2ensite $domain

# Reload Apache to apply the changes
systemctl reload apache2

# Obtain SSL certificate and update Apache configuration with Certbot
certbot --apache --agree-tos --redirect --non-interactive --domain $domain

# Provide instructions to the user
echo "Node.js application configuration for $domain has been created and enabled."
echo "You can now start your Node.js application and configure it to listen on port $app_port."
echo "Don't forget to update your DNS records to point to this server."

Usage

Put your Node.js code on the desired folder, then start the app.

In my case the app is at :

/var/www/html/socket.antoinebrossault.com

Then :

root@somewhere:/home/debian/apacheAutomation# sudo bash newApache2NodeApp.sh
Enter the domain name for your website (e.g., example.com): socket.antoinebrossault.com
Enter the path to the Node.js application directory (e.g., /var/www/nodeapp): /var/www/html/socket.antoinebrossault.com
Enter the Node.js application port (e.g., 3000): 9825