Enhance Dockerfile configurations for API and frontend, including MySQL client installation, improved TypeScript build process, and a custom startup script for database migration. Update production environment example with refined database and application settings.

This commit is contained in:
2025-08-20 04:22:48 +01:00
parent 1759bd623a
commit d6dd571f5c
9 changed files with 1079 additions and 44 deletions

167
scripts/deploy-with-db.ps1 Normal file
View File

@ -0,0 +1,167 @@
# ScriptShare Production Deployment with Database (PowerShell)
Write-Host "🚀 Deploying ScriptShare with Database..." -ForegroundColor Green
# Check if Docker is available
try {
docker --version | Out-Null
} catch {
Write-Host "❌ Docker is not installed. Please install Docker Desktop first." -ForegroundColor Red
exit 1
}
# Check if Docker Compose is available
try {
docker compose version | Out-Null
} catch {
try {
docker-compose --version | Out-Null
} catch {
Write-Host "❌ Docker Compose is not available. Please install Docker Compose." -ForegroundColor Red
exit 1
}
}
# Check if environment file exists
if (-not (Test-Path "env.production.example")) {
Write-Host "❌ Environment example file 'env.production.example' not found." -ForegroundColor Red
exit 1
}
# Copy environment file if it doesn't exist
if (-not (Test-Path ".env")) {
Write-Host "📋 Creating .env file from example..." -ForegroundColor Cyan
Copy-Item "env.production.example" ".env"
Write-Host "⚠️ Please edit .env file with your production settings before continuing!" -ForegroundColor Yellow
Write-Host " - Update database passwords" -ForegroundColor Yellow
Write-Host " - Set your domain URL" -ForegroundColor Yellow
Write-Host " - Change JWT secret" -ForegroundColor Yellow
Read-Host "Press Enter after editing .env file"
}
# Create necessary directories
Write-Host "📁 Creating required directories..." -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path "logs" | Out-Null
New-Item -ItemType Directory -Force -Path "backups" | Out-Null
# Pull latest images
Write-Host "📥 Pulling Docker images..." -ForegroundColor Cyan
docker compose -f docker-compose.production.yml pull mysql:8.0
# Build application images
Write-Host "🔨 Building application images..." -ForegroundColor Cyan
docker compose -f docker-compose.production.yml build --no-cache
# Stop existing containers if running
Write-Host "🛑 Stopping existing containers..." -ForegroundColor Yellow
docker compose -f docker-compose.production.yml down
# Start the database first
Write-Host "🗄️ Starting database..." -ForegroundColor Cyan
docker compose -f docker-compose.production.yml up -d scriptshare-db
# Wait for database to be ready
Write-Host "⏳ Waiting for database to be ready..." -ForegroundColor Cyan
Start-Sleep -Seconds 20
# Check database health
Write-Host "🏥 Checking database health..." -ForegroundColor Cyan
$dbReady = $false
$attempts = 0
$maxAttempts = 30
while (-not $dbReady -and $attempts -lt $maxAttempts) {
try {
$result = docker compose -f docker-compose.production.yml exec -T scriptshare-db mysqladmin ping -h"localhost" -u"root" -p"ScriptShare_Root_2024_Secure" --silent 2>$null
if ($LASTEXITCODE -eq 0) {
$dbReady = $true
}
} catch {
# Continue waiting
}
if (-not $dbReady) {
Write-Host "Database is starting up - waiting..." -ForegroundColor Gray
Start-Sleep -Seconds 5
$attempts++
}
}
if (-not $dbReady) {
Write-Host "❌ Database failed to start within timeout period" -ForegroundColor Red
docker compose -f docker-compose.production.yml logs scriptshare-db
exit 1
}
Write-Host "✅ Database is ready!" -ForegroundColor Green
# Start API server
Write-Host "🚀 Starting API server..." -ForegroundColor Cyan
docker compose -f docker-compose.production.yml up -d scriptshare-api
# Wait for API to be ready
Write-Host "⏳ Waiting for API to be ready..." -ForegroundColor Cyan
Start-Sleep -Seconds 30
# Start frontend
Write-Host "🌐 Starting frontend..." -ForegroundColor Cyan
docker compose -f docker-compose.production.yml up -d scriptshare-frontend
# Wait for all services to be healthy
Write-Host "🏥 Checking service health..." -ForegroundColor Cyan
Start-Sleep -Seconds 30
# Check service status
Write-Host "📊 Checking service status..." -ForegroundColor Cyan
$services = @("scriptshare-db", "scriptshare-api", "scriptshare-frontend")
foreach ($service in $services) {
$status = docker compose -f docker-compose.production.yml ps | Select-String $service
if ($status -and $status.ToString() -match "Up") {
Write-Host "$service is running" -ForegroundColor Green
} else {
Write-Host "$service failed to start" -ForegroundColor Red
Write-Host "Checking logs for $service:" -ForegroundColor Yellow
docker compose -f docker-compose.production.yml logs $service
exit 1
}
}
# Display deployment information
Write-Host ""
Write-Host "🎉 ScriptShare deployment completed successfully!" -ForegroundColor Green
Write-Host ""
Write-Host "📊 Service URLs:" -ForegroundColor Cyan
# Get ports from .env file
$envContent = Get-Content ".env" -ErrorAction SilentlyContinue
$apiPort = "3001"
$frontendPort = "80"
if ($envContent) {
$apiPortLine = $envContent | Where-Object { $_ -match "API_PORT=" }
$frontendPortLine = $envContent | Where-Object { $_ -match "FRONTEND_PORT=" }
if ($apiPortLine) {
$apiPort = ($apiPortLine -split "=")[1].Trim('"')
}
if ($frontendPortLine) {
$frontendPort = ($frontendPortLine -split "=")[1].Trim('"')
}
}
Write-Host " Frontend: http://localhost:$frontendPort" -ForegroundColor White
Write-Host " API: http://localhost:$apiPort/api/health" -ForegroundColor White
Write-Host " Database: localhost:3306" -ForegroundColor White
Write-Host ""
Write-Host "🔧 Management commands:" -ForegroundColor Cyan
Write-Host " View logs: docker compose -f docker-compose.production.yml logs -f" -ForegroundColor Gray
Write-Host " Stop: docker compose -f docker-compose.production.yml down" -ForegroundColor Gray
Write-Host " Restart: docker compose -f docker-compose.production.yml restart" -ForegroundColor Gray
Write-Host " Database shell: docker compose -f docker-compose.production.yml exec scriptshare-db mysql -u scriptshare_user -p scriptshare" -ForegroundColor Gray
Write-Host ""
Write-Host "📝 Next steps:" -ForegroundColor Cyan
Write-Host " 1. Configure your domain DNS to point to this server" -ForegroundColor White
Write-Host " 2. Set up SSL/HTTPS if needed" -ForegroundColor White
Write-Host " 3. Configure automated backups" -ForegroundColor White
Write-Host " 4. Set up monitoring and alerting" -ForegroundColor White

