🚀 Add automatic deployment system

- Add auto-deploy.sh script with full CI/CD pipeline
- Add quick-deploy.sh for fast development deployments
- Add Git post-receive hook for automatic deployment on push
- Add comprehensive deployment documentation
- Add npm scripts for easy deployment management
- Include health checks, logging, and cleanup
- Support for automatic rollback on failures
This commit is contained in:
Dennis Konkol
2025-09-05 19:47:53 +00:00
parent 203a332306
commit b9b3e5308d
32 changed files with 2490 additions and 441 deletions

221
scripts/auto-deploy.sh Executable file
View File

@@ -0,0 +1,221 @@
#!/bin/bash
# Auto-Deploy Script für Portfolio
# Führt automatisch Tests, Build und Deployment durch
set -e
# Configuration
PROJECT_NAME="portfolio"
CONTAINER_NAME="portfolio-app"
IMAGE_NAME="portfolio-app"
PORT=3000
BACKUP_PORT=3001
LOG_FILE="/var/log/portfolio-deploy.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Logging function
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" | tee -a "$LOG_FILE"
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1" | tee -a "$LOG_FILE"
}
warning() {
echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "$LOG_FILE"
}
# Check if running as root
if [[ $EUID -eq 0 ]]; then
error "This script should not be run as root"
exit 1
fi
# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
error "Docker is not running. Please start Docker and try again."
exit 1
fi
# Check if we're in the right directory
if [ ! -f "package.json" ] || [ ! -f "Dockerfile" ]; then
error "Please run this script from the project root directory"
exit 1
fi
log "🚀 Starting automatic deployment for $PROJECT_NAME"
# Step 1: Code Quality Checks
log "📋 Step 1: Running code quality checks..."
# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
warning "You have uncommitted changes. Committing them..."
git add .
git commit -m "Auto-commit before deployment $(date)"
fi
# Pull latest changes
log "📥 Pulling latest changes..."
git pull origin main || {
error "Failed to pull latest changes"
exit 1
}
# Run linting
log "🔍 Running ESLint..."
npm run lint || {
error "ESLint failed. Please fix the issues before deploying."
exit 1
}
# Run tests
log "🧪 Running tests..."
npm run test || {
error "Tests failed. Please fix the issues before deploying."
exit 1
}
success "✅ Code quality checks passed"
# Step 2: Build Application
log "🔨 Step 2: Building application..."
# Build Next.js application
log "📦 Building Next.js application..."
npm run build || {
error "Build failed"
exit 1
}
success "✅ Application built successfully"
# Step 3: Docker Operations
log "🐳 Step 3: Docker operations..."
# Build Docker image
log "🏗️ Building Docker image..."
docker build -t "$IMAGE_NAME:latest" . || {
error "Docker build failed"
exit 1
}
# Tag with timestamp
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
docker tag "$IMAGE_NAME:latest" "$IMAGE_NAME:$TIMESTAMP"
success "✅ Docker image built successfully"
# Step 4: Deployment
log "🚀 Step 4: Deploying application..."
# Check if container is running
if [ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" = "true" ]; then
log "📦 Stopping existing container..."
docker stop "$CONTAINER_NAME" || true
docker rm "$CONTAINER_NAME" || true
fi
# Check if port is available
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then
warning "Port $PORT is in use. Trying backup port $BACKUP_PORT"
DEPLOY_PORT=$BACKUP_PORT
else
DEPLOY_PORT=$PORT
fi
# Start new container
log "🚀 Starting new container on port $DEPLOY_PORT..."
docker run -d \
--name "$CONTAINER_NAME" \
--restart unless-stopped \
-p "$DEPLOY_PORT:3000" \
-e NODE_ENV=production \
"$IMAGE_NAME:latest" || {
error "Failed to start container"
exit 1
}
# Wait for container to be ready
log "⏳ Waiting for container to be ready..."
sleep 10
# Health check
log "🏥 Performing health check..."
HEALTH_CHECK_TIMEOUT=60
HEALTH_CHECK_INTERVAL=2
ELAPSED=0
while [ $ELAPSED -lt $HEALTH_CHECK_TIMEOUT ]; do
if curl -f "http://localhost:$DEPLOY_PORT/api/health" > /dev/null 2>&1; then
success "✅ Application is healthy!"
break
fi
sleep $HEALTH_CHECK_INTERVAL
ELAPSED=$((ELAPSED + HEALTH_CHECK_INTERVAL))
echo -n "."
done
if [ $ELAPSED -ge $HEALTH_CHECK_TIMEOUT ]; then
error "Health check timeout. Application may not be running properly."
log "Container logs:"
docker logs "$CONTAINER_NAME" --tail=50
exit 1
fi
# Step 5: Verification
log "✅ Step 5: Verifying deployment..."
# Test main page
if curl -f "http://localhost:$DEPLOY_PORT/" > /dev/null 2>&1; then
success "✅ Main page is accessible"
else
error "❌ Main page is not accessible"
exit 1
fi
# Show container status
log "📊 Container status:"
docker ps --filter "name=$CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# Show resource usage
log "📈 Resource usage:"
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" "$CONTAINER_NAME"
# Step 6: Cleanup
log "🧹 Step 6: Cleaning up old images..."
# Remove old images (keep last 3 versions)
docker images "$IMAGE_NAME" --format "table {{.Tag}}\t{{.ID}}" | tail -n +2 | head -n -3 | awk '{print $2}' | xargs -r docker rmi || {
warning "No old images to remove"
}
# Clean up unused Docker resources
docker system prune -f --volumes || {
warning "Failed to clean up Docker resources"
}
# Final success message
success "🎉 Deployment completed successfully!"
log "🌐 Application is available at: http://localhost:$DEPLOY_PORT"
log "🏥 Health check endpoint: http://localhost:$DEPLOY_PORT/api/health"
log "📊 Container name: $CONTAINER_NAME"
log "📝 Logs: docker logs $CONTAINER_NAME"
# Update deployment log
echo "$(date): Deployment successful - Port: $DEPLOY_PORT - Image: $IMAGE_NAME:$TIMESTAMP" >> "$LOG_FILE"
exit 0

160
scripts/deploy.sh Executable file
View File

@@ -0,0 +1,160 @@
#!/bin/bash
# Portfolio Deployment Script
# Usage: ./scripts/deploy.sh [environment]
set -e
# Configuration
ENVIRONMENT=${1:-production}
REGISTRY="ghcr.io"
IMAGE_NAME="dennis-konkol/my_portfolio"
CONTAINER_NAME="portfolio-app"
COMPOSE_FILE="docker-compose.prod.yml"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Logging function
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
# Check if running as root
if [[ $EUID -eq 0 ]]; then
error "This script should not be run as root"
exit 1
fi
# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
error "Docker is not running. Please start Docker and try again."
exit 1
fi
# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null; then
error "docker-compose is not installed. Please install docker-compose and try again."
exit 1
fi
# Check if .env file exists
if [ ! -f .env ]; then
error ".env file not found. Please create it with the required environment variables."
exit 1
fi
log "Starting deployment for environment: $ENVIRONMENT"
# Set image tag based on environment
if [ "$ENVIRONMENT" = "production" ]; then
IMAGE_TAG="production"
else
IMAGE_TAG="main"
fi
FULL_IMAGE_NAME="$REGISTRY/$IMAGE_NAME:$IMAGE_TAG"
log "Using image: $FULL_IMAGE_NAME"
# Login to registry (if needed)
log "Logging in to container registry..."
echo "$GITHUB_TOKEN" | docker login $REGISTRY -u $GITHUB_ACTOR --password-stdin || {
warning "Failed to login to registry. Make sure GITHUB_TOKEN and GITHUB_ACTOR are set."
}
# Pull latest image
log "Pulling latest image..."
docker pull $FULL_IMAGE_NAME || {
error "Failed to pull image $FULL_IMAGE_NAME"
exit 1
}
# Stop and remove old containers
log "Stopping old containers..."
docker-compose -f $COMPOSE_FILE down || {
warning "No old containers to stop"
}
# Remove old images (keep last 3 versions)
log "Cleaning up old images..."
docker images $REGISTRY/$IMAGE_NAME --format "table {{.Tag}}\t{{.ID}}" | tail -n +2 | head -n -3 | awk '{print $2}' | xargs -r docker rmi || {
warning "No old images to remove"
}
# Start new containers
log "Starting new containers..."
docker-compose -f $COMPOSE_FILE up -d || {
error "Failed to start containers"
exit 1
}
# Wait for health check
log "Waiting for application to be healthy..."
HEALTH_CHECK_TIMEOUT=60
HEALTH_CHECK_INTERVAL=2
ELAPSED=0
while [ $ELAPSED -lt $HEALTH_CHECK_TIMEOUT ]; do
if curl -f http://localhost:3000/api/health > /dev/null 2>&1; then
success "Application is healthy!"
break
fi
sleep $HEALTH_CHECK_INTERVAL
ELAPSED=$((ELAPSED + HEALTH_CHECK_INTERVAL))
echo -n "."
done
if [ $ELAPSED -ge $HEALTH_CHECK_TIMEOUT ]; then
error "Health check timeout. Application may not be running properly."
log "Container logs:"
docker-compose -f $COMPOSE_FILE logs --tail=50
exit 1
fi
# Verify deployment
log "Verifying deployment..."
if curl -f http://localhost:3000/api/health > /dev/null 2>&1; then
success "Deployment successful!"
# Show container status
log "Container status:"
docker-compose -f $COMPOSE_FILE ps
# Show resource usage
log "Resource usage:"
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
else
error "Deployment verification failed!"
log "Container logs:"
docker-compose -f $COMPOSE_FILE logs --tail=50
exit 1
fi
# Cleanup
log "Cleaning up unused Docker resources..."
docker system prune -f --volumes || {
warning "Failed to clean up Docker resources"
}
success "Deployment completed successfully!"
log "Application is available at: http://localhost:3000"
log "Health check endpoint: http://localhost:3000/api/health"

167
scripts/monitor.sh Executable file
View File

@@ -0,0 +1,167 @@
#!/bin/bash
# Portfolio Monitoring Script
# Usage: ./scripts/monitor.sh [action]
set -e
# Configuration
CONTAINER_NAME="portfolio-app"
COMPOSE_FILE="docker-compose.prod.yml"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Logging function
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
# Check container health
check_health() {
log "Checking application health..."
if curl -f http://localhost:3000/api/health > /dev/null 2>&1; then
success "Application is healthy"
return 0
else
error "Application is unhealthy"
return 1
fi
}
# Show container status
show_status() {
log "Container status:"
docker-compose -f $COMPOSE_FILE ps
echo ""
log "Resource usage:"
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}"
echo ""
log "Container logs (last 20 lines):"
docker-compose -f $COMPOSE_FILE logs --tail=20
}
# Show detailed metrics
show_metrics() {
log "Detailed metrics:"
# Container info
echo "=== Container Information ==="
docker inspect $CONTAINER_NAME --format='{{.State.Status}} - {{.State.StartedAt}}' 2>/dev/null || echo "Container not found"
# Memory usage
echo ""
echo "=== Memory Usage ==="
docker stats --no-stream --format "{{.MemUsage}}" $CONTAINER_NAME 2>/dev/null || echo "Container not running"
# CPU usage
echo ""
echo "=== CPU Usage ==="
docker stats --no-stream --format "{{.CPUPerc}}" $CONTAINER_NAME 2>/dev/null || echo "Container not running"
# Network usage
echo ""
echo "=== Network Usage ==="
docker stats --no-stream --format "{{.NetIO}}" $CONTAINER_NAME 2>/dev/null || echo "Container not running"
# Disk usage
echo ""
echo "=== Disk Usage ==="
docker system df
}
# Restart container
restart_container() {
log "Restarting container..."
docker-compose -f $COMPOSE_FILE restart
# Wait for health check
log "Waiting for container to be healthy..."
sleep 10
if check_health; then
success "Container restarted successfully"
else
error "Container restart failed"
exit 1
fi
}
# Show logs
show_logs() {
local lines=${1:-50}
log "Showing last $lines lines of logs:"
docker-compose -f $COMPOSE_FILE logs --tail=$lines -f
}
# Cleanup
cleanup() {
log "Cleaning up Docker resources..."
# Remove unused containers
docker container prune -f
# Remove unused images
docker image prune -f
# Remove unused volumes
docker volume prune -f
# Remove unused networks
docker network prune -f
success "Cleanup completed"
}
# Main script logic
case "${1:-status}" in
"health")
check_health
;;
"status")
show_status
;;
"metrics")
show_metrics
;;
"restart")
restart_container
;;
"logs")
show_logs $2
;;
"cleanup")
cleanup
;;
*)
echo "Usage: $0 {health|status|metrics|restart|logs|cleanup}"
echo ""
echo "Commands:"
echo " health - Check application health"
echo " status - Show container status and resource usage"
echo " metrics - Show detailed metrics"
echo " restart - Restart the container"
echo " logs - Show container logs (optional: number of lines)"
echo " cleanup - Clean up unused Docker resources"
exit 1
;;
esac

