Home Tech News Automating Node.js, MongoDB, and Nginx Deployment on Ubuntu with a Shell Script

Automating Node.js, MongoDB, and Nginx Deployment on Ubuntu with a Shell Script

deployment node js
application deployment script

Setting up a web application on a Linux server traditionally involves multiple manual steps, including package installation, database configuration, and setting up a reverse proxy. This process is often time-consuming and prone to human error. To simplify deployment, developers can use automation scripts that handle the entire setup process efficiently and consistently.

In this guide, we’ll explore how a single shell script can automate the deployment of a Node.js application with a MongoDB database, using Nginx as a reverse proxy, on an Ubuntu server. This approach not only speeds up deployment but also ensures consistent configurations across environments.

What This Script Does

The automation script is designed to handle the end-to-end setup process, including the following steps:

  • Collecting essential inputs such as domain names and port numbers for both frontend and admin applications.
  • Installing Node.js, MongoDB, and Nginx automatically.
  • Configuring MongoDB for secured usage by setting authentication parameters and enabling access control.
  • Setting up Nginx as a reverse proxy to manage incoming web traffic and route it correctly to the Node.js applications.
  • Installing and configuring PM2 to manage the Node.js applications as background processes.
  • Ensuring that MongoDB, Nginx, and the Node.js applications automatically restart when the server reboots.

Breakdown of the Setup Process

Collecting Configuration Details

At the beginning of the deployment process, the script prompts the user to input domain names for the frontend and admin panels. It also collects port numbers for the Node.js applications and the MongoDB service. If no inputs are provided, the script applies default values, ensuring that the setup proceeds without interruption.

Preparing the Server Environment

Next, the script prepares the server environment by creating necessary directories for application files and setting appropriate permissions. It updates the server’s package repositories to ensure that the latest stable packages are installed.

Installing Node.js and PM2

The script installs the latest recommended version of Node.js, along with essential build tools required for compiling Node.js packages. To manage Node.js applications efficiently, PM2 (a process manager for Node.js) is installed globally. PM2 helps in running applications in the background, automatically restarting them in case of failure, and managing process logs.

Setting Up MongoDB

To handle data storage, MongoDB is installed and configured as part of the script. Security is emphasized by setting up authentication and restricting unauthorized access. The script configures MongoDB to bind to all available IP addresses, listens on the specified port, and stores logs and database files in standard locations. Once configured, MongoDB is started and enabled to launch automatically on server boot.

Configuring Nginx as a Reverse Proxy

Nginx, a popular and efficient web server, is installed to handle incoming HTTP requests. The script generates configuration files for both frontend and admin domain names, setting up virtual hosts. These configurations allow Nginx to forward incoming requests to the respective Node.js applications running on different ports.

Additionally, the configuration handles necessary headers, supports WebSocket upgrades, and manages connection timeouts. After the configuration is complete, Nginx is reloaded to apply changes.

Managing Applications with PM2

Finally, the script uses PM2 to manage the running Node.js applications. PM2 ensures that applications continue running in the background and restart automatically after server reboots. The script configures PM2 to work with system services so that processes are preserved across server restarts without manual intervention.

Why Use This Script

Manually deploying Node.js applications with MongoDB and Nginx can be complex, especially when dealing with multiple projects or environments. By using this automated shell script, developers can:

  • Standardize server configurations.
  • Reduce the time required for deployments.
  • Minimize setup errors caused by manual steps.
  • Improve application reliability with automated process management.

Conclusion

This shell script serves as a complete deployment solution for Node.js-based web applications using MongoDB for data storage and Nginx for handling web traffic. It eliminates the need for manual configurations and ensures that all services are correctly installed and managed.

For production environments, it is advisable to further enhance security by installing SSL certificates using tools like Let’s Encrypt. With this automated setup, developers can focus more on building applications rather than managing server configurations.

By understanding and adopting automated deployment techniques like this, teams can streamline their workflows and ensure consistent, reliable server environments for their applications.

Here is the script:

ShellScript
#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

# Variables
CODE_PATH="/var/www/code"
NGINX_CONF_PATH="/etc/nginx/conf.d"

# Collect required information
read -p "Enter frontend domain name (e.g., myapp.com): " FRONTEND_DOMAIN
read -p "Enter admin domain name (e.g., admin.myapp.com): " ADMIN_DOMAIN
read -p "Enter frontend port (default: 3000): " FRONTEND_PORT
FRONTEND_PORT=${FRONTEND_PORT:-3000}
read -p "Enter admin port (default: 4000): " ADMIN_PORT
ADMIN_PORT=${ADMIN_PORT:-4000}
read -p "Enter MongoDB port (default: 27017): " MONGO_PORT
MONGO_PORT=${MONGO_PORT:-27017}