126
scripts/deploy-with-db.sh Normal file
View File

@ -0,0 +1,126 @@
#!/bin/bash
# ScriptShare Production Deployment with Database
set -e
echo "🚀 Deploying ScriptShare with Database..."
# Check if Docker and Docker Compose are available
if ! command -v docker &> /dev/null; then
echo "❌ Docker is not installed. Please install Docker first."
exit 1
fi
if ! docker compose version &> /dev/null && ! command -v docker-compose &> /dev/null; then
echo "❌ Docker Compose is not installed. Please install Docker Compose first."
exit 1
fi
# Check if environment file exists
if [ ! -f "env.production.example" ]; then
echo "❌ Environment example file 'env.production.example' not found."
exit 1
fi
# Copy environment file if it doesn't exist
if [ ! -f ".env" ]; then
echo "📋 Creating .env file from example..."
cp env.production.example .env
echo "⚠️ Please edit .env file with your production settings before continuing!"
echo " - Update database passwords"
echo " - Set your domain URL"
echo " - Change JWT secret"
read -p "Press Enter after editing .env file..."
fi
# Create necessary directories
echo "📁 Creating required directories..."
mkdir -p logs
mkdir -p backups
# Pull latest images
echo "📥 Pulling Docker images..."
docker compose -f docker-compose.production.yml pull mysql:8.0
# Build application images
echo "🔨 Building application images..."
docker compose -f docker-compose.production.yml build --no-cache
# Stop existing containers if running
echo "🛑 Stopping existing containers..."
docker compose -f docker-compose.production.yml down
# Create Docker network if it doesn't exist
echo "🌐 Setting up Docker network..."
docker network create scriptshare-network 2>/dev/null || echo "Network already exists"
# Start the database first
echo "🗄️ Starting database..."
docker compose -f docker-compose.production.yml up -d scriptshare-db
# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
sleep 20
# Check database health
echo "🏥 Checking database health..."
until docker compose -f docker-compose.production.yml exec -T scriptshare-db mysqladmin ping -h"localhost" -u"root" -p"${DB_ROOT_PASSWORD:-ScriptShare_Root_2024_Secure}" --silent; do
echo "Database is starting up - waiting..."
sleep 5
done
echo "✅ Database is ready!"
# Start API server
echo "🚀 Starting API server..."
docker compose -f docker-compose.production.yml up -d scriptshare-api
# Wait for API to be ready
echo "⏳ Waiting for API to be ready..."
sleep 30
# Start frontend
echo "🌐 Starting frontend..."
docker compose -f docker-compose.production.yml up -d scriptshare-frontend
# Wait for all services to be healthy
echo "🏥 Checking service health..."
sleep 30
# Check service status
echo "📊 Checking service status..."
services=("scriptshare-db" "scriptshare-api" "scriptshare-frontend")
for service in "${services[@]}"; do
if docker compose -f docker-compose.production.yml ps | grep -q "$service.*Up"; then
echo "$service is running"
else
echo "$service failed to start"
echo "Checking logs for $service:"
docker compose -f docker-compose.production.yml logs "$service"
exit 1
fi
done
# Display deployment information
echo ""
echo "🎉 ScriptShare deployment completed successfully!"
echo ""
echo "📊 Service URLs:"
API_PORT=$(grep API_PORT .env | cut -d'=' -f2 | tr -d '"' || echo "3001")
FRONTEND_PORT=$(grep FRONTEND_PORT .env | cut -d'=' -f2 | tr -d '"' || echo "80")
echo " Frontend: http://localhost:${FRONTEND_PORT}"
echo " API: http://localhost:${API_PORT}/api/health"
echo " Database: localhost:3306"
echo ""
echo "🔧 Management commands:"
echo " View logs: docker compose -f docker-compose.production.yml logs -f"
echo " Stop: docker compose -f docker-compose.production.yml down"
echo " Restart: docker compose -f docker-compose.production.yml restart"
echo " Database shell: docker compose -f docker-compose.production.yml exec scriptshare-db mysql -u scriptshare_user -p scriptshare"
echo ""
echo "📝 Next steps:"
echo " 1. Configure your domain DNS to point to this server"
echo " 2. Set up SSL/HTTPS if needed"
echo " 3. Configure automated backups"
echo " 4. Set up monitoring and alerting"