63
scripts/quick-deploy.sh Executable file
View File

@@ -0,0 +1,63 @@
#!/bin/bash
# Quick Deploy Script für lokale Entwicklung
# Schnelles Deployment ohne umfangreiche Tests
set -e
# Configuration
CONTAINER_NAME="portfolio-app"
IMAGE_NAME="portfolio-app"
PORT=3000
# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'
log() {
echo -e "${BLUE}[$(date +'%H:%M:%S')]${NC} $1"
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1"
}
log "🚀 Quick deployment starting..."
# Build Docker image
log "🏗️ Building Docker image..."
docker build -t "$IMAGE_NAME:latest" .
# Stop existing container
if [ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" = "true" ]; then
log "🛑 Stopping existing container..."
docker stop "$CONTAINER_NAME"
docker rm "$CONTAINER_NAME"
fi
# Start new container
log "🚀 Starting new container..."
docker run -d \
--name "$CONTAINER_NAME" \
--restart unless-stopped \
-p "$PORT:3000" \
-e NODE_ENV=production \
"$IMAGE_NAME:latest"
# Wait and check health
log "⏳ Waiting for container to be ready..."
sleep 5
if curl -f "http://localhost:$PORT/api/health" > /dev/null 2>&1; then
success "✅ Application is running at http://localhost:$PORT"
else
error "❌ Health check failed"
docker logs "$CONTAINER_NAME" --tail=20
exit 1
fi