#!/bin/bash
# Define variables
REDIS_PASSWORD="Sumit@123"
GITHUB_USERNAME="sumit-linearloop"
GITHUB_TOKEN="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"
REPO_URL="https://$GITHUB_TOKEN@github.com/$GITHUB_USERNAME/digitalocean-api.git"
TARGET_DIR="/var/www/nestjs-app"
# Update and install dependencies
echo "Updating system and installing dependencies..."
apt-get update && apt-get upgrade -y
apt-get install nginx -y
apt-get install git -y
apt-get install curl -y
apt-get install redis-server -y
# Install nvm (Node Version Manager)
# Log everything to /root/startup-script.log
exec > >(tee -a /root/startup-script.log) 2>&1
# Install nvm (Node Version Manager)
echo "Installing NVM..."
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# Load nvm in the current shell
source ~/.bashrc || source ~/.profile
# Verify nvm installation
echo "Verifying NVM installation..."
nvm -v || { echo "NVM not installed"; exit 1; }
# Install Node.js version 18 using nvm and set it as default
echo "Installing Node.js 18..."
nvm install 18
nvm use 18 || { echo "Node.js installation failed"; exit 1; }
# Install global npm packages
echo "Installing global npm packages (yarn, pm2)..."
npm install --global yarn pm2 || { echo "Global npm package installation failed"; exit 1; }
echo "Script completed successfully."
# Clone the GitHub repo
echo "Cloning repository from: $REPO_URL"
mkdir -p $TARGET_DIR && cd $TARGET_DIR
git clone --verbose $REPO_URL . || { echo "Git clone failed. Check your token or repository access."; exit 1; }
# Install dependencies and build the project
echo "Installing project dependencies with Yarn..."
yarn install || { echo "Yarn install failed"; exit 1; }
echo "Building the project with Yarn..."
yarn build || { echo "Yarn build failed"; exit 1; }
# Enable the PM2 service
echo "Configuring PM2 service for NestJS app..."
pm2 stop "nestjs-app" || echo "PM2 service not running"
pm2 delete "nestjs-app" || echo "No PM2 process to delete"
pm2 start /var/www/nestjs-app/dist/main.js --name "nestjs-app" -i 1 || { echo "PM2 start failed"; exit 1; }
pm2 save || { echo "PM2 save failed"; exit 1; }
# Set up NGINX for domain api.sumitdevops.xyz
echo "Configuring NGINX for domain api.sumitdevops.xyz..."
cat << 'EOF' > /etc/nginx/sites-available/api.sumitdevops.xyz
server {
listen 80;
server_name api.sumitdevops.xyz;
location / {
proxy_pass http://localhost:3000;
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;
}
}
EOF
# Enable the NGINX configuration
ln -s /etc/nginx/sites-available/api.sumitdevops.xyz /etc/nginx/sites-enabled/
# Restart NGINX to apply the new configuration
echo "Restarting NGINX..."