220
scripts/init-db.sql Normal file
View File

@ -0,0 +1,220 @@
-- ScriptShare Database Initialization Script
-- This script sets up the initial database structure and default data
USE scriptshare;
-- Set proper character set and collation
ALTER DATABASE scriptshare CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create users table if it doesn't exist
CREATE TABLE IF NOT EXISTS `users` (
`id` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL UNIQUE,
`username` varchar(100) NOT NULL UNIQUE,
`displayName` varchar(255) NOT NULL,
`passwordHash` varchar(255) NOT NULL,
`avatarUrl` text,
`bio` text,
`isAdmin` boolean DEFAULT false,
`isModerator` boolean DEFAULT false,
`isVerified` boolean DEFAULT false,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_users_email` (`email`),
INDEX `idx_users_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create scripts table if it doesn't exist
CREATE TABLE IF NOT EXISTS `scripts` (
`id` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`description` text,
`content` longtext NOT NULL,
`authorId` varchar(255) NOT NULL,
`categories` json,
`tags` json,
`compatibleOs` json,
`language` varchar(50) DEFAULT 'bash',
`isApproved` boolean DEFAULT false,
`isPublic` boolean DEFAULT true,
`viewCount` int DEFAULT 0,
`downloadCount` int DEFAULT 0,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`authorId`) REFERENCES `users`(`id`) ON DELETE CASCADE,
INDEX `idx_scripts_author` (`authorId`),
INDEX `idx_scripts_approved` (`isApproved`),
INDEX `idx_scripts_public` (`isPublic`),
INDEX `idx_scripts_created` (`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create ratings table if it doesn't exist
CREATE TABLE IF NOT EXISTS `ratings` (
`id` varchar(255) NOT NULL,
`scriptId` varchar(255) NOT NULL,
`userId` varchar(255) NOT NULL,
`rating` int NOT NULL CHECK (rating >= 1 AND rating <= 5),
`comment` text,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_user_script_rating` (`scriptId`, `userId`),
FOREIGN KEY (`scriptId`) REFERENCES `scripts`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE CASCADE,
INDEX `idx_ratings_script` (`scriptId`),
INDEX `idx_ratings_user` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create script_analytics table if it doesn't exist
CREATE TABLE IF NOT EXISTS `script_analytics` (
`id` varchar(255) NOT NULL,
`scriptId` varchar(255) NOT NULL,
`eventType` varchar(50) NOT NULL,
`userId` varchar(255),
`userAgent` text,
`ipAddress` varchar(45),
`referrer` text,
`metadata` json,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`scriptId`) REFERENCES `scripts`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE SET NULL,
INDEX `idx_analytics_script` (`scriptId`),
INDEX `idx_analytics_event` (`eventType`),
INDEX `idx_analytics_created` (`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create script_collections table if it doesn't exist
CREATE TABLE IF NOT EXISTS `script_collections` (
`id` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`description` text,
`authorId` varchar(255) NOT NULL,
`isPublic` boolean DEFAULT false,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`authorId`) REFERENCES `users`(`id`) ON DELETE CASCADE,
INDEX `idx_collections_author` (`authorId`),
INDEX `idx_collections_public` (`isPublic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create collection_scripts table if it doesn't exist
CREATE TABLE IF NOT EXISTS `collection_scripts` (
`id` varchar(255) NOT NULL,
`collectionId` varchar(255) NOT NULL,
`scriptId` varchar(255) NOT NULL,
`addedAt` timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_collection_script` (`collectionId`, `scriptId`),
FOREIGN KEY (`collectionId`) REFERENCES `script_collections`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`scriptId`) REFERENCES `scripts`(`id`) ON DELETE CASCADE,
INDEX `idx_collection_scripts_collection` (`collectionId`),
INDEX `idx_collection_scripts_script` (`scriptId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create script_versions table if it doesn't exist
CREATE TABLE IF NOT EXISTS `script_versions` (
`id` varchar(255) NOT NULL,
`scriptId` varchar(255) NOT NULL,
`version` varchar(50) NOT NULL,
`content` longtext NOT NULL,
`changelog` text,
`createdAt` timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY (`scriptId`) REFERENCES `scripts`(`id`) ON DELETE CASCADE,
INDEX `idx_versions_script` (`scriptId`),
INDEX `idx_versions_created` (`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Insert default admin user (password: admin123)
-- Note: In production, use proper password hashing
INSERT IGNORE INTO `users` (
`id`,
`email`,
`username`,
`displayName`,
`passwordHash`,
`isAdmin`,
`isModerator`,
`isVerified`
) VALUES (
'admin-default-001',
'admin@scriptshare.local',
'admin',
'System Administrator',
'$2b$10$8K5YBvK8H.UX3JQ2K9J9x.RQfFr6bF7UE9FJm.LrEY8K.QG8wH8G6', -- admin123
true,
true,
true
);
-- Insert sample categories data
INSERT IGNORE INTO `script_collections` (
`id`,
`name`,
`description`,
`authorId`,
`isPublic`
) VALUES
('collection-system-001', 'System Administration', 'Essential system administration scripts', 'admin-default-001', true),
('collection-devops-001', 'DevOps Automation', 'CI/CD and deployment automation scripts', 'admin-default-001', true),
('collection-security-001', 'Security Tools', 'Security scanning and hardening scripts', 'admin-default-001', true),
('collection-backup-001', 'Backup & Recovery', 'Data backup and recovery automation', 'admin-default-001', true);
-- Insert sample script
INSERT IGNORE INTO `scripts` (
`id`,
`name`,
`description`,
`content`,
`authorId`,
`categories`,
`tags`,
`compatibleOs`,
`language`,
`isApproved`,
`isPublic`
) VALUES (
'script-welcome-001',
'System Information Script',
'A simple script to display system information including OS, CPU, memory, and disk usage.',
'#!/bin/bash\n\necho "=== System Information ==="\necho "Hostname: $(hostname)"\necho "OS: $(uname -s)"\necho "Kernel: $(uname -r)"\necho "Architecture: $(uname -m)"\necho ""\necho "=== CPU Information ==="\necho "CPU: $(lscpu | grep \"Model name\" | cut -d: -f2 | xargs)"\necho "Cores: $(nproc)"\necho ""\necho "=== Memory Information ==="\nfree -h\necho ""\necho "=== Disk Usage ==="\ndf -h\necho ""\necho "=== System Uptime ==="\nuptime',
'admin-default-001',
'["System Administration", "Monitoring"]',
'["system", "info", "monitoring", "diagnostics"]',
'["linux", "macos"]',
'bash',
true,
true
);
-- Add the sample script to system collection
INSERT IGNORE INTO `collection_scripts` (
`id`,
`collectionId`,
`scriptId`
) VALUES (
'cs-001',
'collection-system-001',
'script-welcome-001'
);
-- Create indexes for performance optimization
CREATE INDEX IF NOT EXISTS `idx_scripts_name` ON `scripts`(`name`);
CREATE INDEX IF NOT EXISTS `idx_scripts_language` ON `scripts`(`language`);
CREATE INDEX IF NOT EXISTS `idx_analytics_user` ON `script_analytics`(`userId`);
CREATE INDEX IF NOT EXISTS `idx_collections_name` ON `script_collections`(`name`);
-- Set up database optimization settings
SET GLOBAL innodb_buffer_pool_size = 268435456; -- 256MB
SET GLOBAL max_connections = 200;
SET GLOBAL innodb_file_per_table = 1;
-- Print initialization complete message
SELECT 'ScriptShare database initialization completed successfully!' as message;
SELECT COUNT(*) as total_users FROM users;
SELECT COUNT(*) as total_scripts FROM scripts;
SELECT COUNT(*) as total_collections FROM script_collections;