# Create necessary directories
echo -e "${GREEN}Creating necessary directories...${NC}"
sudo mkdir -p /var/www
sudo chown -R $USER:$USER /var/www
sudo chmod -R 755 /var/www

# Update system
echo -e "${GREEN}Updating system packages...${NC}"
sudo apt update && sudo apt upgrade -y

# Install Node.js 20.x
echo -e "${GREEN}Installing Node.js 20.x...${NC}"
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs build-essential

# Verify Node.js installation
echo -e "${GREEN}Node.js version:${NC}"
node --version
npm --version

# Install PM2 globally
echo -e "${GREEN}Installing PM2...${NC}"
sudo npm install -y pm2@latest -g

# Install MongoDB
echo -e "${GREEN}Installing MongoDB...${NC}"
sudo apt-get install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

# Configure MongoDB
echo -e "${GREEN}Configuring MongoDB...${NC}"
sudo tee /etc/mongod.conf > /dev/null <<EOL
storage:
  dbPath: /var/lib/mongodb

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: ${MONGO_PORT}
  bindIp: 0.0.0.0

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: "enabled"
EOL

# Start and enable MongoDB
sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

# Install Nginx
echo -e "${GREEN}Installing Nginx...${NC}"
sudo apt install -y nginx

# Create directory for code if it doesn't exist
sudo mkdir -p ${CODE_PATH}

# Create Nginx configuration files
echo -e "${GREEN}Creating Nginx configurations...${NC}"

# Frontend configuration
sudo tee ${NGINX_CONF_PATH}/${FRONTEND_DOMAIN}.conf > /dev/null <<EOL
server {
    listen 80;
    server_name ${FRONTEND_DOMAIN};

    location / {
        proxy_pass http://localhost:${FRONTEND_PORT};
        proxy_http_version 1.1;
        proxy_cache_bypass \$http_upgrade;
        client_max_body_size 20M;

        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Forwarded-Host \$host;
        proxy_set_header X-Forwarded-Port \$server_port;

        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOL

# Admin configuration
sudo tee ${NGINX_CONF_PATH}/${ADMIN_DOMAIN}.conf > /dev/null <<EOL
server {
    listen 80;
    server_name ${ADMIN_DOMAIN};

    location / {
        proxy_pass http://localhost:${ADMIN_PORT};
        proxy_http_version 1.1;
        proxy_cache_bypass \$http_upgrade;
        client_max_body_size 20M;

        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Forwarded-Host \$host;
        proxy_set_header X-Forwarded-Port \$server_port;

        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOL

# Test and reload Nginx
sudo nginx -t && sudo systemctl reload nginx

# Setup PM2 startup script
echo -e "${GREEN}Setting up PM2 startup script...${NC}"
sudo pm2 startup systemd

# Start applications with PM2 (without ecosystem file)
echo -e "${GREEN}Starting applications with PM2...${NC}"
cd ${CODE_PATH}

# Start frontend
# cd frontend
# npm i --force && npm run build
# pm2 start npm --name "frontend" -- start

# # Start admin
# cd ../admin
# npm i --force && npm run build
# pm2 start npm --name "admin" -- start

# # Save PM2 process list
# pm2 save

# echo -e "${GREEN}Initial setup completed!${NC}"
# echo -e "${GREEN}Next steps:${NC}"
# echo "1. Run the SSL script (ssl-setup.sh) to configure HTTPS"
# echo "2. Make sure your domain DNS is pointing to this server"
# echo "3. Check if your applications are running: pm2 status"
# echo "4. Verify MongoDB is running: systemctl status mongod"
ShellScript

For SSL use the below script

ShellScript
#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${GREEN}Starting SSL setup...${NC}"

# Collect domain information
read -p "Enter your domain name (e.g., example.com): " DOMAIN_NAME

# Install Certbot and Nginx plugin
echo -e "${GREEN}Installing Certbot...${NC}"
sudo apt install -y certbot python3-certbot-nginx

# Obtain SSL certificate
echo -e "${GREEN}Obtaining SSL certificate...${NC}"
sudo certbot --nginx -d $DOMAIN_NAME -d www.$DOMAIN_NAME

# Setup auto-renewal
echo -e "${GREEN}Setting up auto-renewal...${NC}"
sudo systemctl status certbot.timer

echo -e "${GREEN}SSL setup completed!${NC}"
echo -e "${GREEN}Your website should now be accessible via HTTPS${NC}"
echo "Don't forget to test your website at https://$DOMAIN_NAME"
ShellScript
Exit mobile version