Skip to content

Instantly share code, notes, and snippets.

@TanjinAlam
Last active March 22, 2025 20:17
Show Gist options
  • Save TanjinAlam/decb3a089e5581323b50a35abbf5ceb0 to your computer and use it in GitHub Desktop.
Save TanjinAlam/decb3a089e5581323b50a35abbf5ceb0 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Configuration
SERVICE_URL="http://127.0.0.1:3000"
LOG_FILE="/var/log/nodejs-health.log"
WARNING_FILE="/var/log/nodejs-warnings.log"
# Function to log messages
log_message() {
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $1" >> "$LOG_FILE"
}
# Function to log warnings
log_warning() {
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] WARNING: $1" >> "$WARNING_FILE"
}
# Function to check if systemd service is running
check_systemd_service() {
systemctl is-active --quiet node-app.service
return $?
}
# Function to restart the service
restart_service() {
log_message "Attempting to restart node-app.service..."
sudo systemctl restart node-app.service
sleep 5 # Wait for service to restart
if check_systemd_service; then
log_message "Service successfully restarted"
return 0
else
log_warning "Failed to restart Node.js service - System remains down"
return 1
fi
}
# Main health check
main() {
# Create log files if they don't exist
touch "$LOG_FILE"
touch "$WARNING_FILE"
# Check if service is running
if ! check_systemd_service; then
log_warning "Node.js service is not running - System crashed"
restart_service
exit 1
fi
# Make HTTP request to check service
response=$(curl -s -w "%{http_code}" "$SERVICE_URL" -o /dev/null)
if [ "$response" = "200" ]; then
log_message "Health check passed - Service is responding normally"
else
log_warning "Service is not responding properly (HTTP $response) - System may be crashed"
restart_service
fi
}
# Run main function
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment