Migracja strony na VPS – Krok po kroku bez przestojów [Przewodnik 2025]

Migracja strony na VPS – Krok po kroku bez przestojów [Przewodnik 2025]

Migracja strony na VPS – Krok po kroku bez przestojów [Przewodnik 2025]

 

Spis treści

  1. Dlaczego migrować na VPS?
  2. Przygotowanie do migracji
  3. Audit obecnego hostingu
  4. Wybór i konfiguracja VPS
  5. Strategia migracji
  6. Backup danych
  7. Transfer plików
  8. Migracja bazy danych
  9. Konfiguracja domeny i DNS
  10. Testowanie i weryfikacja
  11. Przełączenie ruchu
  12. Monitorowanie po migracji
  13. Optymalizacja po migracji
  14. Troubleshooting
  15. Checklist migracji

Dlaczego migrować na VPS? {#dlaczego-migrowac}

Problemy z hostingiem współdzielonym

Ograniczenia wydajności:

  • Wolne ładowanie strony (>3 sekundy)
  • Przestoje podczas high traffic
  • Ograniczenia zasobów (RAM, CPU)
  • Throttling podczas peak hours
  • Problemy z obsługą większej liczby użytkowników

Ograniczenia funkcjonalne:

  • Brak dostępu do konfiguracji serwera
  • Starsze wersje PHP/MySQL
  • Ograniczone opcje cache’owania
  • Niemożliwość instalacji custom software
  • Ograniczenia w .htaccess

Problemy biznesowe:

  • Utracone konwersje przez wolną stronę
  • Gorsze pozycje w Google (Core Web Vitals)
  • Problemy z handlem wielu produktów
  • Ograniczenia w rozwoju funkcjonalności
  • Brak kontroli nad środowiskiem

Korzyści z migracji na VPS

Wydajność:Dedykowane zasoby – gwarantowana RAM i CPU ✅ Szybsze ładowanie – 2-5x improvement w page speed ✅ Stabilność – brak wpływu innych stron na Twoją ✅ Skalowalność – łatwe zwiększanie zasobów

Kontrola:Root access – pełna kontrola nad systemem ✅ Custom konfiguracje – dostosowanie do potrzeb ✅ Najnowsze technologie – PHP 8.x, HTTP/2, etc. ✅ Zaawansowany cache – Redis, Memcached, OPcache

Bezpieczeństwo:Izolacja – Twoje dane oddzielone od innych ✅ Custom security – własne reguły firewall ✅ SSL certificates – pełna kontrola nad certyfikatami ✅ Regular backups – automatyczne i custom kopie

ROI z migracji

Przykład kalkulacji dla e-commerce:

Obecna konwersja: 2.5%
Po migracji: 3.0% (+0.5% improvement)
Miesięczny ruch: 10,000 visitors
Average order value: 150 zł

Dodatkowy przychód miesięczny:
10,000 × 0.5% × 150 zł = 7,500 zł

Koszt VPS: 200 zł/miesiąc
ROI: (7,500 - 200) / 200 = 3,650% monthly

SEO benefits:

  • Lepsza pozycja w Google przez page speed
  • Wyższa jakość Core Web Vitals
  • Mniejszy bounce rate
  • Więcej indexed pages przez lepszą crawlabilty

Przygotowanie do migracji {#przygotowanie}

Timeline migracji

4 tygodnie przed migracją:

  • [ ] Wybór VPS provider i pakietu
  • [ ] Zamówienie i konfiguracja VPS
  • [ ] Audit obecnego hostingu
  • [ ] Dokumentacja obecnej konfiguracji
  • [ ] Plan komunikacji z zespołem

2 tygodnie przed:

  • [ ] Testowanie VPS environment
  • [ ] Backup strategy implementation
  • [ ] DNS TTL reduction (do 300 seconds)
  • [ ] Przygotowanie migration scripts
  • [ ] Testing environment setup

1 tydzień przed:

  • [ ] Final backup testing
  • [ ] Migration rehearsal na test environment
  • [ ] Team briefing i role assignment
  • [ ] Rollback plan finalization
  • [ ] Monitoring tools setup

Weekend migracji:

  • [ ] Final sync danych
  • [ ] DNS cutover
  • [ ] Traffic monitoring
  • [ ] Functionality testing
  • [ ] Performance validation

Zespół migracji

Role i odpowiedzialności:

Migration Lead:

  • Koordynacja całego procesu
  • Decision making podczas problemów
  • Komunikacja z stakeholders
  • Timeline management

Technical Lead:

  • Server configuration
  • Database migration
  • Application deployment
  • Technical troubleshooting

QA/Testing:

  • Functionality testing
  • Performance validation
  • User experience verification
  • Bug identification i reporting

DevOps/Infrastructure:

  • DNS management
  • Monitoring setup
  • Backup verification
  • Security configuration

Communication plan

Internal team:

Migration Status Updates:
- Daily standup podczas preparation phase
- Hourly updates podczas migration weekend
- Immediate escalation dla critical issues
- Post-migration debrief within 48h

External stakeholders:

Customer Communication:
T-7 days: "Planned maintenance notification"
T-24h: "Final reminder - brief maintenance window"
T-0: "Maintenance in progress"  
T+1h: "Migration completed successfully"
T+24h: "Performance improvements confirmed"

Risk assessment

High-risk scenarios:

DNS propagation delays:

  • Risk: Users might see old site dla 24-48h
  • Mitigation: Lower TTL values, monitor global DNS
  • Contingency: Temporary redirect setup

Database corruption during transfer:

  • Risk: Data loss or inconsistency
  • Mitigation: Multiple backup points, checksums
  • Contingency: Immediate rollback to original

Application compatibility issues:

  • Risk: Features not working on new environment
  • Mitigation: Thorough testing on staging
  • Contingency: Quick rollback plan

Performance degradation:

  • Risk: Slower site after migration
  • Mitigation: Performance testing pre-migration
  • Contingency: Immediate optimization plan

Audit obecnego hostingu {#audit-obecnego}

Inventoryzacja zasobów

Website files audit:

# Sprawdzenie rozmiaru plików
du -sh /public_html/
find /public_html/ -type f -name "*.php" | wc -l
find /public_html/ -type f -name "*.jpg" -o -name "*.png" | wc -l

# Największe pliki
find /public_html/ -type f -exec ls -lah {} \; | sort -nrk 5 | head -20

# Directory structure
tree -d -L 3 /public_html/

Database inventory:

-- Show all databases
SHOW DATABASES;

-- Database sizes
SELECT 
    table_schema AS 'Database',
    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)'
FROM information_schema.tables 
GROUP BY table_schema;

-- Table analysis dla każdej bazy
SELECT 
    table_name AS 'Table',
    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)',
    table_rows AS 'Rows'
FROM information_schema.tables 
WHERE table_schema = 'your_database'
ORDER BY (data_length + index_length) DESC;

Email accounts inventory:

Lista email accounts:
- admin@domain.com (5 GB used)
- info@domain.com (2.1 GB used)  
- support@domain.com (890 MB used)
- newsletter@domain.com (45 MB used)

Email forwarders:
- contact@domain.com → admin@domain.com
- sales@domain.com → team@company.com

Autoresponders:
- vacation@domain.com (seasonal)

Performance baseline

Current performance metrics:

# Website speed testing
curl -o /dev/null -s -w "Total time: %{time_total}s\n" https://yourdomain.com

# Database performance  
mysql -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';"
mysql -e "SHOW GLOBAL STATUS LIKE 'Questions';"

# Resource usage tracking
# (if available through hosting panel)

External performance testing:

Tools do użycia:
- GTmetrix: Overall performance score
- Google PageSpeed Insights: Core Web Vitals
- Pingdom: Load time from multiple locations
- WebPageTest: Detailed waterfall analysis

Baseline measurements:
- Load time: 4.2 seconds
- First Contentful Paint: 2.1s
- Largest Contentful Paint: 3.8s  
- Cumulative Layout Shift: 0.15
- First Input Delay: 180ms

Application analysis

WordPress site analysis:

// Check WordPress version
echo get_bloginfo('version');

// Active plugins audit
$active_plugins = get_option('active_plugins');
foreach($active_plugins as $plugin) {
    echo $plugin . "\n";
}

// Theme information
$theme = wp_get_theme();
echo "Theme: " . $theme->get('Name') . " v" . $theme->get('Version');

// Database size
$db_size = $wpdb->get_var("
    SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) 
    FROM information_schema.tables 
    WHERE table_schema = '" . DB_NAME . "'
");
echo "Database size: " . $db_size . " MB";

Custom application analysis:

Framework detection:
- CMS: WordPress 6.4.2
- Theme: Custom theme based on Genesis
- Plugins: 23 active plugins
- Custom code: 15 custom PHP files

Dependencies:
- PHP version: 7.4.33
- MySQL version: 5.7.44
- Required PHP extensions: gd, curl, mbstring, zip
- External APIs: PayPal, Google Maps, MailChimp

Performance bottlenecks:
- Large images not optimized
- No caching plugins active
- Multiple external script calls
- Unoptimized database queries

Security audit

Current security setup:

SSL Certificate: Let's Encrypt (expires: 2025-04-15)
File permissions: Standard hosting setup
Backup frequency: Weekly (hosting provider)
Security plugins: None active
Firewall: Basic hosting firewall

Vulnerabilities identified:
- WordPress core 1 version behind
- 3 plugins need updates  
- wp-config.php readable (should be 600)
- No two-factor authentication
- Admin user still named "admin"

Wybór i konfiguracja VPS {#wybor-vps}

Sizing requirements

Resource calculations based on audit:

Current resource usage:
- Website files: 2.3 GB
- Database: 890 MB
- Email: 8.1 GB
- Logs: 150 MB
Total: ~11.5 GB

Growth projection (12 months):
- File growth: +50% = 3.5 GB
- Database growth: +100% = 1.8 GB  
- Email growth: +30% = 10.5 GB
Projected total: ~16 GB

Recommended VPS:
- Disk space: 50 GB SSD (3x current usage)
- RAM: 4 GB (dla WordPress + database + cache)
- CPU: 4 vCores
- Bandwidth: 1 TB/month

Performance requirements:

Target performance goals:
- Page load time: <2 seconds (improvement z 4.2s)
- Database query time: <100ms average
- Concurrent users: 200+ simultaneous
- 99.9% uptime SLA

VPS provider selection

Evaluation criteria:

Netrion.pl – Recommended dla polskich stron:Polska lokalizacja – najniższe ping times ✅ SSD/NVMe storage – maksymalna wydajność I/O ✅ 24/7 polskie wsparcie – brak barier językowych ✅ Managed options – pomoc w zarządzaniu ✅ Migration assistance – wsparcie podczas przenoszenia ✅ Backup solutions – automatyczne kopie zapasowe

VPS package recommendation:

Netrion VPS Business:
- 4 GB RAM
- 4 vCPU cores  
- 100 GB NVMe SSD
- 1 Gbps connection
- Unlimited transfer
- DirectAdmin panel
- Daily backups
- Polish support 24/7
Price: ~180 zł/month

Initial VPS setup

Operating system selection:

Recommended: Ubuntu 22.04 LTS
Reasons:
- Long-term support (5 years)
- Excellent PHP/MySQL compatibility
- Large community support
- Regular security updates
- Well-documented

Basic server hardening:

# Update system packages
apt update && apt upgrade -y

# Create non-root user
adduser migration_user
usermod -aG sudo migration_user

# Configure SSH keys
mkdir -p /home/migration_user/.ssh
chmod 700 /home/migration_user/.ssh

# Disable root SSH login
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl restart ssh

# Configure firewall
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw allow 2222/tcp  # DirectAdmin
ufw --force enable

Web stack installation:

# Install LAMP stack
apt install -y nginx mysql-server php8.1-fpm php8.1-mysql php8.1-curl php8.1-gd php8.1-zip php8.1-xml php8.1-mbstring

# Configure PHP-FPM
sed -i 's/memory_limit = 128M/memory_limit = 256M/' /etc/php/8.1/fpm/php.ini
sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' /etc/php/8.1/fpm/php.ini
sed -i 's/post_max_size = 8M/post_max_size = 64M/' /etc/php/8.1/fpm/php.ini

# Restart services
systemctl restart php8.1-fpm nginx mysql

DirectAdmin installation

DirectAdmin setup (jeśli wybrany):

# Download i install DirectAdmin
wget https://download.directadmin.com/directadmin_1.65.tar.gz
tar xzf directadmin_1.65.tar.gz
cd directadmin_1.65
./setup.sh

# Basic DirectAdmin configuration
./directadmin i --hostname=server.yourdomain.com

Alternatywnie: Manual LEMP setup

# Nginx virtual host configuration
cat > /etc/nginx/sites-available/yourdomain.com << EOF
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/yourdomain.com/public_html;
    index index.php index.html;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }
}
EOF

# Enable site
ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

Strategia migracji {#strategia-migracji}

Rodzaje strategii migracji

1. Big Bang Migration:

Timeline: 2-4 godziny downtime
Process:
1. Maintenance mode ON
2. Final backup
3. Transfer all data
4. DNS switch
5. Testing
6. Go live

Pros: Fast, simple
Cons: Downtime required, higher risk
Best dla: Small sites, off-peak migration

2. Staged Migration:

Timeline: 1-2 weeks z minimal downtime
Process:
1. Setup parallel environment
2. Initial data sync
3. Incremental syncs
4. Testing
5. Final sync + DNS switch

Pros: Minimal downtime, lower risk
Cons: More complex, longer timeline
Best dla: Business-critical sites

3. Blue-Green Deployment:

Timeline: 1 week preparation + instant switch
Process:
1. Complete environment replication
2. Switch traffic at load balancer level
3. Instant rollback możliwy

Pros: Zero downtime, instant rollback
Cons: Requires advanced setup
Best dla: High-traffic sites, e-commerce

Recommended strategy selection

For most WordPress sites (Staged Migration):

Phase 1: Environment Preparation (Week 1)

  • VPS setup i configuration
  • Install matching software versions
  • SSL certificate installation
  • Basic security hardening

Phase 2: Initial Data Transfer (Week 2)

  • Transfer website files
  • Database initial import
  • Email accounts setup
  • DNS preparation (lower TTL)

Phase 3: Incremental Sync (Days 1-6)

  • Daily database syncs
  • File synchronization
  • Email sync
  • Testing i optimization

Phase 4: Final Cutover (Weekend)

  • Final sync (under maintenance mode)
  • DNS switch
  • Monitoring i validation
  • Performance optimization

Pre-migration testing

Staging environment setup:

# Create staging subdomain
staging.yourdomain.com
→ Points to new VPS
→ Identical configuration
→ Test data migration process
→ Validate all functionality

Testing checklist:

Functionality Testing:
☐ Homepage loads correctly
☐ All pages accessible
☐ Contact forms working
☐ User registration/login
☐ Shopping cart (if e-commerce)
☐ Payment processing
☐ Search functionality
☐ Admin panel access

Performance Testing:
☐ Page load times <2 seconds
☐ Database queries optimized
☐ Images loading correctly
☐ CSS/JS files loading
☐ Mobile responsiveness
☐ Cross-browser compatibility

Integration Testing:
☐ Email sending/receiving
☐ External API connections
☐ Analytics tracking
☐ Social media integration
☐ Newsletter subscriptions
☐ Customer notifications

Backup danych {#backup-danych}

Comprehensive backup strategy

Files backup:

# Create full website backup
tar -czf website_backup_$(date +%Y%m%d).tar.gz /path/to/website/

# Selective backup dla large sites
tar -czf essential_backup_$(date +%Y%m%d).tar.gz \
    --exclude='/path/to/website/wp-content/cache' \
    --exclude='/path/to/website/wp-content/uploads/backup' \
    /path/to/website/

# Verify backup integrity
tar -tzf website_backup_$(date +%Y%m%d).tar.gz > /dev/null && echo "Backup OK"

Database backup:

# Single database backup
mysqldump -u username -p database_name > db_backup_$(date +%Y%m%d).sql

# All databases backup
mysqldump -u root -p --all-databases > all_databases_$(date +%Y%m%d).sql

# Compressed database backup
mysqldump -u username -p database_name | gzip > db_backup_$(date +%Y%m%d).sql.gz

# Database backup z structure only (dla testing)
mysqldump -u username -p --no-data database_name > structure_only.sql

Email backup:

# Email accounts backup (if using mail server)
tar -czf email_backup_$(date +%Y%m%d).tar.gz /home/*/mail/

# Individual mailbox backup
tar -czf mailbox_user_$(date +%Y%m%d).tar.gz /home/user/mail/domain.com/username/

Backup verification

File integrity checking:

# Create checksums
find /path/to/website -type f -exec sha256sum {} \; > checksums_original.txt

# Verify after restore
sha256sum -c checksums_original.txt

# Compare directory structures
diff -r /original/path /restored/path

Database integrity checking:

-- Check table integrity
CHECK TABLE wp_posts;
CHECK TABLE wp_options;
CHECK TABLE wp_users;

-- Analyze tables
ANALYZE TABLE wp_posts;

-- Repair if needed
REPAIR TABLE wp_posts;

Multiple backup locations

Local backups:

# Primary backup location
/home/user/backups/daily/
/home/user/backups/weekly/
/home/user/backups/monthly/

# Backup rotation script
#!/bin/bash
BACKUP_DIR="/home/user/backups"
DATE=$(date +%Y%m%d)

# Create daily backup
tar -czf "$BACKUP_DIR/daily/backup_$DATE.tar.gz" /path/to/website/

# Rotate backups (keep 7 daily, 4 weekly, 12 monthly)
find "$BACKUP_DIR/daily/" -type f -mtime +7 -delete
find "$BACKUP_DIR/weekly/" -type f -mtime +28 -delete
find "$BACKUP_DIR/monthly/" -type f -mtime +365 -delete

Remote backups:

# SFTP backup to remote server
sftp backup@remote-server.com << EOF
cd /backups/yourdomain.com/
put backup_$(date +%Y%m%d).tar.gz
bye
EOF

# Cloud backup (AWS S3 example)
aws s3 cp backup_$(date +%Y%m%d).tar.gz s3://your-backup-bucket/yourdomain.com/

# Rsync to remote location
rsync -avz /local/backup/ user@remote:/backup/destination/

Automated backup scheduling

Cron job setup:

# Daily backup at 2 AM
0 2 * * * /home/user/scripts/daily_backup.sh

# Weekly backup on Sundays at 3 AM  
0 3 * * 0 /home/user/scripts/weekly_backup.sh

# Monthly backup on 1st at 4 AM
0 4 1 * * /home/user/scripts/monthly_backup.sh

Backup monitoring:

#!/bin/bash
# backup_monitor.sh

BACKUP_DIR="/home/user/backups/daily"
LATEST_BACKUP=$(ls -t $BACKUP_DIR | head -1)
BACKUP_AGE=$(find $BACKUP_DIR/$LATEST_BACKUP -mtime +1)

if [ -n "$BACKUP_AGE" ]; then
    echo "WARNING: Latest backup is older than 24 hours" | \
    mail -s "Backup Alert" admin@yourdomain.com
fi

# Check backup size (should be reasonable)
BACKUP_SIZE=$(du -h $BACKUP_DIR/$LATEST_BACKUP | awk '{print $1}')
echo "Latest backup size: $BACKUP_SIZE" | \
mail -s "Daily Backup Report" admin@yourdomain.com

Transfer plików {#transfer-plikow}

Metody transferu plików

1. SFTP/SCP Transfer:

# Single file transfer
scp /local/file.txt user@new-vps:/remote/path/

# Directory transfer z compression
tar -czf - /local/website/ | ssh user@new-vps "cd /remote/path && tar -xzf -"

# Rsync dla large transfers
rsync -avz --progress /local/website/ user@new-vps:/remote/path/

# Resume interrupted transfers
rsync -avz --partial --progress /local/website/ user@new-vps:/remote/path/

2. FTP/SFTP via FileZilla/WinSCP:

Configuration:
Protocol: SFTP
Host: new-vps-ip
Port: 22
Username: migration_user
Password: [or SSH key]

Transfer settings:
- Binary transfer mode
- Preserve timestamps
- Resume interrupted transfers
- Transfer only newer files

3. wget/curl (for accessible files):

# Download from current hosting (if accessible via HTTP)
wget -r -np -k -E -p http://yourdomain.com/

# Mirror entire website
wget --mirror --convert-links --adjust-extension \
     --page-requisites --no-parent http://yourdomain.com/

Large file optimization

Pre-transfer optimization:

# Identify large files
find /website/path -size +100M -ls

# Compress uploads directory
tar -czf uploads_backup.tar.gz wp-content/uploads/
# Transfer compressed file, then extract on target

# Split large files
split -b 100M large_file.tar.gz large_file_part_

# Transfer parts separately, then reassemble
cat large_file_part_* > large_file.tar.gz

Transfer monitoring:

# Monitor transfer progress
rsync -avz --progress --stats /source/ destination/

# Bandwidth limiting (dla live sites)
rsync -avz --bwlimit=1000 /source/ destination/  # 1MB/s limit

# Parallel transfers dla multiple files
parallel -j 4 scp {} user@newvps:/destination/ ::: file1 file2 file3 file4

File permissions preservation

WordPress permissions setup:

# Set correct permissions on new VPS
find /var/www/yourdomain.com/ -type d -exec chmod 755 {} \;
find /var/www/yourdomain.com/ -type f -exec chmod 644 {} \;

# Special permissions dla WordPress
chmod 600 wp-config.php
chmod 755 wp-content/
chmod 755 wp-content/uploads/
chmod 644 .htaccess

# Set ownership
chown -R www-data:www-data /var/www/yourdomain.com/

Verification script:

#!/bin/bash
# verify_permissions.sh

WEBSITE_PATH="/var/www/yourdomain.com"

echo "Checking file permissions..."

# Check sensitive files
if [ $(stat -c %a "$WEBSITE_PATH/wp-config.php") != "600" ]; then
    echo "WARNING: wp-config.php permissions incorrect"
fi

# Check directory permissions
find "$WEBSITE_PATH" -type d ! -perm 755 -ls | head -10

# Check file permissions
find "$WEBSITE_PATH" -type f ! -perm 644 ! -name "wp-config.php" -ls | head -10

echo "Permission check completed"

Incremental sync strategy

Initial transfer:

# First transfer - everything
rsync -avz /source/website/ user@newvps:/destination/website/

Incremental updates:

# Daily incremental sync during preparation phase
rsync -avz --delete /source/website/ user@newvps:/destination/website/

# Sync only changes z last 24 hours
find /source/website -mtime -1 -type f | \
rsync -avz --files-from=- / user@newvps:/destination/

# Final sync podczas maintenance window
rsync -avz --delete --exclude='*.log' /source/ user@newvps:/destination/

Migracja bazy danych {#migracja-bazy}

Database dump i transfer

Creating optimized database dump:

# Standard mysqldump
mysqldump -u username -p \
  --single-transaction \
  --routines \
  --triggers \
  database_name > database_export.sql

# Compressed dump dla large databases
mysqldump -u username -p \
  --single-transaction \
  --routines \
  --triggers \
  database_name | gzip > database_export.sql.gz

# Split large dumps
mysqldump -u username -p database_name | split -l 50000 - database_part_

# Dump z extended inserts (faster import)
mysqldump -u username -p \
  --single-transaction \
  --extended-insert \
  --quick \
  --lock-tables=false \
  database_name > database_export.sql

Database import on new VPS:

# Create database and user
mysql -u root -p
CREATE DATABASE new_database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'db_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON new_database_name.* TO 'db_user'@'localhost';
FLUSH PRIVILEGES;

# Import database
mysql -u db_user -p new_database_name < database_export.sql

# Monitor import progress (dla large databases)
pv database_export.sql | mysql -u db_user -p new_database_name

WordPress-specific database migration

WordPress database modifications:

-- Update site URLs
UPDATE wp_options SET option_value = 'https://yourdomain.com' 
WHERE option_name = 'home';

UPDATE wp_options SET option_value = 'https://yourdomain.com' 
WHERE option_name = 'siteurl';

-- Update upload paths (if changed)
UPDATE wp_options SET option_value = '/var/www/yourdomain.com/public_html/wp-content/uploads' 
WHERE option_name = 'upload_path';

-- Fix serialized data (if domain changed)
UPDATE wp_options SET option_value = REPLACE(option_value, 'http://olddomain.com', 'https://yourdomain.com');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'http://olddomain.com', 'https://yourdomain.com');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, 'http://olddomain.com', 'https://yourdomain.com');

Search and replace script dla WordPress:

# Using WP-CLI (recommended)
wp search-replace 'http://olddomain.com' 'https://yourdomain.com' --dry-run
wp search-replace 'http://olddomain.com' 'https://yourdomain.com'

# Verify changes
wp option get home
wp option get siteurl

Database optimization post-migration

Performance optimization:

-- Optimize all tables
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_comments, wp_commentmeta, wp_options, wp_users, wp_usermeta;

-- Repair any corrupted tables
REPAIR TABLE wp_posts;
CHECK TABLE wp_posts;

-- Update table statistics
ANALYZE TABLE wp_posts, wp_postmeta, wp_comments, wp_options;

-- Add missing indexes (if needed)
ALTER TABLE wp_postmeta ADD INDEX meta_key_value (meta_key, meta_value(10));
ALTER TABLE wp_posts ADD INDEX post_name (post_name);

Database cleanup:

-- Remove spam comments
DELETE FROM wp_comments WHERE comment_approved = 'spam';

-- Clean post revisions (keep last 3)
DELETE FROM wp_posts 
WHERE post_type = 'revision' 
AND ID NOT IN (
    SELECT * FROM (
        SELECT ID FROM wp_posts 
        WHERE post_type = 'revision' 
        ORDER BY post_date DESC 
        LIMIT 3
    ) AS temp
);

-- Remove orphaned metadata
DELETE FROM wp_postmeta 
WHERE post_id NOT IN (SELECT ID FROM wp_posts);

DELETE FROM wp_commentmeta 
WHERE comment_id NOT IN (SELECT comment_ID FROM wp_comments);

-- Remove unused tags and categories
DELETE FROM wp_terms 
WHERE term_id NOT IN (SELECT term_id FROM wp_term_relationships);

Database synchronization dla staged migration

Initial sync:

# Export from source
mysqldump -u source_user -p source_db > initial_sync.sql

# Import to target
mysql -u target_user -p target_db < initial_sync.sql

Incremental sync (during preparation phase):

#!/bin/bash
# incremental_db_sync.sh

SOURCE_DB="source_database"
TARGET_DB="target_database"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Export only recent changes (posts, comments modified in last 24h)
mysqldump -u source_user -p $SOURCE_DB \
  --where="post_modified > DATE_SUB(NOW(), INTERVAL 1 DAY)" \
  wp_posts > recent_posts.sql

mysqldump -u source_user -p $SOURCE_DB \
  --where="comment_date > DATE_SUB(NOW(), INTERVAL 1 DAY)" \
  wp_comments > recent_comments.sql

# Import incremental changes
mysql -u target_user -p $TARGET_DB < recent_posts.sql
mysql -u target_user -p $TARGET_DB < recent_comments.sql

echo "Incremental sync completed at $TIMESTAMP"

Konfiguracja domeny i DNS {#konfiguracja-dns}

DNS preparation strategy

Phase 1: TTL Reduction (1 week before migration)

Lower TTL values dla all DNS records:
A record: 300 seconds (5 minutes)
CNAME records: 300 seconds
MX records: 300 seconds
TXT records: 300 seconds

This allows faster propagation during cutover

Phase 2: DNS Records Inventory

# Document current DNS settings
dig yourdomain.com ANY
dig yourdomain.com MX
dig yourdomain.com TXT
nslookup -type=NS yourdomain.com

# Common records to migrate:
A record: yourdomain.com → old-server-IP
A record: www.yourdomain.com → old-server-IP
MX record: yourdomain.com → mail.yourdomain.com (priority 10)
CNAME: mail → yourdomain.com
TXT: SPF record
TXT: DKIM records
TXT: Domain verification records

DNS cutover strategy

Option 1: Registrar DNS Update

If DNS managed przez domain registrar:
1. Login to registrar control panel
2. Update A records to new VPS IP
3. Update any IP-specific records
4. Monitor propagation z online tools

Propagation time: 4-24 hours globally
Control: Limited to registrar interface

Option 2: Nameserver Migration

If switching to VPS provider DNS:
1. Configure DNS records na new nameservers
2. Update nameservers at registrar
3. Wait dla propagation

Example - Netrion.pl nameservers:
ns1.netrion.pl
ns2.netrion.pl

Configuration time: Immediate on new NS
Propagation time: 24-48 hours

Option 3: Cloudflare DNS (Recommended)

Benefits:
- Instant DNS updates
- Global CDN
- DDoS protection
- SSL automation
- Analytics

Setup process:
1. Create Cloudflare account
2. Add domain to Cloudflare
3. Import existing DNS records
4. Update nameservers to Cloudflare
5. Configure proxy settings

DNS record configuration

Essential DNS records dla new VPS:

A Records:
yourdomain.com        → new-vps-ip (proxy OFF dla email)
www.yourdomain.com    → new-vps-ip (proxy ON dla website)

CNAME Records:
mail.yourdomain.com   → yourdomain.com
ftp.yourdomain.com    → yourdomain.com

MX Records:
yourdomain.com        → mail.yourdomain.com (priority 10)

TXT Records:
yourdomain.com        → "v=spf1 a mx ip4:new-vps-ip ~all"
_dmarc.yourdomain.com → "v=DMARC1; p=none; rua=mailto:admin@yourdomain.com"

Email-specific DNS configuration:

SPF Record:
"v=spf1 a mx ip4:your-vps-ip include:_spf.google.com ~all"

DKIM Setup (if using mail server):
selector1._domainkey.yourdomain.com → DKIM public key

DMARC Policy:
"v=DMARC1; p=quarantine; rua=mailto:dmarc@yourdomain.com; pct=100"

DNS propagation monitoring

Tools dla monitoring propagation:

Online tools:
- whatsmydns.net - Global DNS checker
- dnschecker.org - Multiple location testing
- dns.google - Google's DNS lookup
- 8.8.8.8 testing

Command line monitoring:
dig @8.8.8.8 yourdomain.com
dig @1.1.1.1 yourdomain.com  
nslookup yourdomain.com 8.8.8.8

Propagation verification script:

#!/bin/bash
# dns_propagation_check.sh

DOMAIN="yourdomain.com"
NEW_IP="your-new-vps-ip"

echo "Checking DNS propagation dla $DOMAIN..."

# Test multiple DNS servers
DNS_SERVERS=("8.8.8.8" "1.1.1.1" "9.9.9.9" "208.67.222.222")

for server in "${DNS_SERVERS[@]}"; do
    RESULT=$(dig @$server +short $DOMAIN)
    if [ "$RESULT" = "$NEW_IP" ]; then
        echo "✓ $server: $RESULT (Updated)"
    else
        echo "✗ $server: $RESULT (Not updated)"
    fi
done

# Check TTL values
echo -e "\nCurrent TTL values:"
dig $DOMAIN | grep -E "^$DOMAIN.*IN.*A"

Subdomain configuration

Common subdomains to configure:

www.yourdomain.com     → Main website
mail.yourdomain.com    → Webmail access
ftp.yourdomain.com     → FTP access
cpanel.yourdomain.com  → Control panel (if applicable)
api.yourdomain.com     → API endpoint
blog.yourdomain.com    → Blog subdomain
shop.yourdomain.com    → E-commerce section

DirectAdmin subdomain setup:

1. Login to DirectAdmin
2. Subdomain Management
3. Create Subdomain:
   - Subdomain: blog
   - Domain: yourdomain.com  
   - Document Root: /domains/yourdomain.com/public_html/blog
4. Configure DNS automatically

Testowanie i weryfikacja {#testowanie}

Pre-cutover testing

Testing environment setup:

Test access methods:
1. Hosts file modification (dla immediate testing)
2. Staging subdomain (staging.yourdomain.com)
3. Temporary domain (yourdomain.newvps.com)
4. IP-based access (http://vps-ip/~username/)

Recommended: Staging subdomain approach
staging.yourdomain.com → new-vps-ip

Hosts file testing (dla developers):

# Windows: C:\Windows\System32\drivers\etc\hosts
# Mac/Linux: /etc/hosts

# Add this line dla testing:
new-vps-ip yourdomain.com www.yourdomain.com

# Test website access, then remove line after testing

Comprehensive functionality testing

Website functionality checklist:

☐ Homepage loads correctly
☐ All navigation menu items work
☐ Internal links functional
☐ Contact forms submit successfully
☐ Search functionality works
☐ User registration/login system
☐ Password reset functionality
☐ File downloads work
☐ Image galleries load
☐ Video embeds play correctly

WordPress-specific:
☐ Admin panel accessible
☐ Themes load correctly
☐ Plugins function properly
☐ Widget areas display
☐ Customizer works
☐ Media library accessible
☐ Post editing/publishing
☐ Comments system
☐ RSS feeds generate
☐ Sitemap.xml accessible

E-commerce testing (if applicable):

☐ Product pages load
☐ Shopping cart functionality
☐ Checkout process complete
☐ Payment gateway integration
☐ Order confirmation emails
☐ User account creation
☐ Inventory management
☐ Shipping calculations
☐ Tax calculations
☐ Coupon codes work
☐ Admin order management

Performance testing

Speed testing tools:

# Command-line speed testing
time curl -o /dev/null -s yourdomain.com

# Load testing z apache bench
ab -n 1000 -c 10 http://yourdomain.com/

# More comprehensive load testing
wrk -t12 -c400 -d30s http://yourdomain.com/

Performance benchmarking:

Before migration (baseline):
- Load time: 4.2 seconds
- First paint: 2.1 seconds
- Time to interactive: 5.8 seconds
- Page size: 2.3 MB

After migration (target):
- Load time: <2.0 seconds
- First paint: <1.0 second  
- Time to interactive: <3.0 seconds
- Page size: <2.0 MB (after optimization)

Core Web Vitals monitoring:

// Add to website dla monitoring
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    if (entry.name === 'first-contentful-paint') {
      console.log('FCP:', entry.startTime);
    }
    if (entry.name === 'largest-contentful-paint') {
      console.log('LCP:', entry.startTime);
    }
  }
}).observe({entryTypes: ['paint', 'largest-contentful-paint']});

Security testing

Basic security verification:

# SSL certificate testing
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

# Security headers check
curl -I https://yourdomain.com | grep -i "security\|x-frame\|x-xss"

# WordPress security check (if applicable)
wpscan --url https://yourdomain.com --enumerate u

File permissions audit:

# Check sensitive file permissions
find /var/www/yourdomain.com -name "wp-config.php" -exec ls -la {} \;
find /var/www/yourdomain.com -name ".htaccess" -exec ls -la {} \;

# Check dla world-writable files (security risk)
find /var/www/yourdomain.com -type f -perm -002 -ls

# Verify proper ownership
ls -la /var/www/yourdomain.com/

Email testing

Email functionality verification:

Outgoing email tests:
☐ Contact form submissions send emails
☐ User registration emails arrive
☐ Password reset emails work
☐ E-commerce order confirmations
☐ Newsletter subscriptions
☐ Admin notifications

Incoming email tests:
☐ Email accounts receive mail
☐ Webmail access functional
☐ IMAP/POP3 client access
☐ Email forwarding works
☐ Autoresponders active
☐ Spam filtering effective

Email delivery testing:

# Test SMTP functionality
telnet mail.yourdomain.com 587
# EHLO yourdomain.com
# MAIL FROM: test@yourdomain.com
# RCPT TO: recipient@gmail.com
# DATA
# Test message content
# .
# QUIT

# SPF/DKIM validation
echo "Test email body" | mail -s "Test Subject" test@gmail.com
# Check email headers dla SPF/DKIM status

Mobile and browser testing

Cross-browser compatibility:

Desktop browsers:
☐ Chrome (latest)
☐ Firefox (latest)
☐ Safari (latest)
☐ Edge (latest)

Mobile browsers:
☐ Chrome Mobile
☐ Safari iOS
☐ Samsung Internet
☐ Firefox Mobile

Testing aspects:
☐ Layout rendering
☐ JavaScript functionality
☐ Form submissions
☐ Media playback
☐ Touch interactions
☐ Responsive design

Mobile testing tools:

Browser dev tools:
- Chrome DevTools device simulation
- Firefox Responsive Design Mode
- Safari Web Inspector

Online testing:
- BrowserStack
- CrossBrowserTesting
- LambdaTest

Physical device testing:
- iOS devices (iPhone, iPad)
- Android devices (various manufacturers)
- Different screen sizes

Przełączenie ruchu {#przelaczenie-ruchu}

Final cutover planning

Maintenance window scheduling:

Optimal timing dla most websites:
- Weekend (less business impact)
- Late evening/early morning
- Off-peak traffic hours
- Avoid holiday periods
- Consider global audience time zones

Example schedule:
Friday 10 PM - Sunday 6 AM (34-hour window)
- Friday 10 PM: Begin final sync
- Saturday 2 AM: DNS cutover
- Saturday 6 AM: Primary testing complete
- Sunday 6 AM: Full validation complete

Team coordination:

Migration team roles podczas cutover:

Migration Lead:
- Overall coordination
- Go/no-go decisions
- Stakeholder communication
- Escalation management

Technical Lead:
- Execute technical steps
- Monitor system performance  
- Troubleshoot issues
- Database integrity verification

QA Engineer:
- Functionality testing
- User acceptance testing
- Bug identification
- Performance validation

DevOps Engineer:
- DNS management
- Server monitoring
- Security verification
- Backup validation

Step-by-step cutover process

Hour -2: Final preparation

# Final incremental sync
rsync -avz --delete /source/files/ newvps:/destination/files/

# Final database sync
mysqldump source_db | mysql -h newvps target_db

# Verify all services running on new VPS
systemctl status nginx php8.1-fpm mysql

# Pre-cutover testing
curl -I http://new-vps-ip/

Hour -1: Maintenance mode

// WordPress maintenance mode
// File: wp-content/maintenance.php
<?php
$upgrading = time();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Maintenance in Progress</title>
    <meta charset="utf-8">
    <style>
        body { font-family: Arial; text-align: center; padding: 50px; }
        .maintenance { max-width: 600px; margin: 0 auto; }
    </style>
</head>
<body>
    <div class="maintenance">
        <h1>Website Under Maintenance</h1>
        <p>We're upgrading our servers dla better performance.</p>
        <p>We'll be back online within 2 hours.</p>
        <p>Thank you dla your patience!</p>
    </div>
</body>
</html>

Hour 0: DNS cutover

# Update DNS records (Cloudflare example)
# A record: yourdomain.com → new-vps-ip
# A record: www.yourdomain.com → new-vps-ip

# Monitor DNS propagation
watch -n 30 'dig @8.8.8.8 yourdomain.com +short'

# Verify change took effect
nslookup yourdomain.com 8.8.8.8
nslookup yourdomain.com 1.1.1.1

Hour +1: Validation and monitoring

# Website accessibility test
curl -I https://yourdomain.com

# Performance testing
time curl -o /dev/null -s https://yourdomain.com

# Database connectivity test
mysql -h localhost -u dbuser -p -e "SELECT COUNT(*) FROM wp_posts;"

# Email functionality test
echo "Test after migration" | mail -s "Post-migration test" admin@yourdomain.com

Traffic monitoring

Real-time monitoring setup:

# Nginx access log monitoring
tail -f /var/log/nginx/access.log | awk '{print $1, $7, $9, $10}'

# Traffic volume monitoring
tail -f /var/log/nginx/access.log | pv -l -r > /dev/null

# Error monitoring
tail -f /var/log/nginx/error.log
tail -f /var/log/php8.1-fpm.log

Analytics verification:

// Verify Google Analytics tracking
gtag('event', 'migration_test', {
    'event_category': 'technical',
    'event_label': 'post_migration',
    'value': 1
});

// Monitor dla tracking issues
console.log('GA Tracking ID:', gtag.config.GA_TRACKING_ID);

Rollback procedures

Criteria dla rollback:

Automatic rollback triggers:
- Website completely inaccessible dla >15 minutes
- Database corruption detected
- Email completely non-functional
- Performance degradation >50%

Manual rollback triggers:
- Critical functionality broken
- Payment processing failures
- Data integrity issues
- Security vulnerabilities discovered

Rollback process:

# Emergency rollback steps:

1. DNS revert (immediate):
   # Change A records back to old server IP
   # TTL is already low (300s) so propagation fast

2. Communication:
   # Notify team of rollback decision
   # Prepare customer communication

3. Investigation:
   # Identify root cause
   # Plan fix dla retry

4. Cleanup:
   # Document lessons learned
   # Update migration plan
   # Schedule retry date

Quick rollback script:

#!/bin/bash
# emergency_rollback.sh

echo "EMERGENCY ROLLBACK INITIATED"
echo "Reverting DNS to original server..."

# Update DNS via API (example dla Cloudflare)
curl -X PUT "https://api.cloudflare.com/client/v4/zones/ZONE_ID/dns_records/RECORD_ID" \
     -H "Authorization: Bearer YOUR_API_TOKEN" \
     -H "Content-Type: application/json" \
     --data '{"type":"A","name":"yourdomain.com","content":"OLD_SERVER_IP","ttl":300}'

echo "DNS rollback completed"
echo "Notifying team..."

# Send notification
echo "Emergency rollback executed at $(date)" | \
mail -s "URGENT: Migration Rollback" team@yourdomain.com

echo "Rollback process completed"

Monitorowanie po migracji {#monitorowanie}

Immediate post-migration monitoring (First 24 hours)

System resource monitoring:

# CPU and memory monitoring
htop
top -p $(pgrep nginx)
top -p $(pgrep mysql)
top -p $(pgrep php-fpm)

# Disk I/O monitoring
iostat -x 1
iotop

# Network monitoring
netstat -i
ss -tuln

Application monitoring:

# Website response time
while true; do
    time curl -o /dev/null -s https://yourdomain.com
    sleep 60
done

# Database performance
mysql -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';"
mysql -e "SHOW GLOBAL STATUS LIKE 'Questions';"
mysql -e "SHOW PROCESSLIST;"

# PHP-FPM status
curl http://localhost/fpm-status

Error monitoring:

# Monitor error logs continuously
tail -f /var/log/nginx/error.log
tail -f /var/log/mysql/error.log  
tail -f /var/log/php8.1-fpm.log
tail -f /var/www/yourdomain.com/logs/error.log

# Error counting script
#!/bin/bash
ERROR_COUNT=$(grep -c "ERROR\|CRITICAL" /var/log/nginx/error.log)
if [ $ERROR_COUNT -gt 10 ]; then
    echo "High error count: $ERROR_COUNT" | \
    mail -s "Error Alert" admin@yourdomain.com
fi

Performance monitoring

Website speed monitoring:

# Automated speed testing
#!/bin/bash
# speed_monitor.sh

URL="https://yourdomain.com"
THRESHOLD=3.0

while true; do
    LOAD_TIME=$(curl -o /dev/null -s -w "%{time_total}" $URL)
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    
    echo "$TIMESTAMP: Load time: ${LOAD_TIME}s"
    
    if (( $(echo "$LOAD_TIME > $THRESHOLD" | bc -l) )); then
        echo "ALERT: Load time ${LOAD_TIME}s exceeds threshold ${THRESHOLD}s" | \
        mail -s "Performance Alert" admin@yourdomain.com
    fi
    
    sleep 300  # Check every 5 minutes
done

Google Analytics monitoring:

// Enhanced tracking dla migration monitoring
gtag('config', 'GA_TRACKING_ID', {
    'custom_map': {
        'custom_parameter_1': 'server_migration'
    }
});

// Track server response times
window.addEventListener('load', function() {
    const navigationTiming = performance.getEntriesByType('navigation')[0];
    const serverTime = navigationTiming.responseEnd - navigationTiming.requestStart;
    
    gtag('event', 'server_response_time', {
        'event_category': 'performance',
        'event_label': 'post_migration',
        'value': Math.round(serverTime)
    });
});

Business metrics monitoring

E-commerce monitoring (if applicable):

-- Monitor order processing
SELECT 
    DATE(order_date) as date,
    COUNT(*) as orders,
    SUM(order_total) as revenue
FROM orders 
WHERE order_date >= CURDATE() - INTERVAL 7 DAY
GROUP BY DATE(order_date)
ORDER BY date DESC;

-- Check dla failed payments
SELECT COUNT(*) as failed_payments
FROM orders 
WHERE status = 'failed' 
AND order_date >= CURDATE() - INTERVAL 1 DAY;

SEO monitoring:

# Monitor crawl errors
# Check Google Search Console API
# Monitor sitemap accessibility
curl -I https://yourdomain.com/sitemap.xml

# Check robots.txt
curl https://yourdomain.com/robots.txt

Email delivery monitoring

Email functionality testing:

# Automated email testing
#!/bin/bash
# email_monitor.sh

TEST_EMAIL="test@yourdomain.com"
EXTERNAL_EMAIL="monitor@gmail.com"

# Test outbound email
echo "Test email $(date)" | mail -s "Automated test" $EXTERNAL_EMAIL

# Test contact form (if available)
curl -X POST https://yourdomain.com/contact-form \
     -d "name=Test User&email=test@example.com&message=Migration test"

# Check mail queue
mailq | wc -l

Email deliverability monitoring:

Tools dla monitoring:
- MXToolbox: DNS and deliverability testing
- Mail-tester.com: Spam score checking
- DMARC Analyzer: Authentication monitoring
- Google Postmaster Tools: Gmail delivery stats

Automated alerting setup

System alerts configuration:

# Install monitoring tools
apt install -y monit

# Configure monit dla service monitoring
cat > /etc/monit/conf.d/web-services << EOF
check process nginx with pidfile /var/run/nginx.pid
    start program = "/bin/systemctl start nginx"
    stop program = "/bin/systemctl stop nginx"
    if failed host 127.0.0.1 port 80 protocol http then restart
    if 5 restarts within 5 cycles then timeout

check process mysql with pidfile /var/run/mysqld/mysqld.pid
    start program = "/bin/systemctl start mysql"
    stop program = "/bin/systemctl stop mysql"
    if failed host 127.0.0.1 port 3306 then restart
    if 5 restarts within 5 cycles then timeout

check process php8.1-fpm with pidfile /var/run/php/php8.1-fpm.pid
    start program = "/bin/systemctl start php8.1-fpm"
    stop program = "/bin/systemctl stop php8.1-fpm"
    if failed unixsocket /var/run/php/php8.1-fpm.sock then restart
EOF

systemctl enable monit
systemctl start monit

Custom monitoring scripts:

# Comprehensive monitoring script
#!/bin/bash
# migration_monitor.sh

LOG_FILE="/var/log/migration_monitor.log"
ALERT_EMAIL="admin@yourdomain.com"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> $LOG_FILE
}

# Website availability
if ! curl -f -s https://yourdomain.com > /dev/null; then
    log_message "CRITICAL: Website not accessible"
    echo "Website down" | mail -s "CRITICAL ALERT" $ALERT_EMAIL
fi

# Database connectivity
if ! mysql -e "SELECT 1" > /dev/null 2>&1; then
    log_message "CRITICAL: Database not accessible"
    echo "Database connection failed" | mail -s "CRITICAL ALERT" $ALERT_EMAIL
fi

# Disk space check
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 90 ]; then
    log_message "WARNING: Disk usage at ${DISK_USAGE}%"
    echo "High disk usage: ${DISK_USAGE}%" | mail -s "Disk Space Warning" $ALERT_EMAIL
fi

# Load average check
LOAD_AVG=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
if (( $(echo "$LOAD_AVG > 5.0" | bc -l) )); then
    log_message "WARNING: High load average: $LOAD_AVG"
    echo "High server load: $LOAD_AVG" | mail -s "Load Average Alert" $ALERT_EMAIL
fi

log_message "Monitoring check completed"

Optymalizacja po migracji {#optymalizacja}

Performance optimization

Web server optimization (Nginx):

# /etc/nginx/nginx.conf optimizations
worker_processes auto;
worker_connections 1024;

# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json;

# Browser caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

PHP optimization:

# /etc/php/8.1/fpm/php.ini optimizations
memory_limit = 256M
max_execution_time = 300
max_input_time = 300
post_max_size = 64M
upload_max_filesize = 64M
max_file_uploads = 20

# OPcache dla PHP performance
opcache.enable = 1
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 2
opcache.fast_shutdown = 1
opcache.enable_cli = 1

MySQL optimization:

# /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M

tmp_table_size = 64M
max_heap_table_size = 64M

# Restart MySQL after changes
systemctl restart mysql

Caching implementation

Redis cache setup:

# Install Redis
apt install -y redis-server

# Configure Redis
sed -i 's/# maxmemory <bytes>/maxmemory 256mb/' /etc/redis/redis.conf
sed -i 's/# maxmemory-policy noeviction/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf

systemctl restart redis-server
systemctl enable redis-server

WordPress cache optimization:

// wp-config.php additions dla caching
define('WP_CACHE', true);
define('WP_CACHE_KEY_SALT', 'yourdomain.com');

// Redis object cache (if using Redis)
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_TIMEOUT', 1);
define('WP_REDIS_READ_TIMEOUT', 1);
define('WP_REDIS_DATABASE', 0);

Nginx page caching:

# FastCGI cache configuration
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=wordpress:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

server {
    # FastCGI cache settings
    location ~ \.php$ {
        fastcgi_cache wordpress;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        
        # Add cache status header
        add_header X-Cache-Status $upstream_cache_status;
        
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        include fastcgi_params;
    }
}

Image optimization

Automatic image compression:

# Install image optimization tools
apt install -y jpegoptim optipng pngquant webp

# Optimize existing images
find /var/www/yourdomain.com/public_html/wp-content/uploads/ -name "*.jpg" -exec jpegoptim --max=85 {} \;
find /var/www/yourdomain.com/public_html/wp-content/uploads/ -name "*.png" -exec optipng -o7 {} \;

# Convert to WebP format
find /var/www/yourdomain.com/public_html/wp-content/uploads/ -name "*.jpg" -exec sh -c 'cwebp -q 85 "$1" -o "${1%.jpg}.webp"' _ {} \;

WebP serving configuration:

# Serve WebP images when available
location ~* \.(jpe?g|png)$ {
    add_header Vary Accept;
    
    # Try WebP version first
    try_files $uri.webp $uri =404;
    
    # Set appropriate MIME type
    location ~* \.webp$ {
        add_header Content-Type image/webp;
    }
}

Database optimization

Query optimization:

-- Add indexes dla frequently queried columns
ALTER TABLE wp_posts ADD INDEX idx_post_status_date (post_status, post_date);
ALTER TABLE wp_postmeta ADD INDEX idx_meta_key_value (meta_key, meta_value(10));
ALTER TABLE wp_comments ADD INDEX idx_comment_approved_date (comment_approved, comment_date);

-- Optimize tables
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_comments, wp_commentmeta, wp_options;

-- Update table statistics
ANALYZE TABLE wp_posts, wp_postmeta, wp_comments, wp_options;

Database maintenance automation:

# Weekly database optimization script
#!/bin/bash
# db_maintenance.sh

DATABASE="wordpress_db"
USER="db_user"
PASSWORD="db_password"

# Optimize tables
mysql -u $USER -p$PASSWORD $DATABASE -e "
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_comments, wp_commentmeta, wp_options, wp_users, wp_usermeta;
"

# Clean spam comments
mysql -u $USER -p$PASSWORD $DATABASE -e "
DELETE FROM wp_comments WHERE comment_approved = 'spam' AND comment_date < DATE_SUB(NOW(), INTERVAL 30 DAY);
"

# Clean old revisions (keep last 3)
mysql -u $USER -p$PASSWORD $DATABASE -e "
DELETE FROM wp_posts 
WHERE post_type = 'revision' 
AND post_date < DATE_SUB(NOW(), INTERVAL 30 DAY)
AND ID NOT IN (
    SELECT * FROM (
        SELECT ID FROM wp_posts 
        WHERE post_type = 'revision' 
        ORDER BY post_date DESC 
        LIMIT 3
    ) AS temp
);
"

echo "Database maintenance completed at $(date)"

Security hardening

Enhanced firewall configuration:

# Advanced UFW rules
ufw --force reset
ufw default deny incoming
ufw default allow outgoing

# Allow essential services
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw allow 2222/tcp  # DirectAdmin (if used)

# Rate limiting dla SSH
ufw limit 22/tcp

# Allow specific IPs only dla admin access
ufw allow from YOUR_OFFICE_IP to any port 22

ufw --force enable

Fail2ban configuration:

# Install Fail2ban
apt install -y fail2ban

# Configure Fail2ban
cat > /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
ignoreip = 127.0.0.1/8 YOUR_OFFICE_IP

[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log

[nginx-http-auth]
enabled = true
port = 80,443
filter = nginx-http-auth
logpath = /var/log/nginx/error.log

[nginx-req-limit]
enabled = true
port = 80,443
filter = nginx-req-limit
logpath = /var/log/nginx/error.log
EOF

systemctl restart fail2ban
systemctl enable fail2ban

Troubleshooting {#troubleshooting}

Common post-migration issues

Issue 1: Website shows old content

Symptoms:

  • Visitors see old website version
  • Changes not visible
  • Mixed old/new content

Diagnosis:

# Check DNS propagation
dig @8.8.8.8 yourdomain.com
dig @1.1.1.1 yourdomain.com
nslookup yourdomain.com

# Check browser cache
# Hard refresh: Ctrl+F5 (Windows) / Cmd+Shift+R (Mac)

Solutions:

# Clear server-side cache
# Nginx cache
rm -rf /var/cache/nginx/*
systemctl reload nginx

# WordPress cache (if using cache plugin)
wp cache flush --path=/var/www/yourdomain.com/public_html/

# CDN cache purge (Cloudflare example)
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
     -H "Authorization: Bearer YOUR_API_TOKEN" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}'

Issue 2: Database connection errors

Symptoms:

  • “Error establishing database connection”
  • Website showing generic error pages
  • Admin panel inaccessible

Diagnosis:

# Test database connectivity
mysql -u dbuser -p -h localhost database_name

# Check MySQL service status
systemctl status mysql
journalctl -u mysql.service

# Verify database credentials
grep DB_ /var/www/yourdomain.com/public_html/wp-config.php

Solutions:

// Verify wp-config.php settings
define('DB_NAME', 'correct_database_name');
define('DB_USER', 'correct_username');
define('DB_PASSWORD', 'correct_password');
define('DB_HOST', 'localhost');

// Test database connection
<?php
$connection = mysqli_connect('localhost', 'dbuser', 'password', 'database_name');
if (!$connection) {
    die('Connection failed: ' . mysqli_connect_error());
}
echo 'Connected successfully';
mysqli_close($connection);
?>

Issue 3: Email not working

Symptoms:

  • Contact forms not sending emails
  • Email accounts not receiving mail
  • SMTP authentication failures

Diagnosis:

# Test mail server connectivity
telnet mail.yourdomain.com 25
telnet mail.yourdomain.com 587
telnet mail.yourdomain.com 993

# Check mail logs
tail -f /var/log/mail.log
tail -f /var/log/postfix/mail.log

# Test email sending
echo "Test email" | mail -s "Test Subject" test@gmail.com

Solutions:

# Verify MX records
dig MX yourdomain.com

# Check SPF record
dig TXT yourdomain.com | grep "v=spf1"

# Fix Postfix configuration (if using Postfix)
postconf -e 'myhostname = mail.yourdomain.com'
postconf -e 'mydomain = yourdomain.com'
systemctl restart postfix

# WordPress SMTP configuration
# Install WP Mail SMTP plugin
# Configure with server details:
# SMTP Host: mail.yourdomain.com
# SMTP Port: 587 (TLS) or 465 (SSL)
# Username: your-email@yourdomain.com
# Password: email account password

Issue 4: SSL certificate problems

Symptoms:

  • Browser SSL warnings
  • Mixed content errors
  • Certificate not trusted

Diagnosis:

# Check SSL certificate
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

# Verify certificate details
echo | openssl s_client -connect yourdomain.com:443 2>/dev/null | openssl x509 -noout -dates

# Check SSL configuration
curl -I https://yourdomain.com

Solutions:

# Regenerate Let's Encrypt certificate
certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Fix mixed content w WordPress
wp search-replace 'http://yourdomain.com' 'https://yourdomain.com' --path=/var/www/yourdomain.com/public_html/

# Add SSL redirect w .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Performance issues

Issue: Slow website performance

Diagnosis tools:

# Server resource check
htop
iostat -x 1
free -m
df -h

# Website speed test
curl -o /dev/null -s -w "Time: %{time_total}s\nDownload: %{speed_download} bytes/sec\n" https://yourdomain.com

# Database performance
mysql -e "SHOW FULL PROCESSLIST;"
mysql -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';"

Optimization steps:

# Enable OPcache
echo "opcache.enable=1" >> /etc/php/8.1/fpm/php.ini
systemctl restart php8.1-fpm

# Database optimization
mysql database_name -e "OPTIMIZE TABLE wp_posts, wp_options, wp_postmeta;"

# Clear unnecessary files
find /var/www/yourdomain.com/public_html/wp-content/uploads/ -name "*.tmp" -delete
find /var/www/yourdomain.com/public_html/ -name "*.log" -mtime +30 -delete

Security issues

Issue: Unauthorized access attempts

Detection:

# Monitor failed login attempts
grep "Failed password" /var/log/auth.log | tail -20
grep "authentication failure" /var/log/auth.log | tail -20

# Check for WordPress brute force attempts
grep "xmlrpc.php" /var/log/nginx/access.log | tail -20
grep "wp-login.php" /var/log/nginx/access.log | grep -v "200" | tail -20

Immediate response:

# Block suspicious IPs
ufw insert 1 deny from SUSPICIOUS_IP

# Change SSH port (if being targeted)
sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
systemctl restart ssh

# Install additional security
apt install -y fail2ban

# WordPress security hardening
# Change admin username
# Enable two-factor authentication  
# Limit login attempts
# Hide wp-admin from unauthorized access

Recovery procedures

Complete site recovery:

# If everything fails, restore from backup
# 1. Stop web services
systemctl stop nginx
systemctl stop mysql

# 2. Restore files
tar -xzf /backups/website_backup_latest.tar.gz -C /var/www/

# 3. Restore database
mysql database_name < /backups/database_backup_latest.sql

# 4. Fix permissions
chown -R www-data:www-data /var/www/yourdomain.com/
chmod -R 755 /var/www/yourdomain.com/
chmod 644 /var/www/yourdomain.com/public_html/wp-config.php

# 5. Restart services
systemctl start mysql
systemctl start nginx

# 6. Test functionality
curl -I https://yourdomain.com

Emergency contacts:

Migration team contacts:
- Technical Lead: +48 123 456 789
- VPS Provider Support: support@netrion.pl / +48 800 XXX XXX
- Domain Registrar: [contact details]
- DNS Provider: [contact details]

Escalation procedures:
1. Technical team (0-30 minutes)
2. Management notification (30-60 minutes)  
3. Customer communication (60-120 minutes)
4. External expert consultation (2+ hours)

Checklist migracji {#checklist}

Pre-migration checklist (2-4 weeks before)

Infrastructure preparation:

☐ VPS ordered and configured
☐ Control panel (DirectAdmin) installed
☐ SSL certificates obtained
☐ DNS TTL values lowered to 300 seconds
☐ Backup strategy implemented
☐ Monitoring tools configured
☐ Team roles and responsibilities assigned

Data audit and preparation:

☐ Complete inventory of current hosting
☐ File structure documented
☐ Database schema documented
☐ Email accounts listed
☐ DNS records documented
☐ External integrations identified
☐ Performance baseline established

Migration week checklist

5 days before migration:

☐ Final VPS configuration completed
☐ Staging environment setup
☐ Initial data transfer completed
☐ Testing environment validated
☐ Rollback procedures finalized
☐ Customer communication sent

2 days before migration:

☐ Incremental backup completed
☐ DNS propagation tools prepared
☐ Migration team briefed
☐ External stakeholders notified
☐ Emergency contact list updated
☐ Monitoring dashboards prepared

Day of migration:

☐ Team coordination call completed
☐ Final backup verification
☐ Maintenance mode activated
☐ Final data synchronization
☐ DNS records updated
☐ SSL certificates verified
☐ Functionality testing completed
☐ Performance validation done
☐ Maintenance mode disabled
☐ Post-migration monitoring activated

Post-migration checklist (First 48 hours)

Immediate verification (0-4 hours):

☐ Website accessibility confirmed
☐ Database connectivity verified
☐ Email functionality tested
☐ SSL certificates working
☐ Performance metrics within targets
☐ Error logs clean
☐ Analytics tracking verified
☐ Customer communication sent

Extended validation (4-24 hours):

☐ All website pages accessible
☐ Contact forms working
☐ E-commerce functionality (if applicable)
☐ User registration/login working
☐ Search functionality operational
☐ Admin panel accessible
☐ Plugin/theme functionality verified
☐ Mobile responsiveness confirmed

Business validation (24-48 hours):

☐ Sales/conversions tracking normal
☐ Email deliverability confirmed
☐ Customer support tickets normal
☐ SEO rankings stable
☐ External integrations working
☐ Backup systems operational
☐ Performance improvements confirmed
☐ Team satisfaction survey completed

Week 1 post-migration checklist

Performance monitoring:

☐ Daily performance reports reviewed
☐ Error rates within normal range
☐ User feedback collected and analyzed
☐ Core Web Vitals improved
☐ Conversion rates maintained/improved
☐ Search engine crawling normal
☐ External monitoring tools configured

Optimization and fine-tuning:

☐ Caching systems optimized
☐ Database queries tuned
☐ Images optimized
☐ CDN configuration refined
☐ Security hardening completed
☐ Backup procedures validated
☐ Documentation updated
☐ Team training completed

Month 1 post-migration checklist

Long-term validation:

☐ Month-over-month performance comparison
☐ SEO impact analysis
☐ Conversion rate analysis
☐ Customer satisfaction survey
☐ Technical debt assessment
☐ Cost analysis vs. previous hosting
☐ Lessons learned documentation
☐ Process improvement recommendations

Success metrics review:

Target achievements:
☐ Page load time: <2 seconds (vs previous 4.2s)
☐ Uptime: 99.9%+ 
☐ Conversion rate: maintained or improved
☐ Customer complaints: <5% increase during migration week
☐ SEO rankings: no significant drops
☐ Team efficiency: improved with better tools
☐ Total cost of ownership: justified by improvements

Podsumowanie

Migracja na VPS to strategiczna decyzja, która może znacząco wpłynąć na sukces Twojego projektu online. Przestrzegając tego szczegółowego przewodnika, zminimalizujesz ryzyko problemów i maksymalizujesz korzyści z przejścia na wydajniejsze środowisko hostingowe.

Kluczowe czynniki sukcesu:

  1. Dokładne planowanie – każdy etap migracji powinien być przemyślany
  2. Kompletne testowanie – weryfikacja funkcjonalności przed przełączeniem ruchu
  3. Właściwy timing – wybór optymalnego momentu na migrację
  4. Monitoring – ciągłe śledzenie wydajności po migracji
  5. Plan B – zawsze miej przygotowany plan rollback

Dlaczego warto wybrać Netrion.pl dla swojej migracji:

Wsparcie migracji – pomoc ekspertów podczas całego procesu ✅ Polska lokalizacja – optymalna wydajność dla polskich użytkowników ✅ Managed services – możliwość skupienia się na biznesie, nie na administracji ✅ 24/7 wsparcie – pomoc techniczna w języku polskim ✅ Nowoczesna infrastruktura – SSD/NVMe, najnowsze technologie ✅ Elastyczność – łatwe skalowanie wraz z rozwojem Twojego projektu

Gotowy na migrację?

Skontaktuj się z ekspertami Netrion.pl (biuro@netrion.pl) i otrzymaj bezpłatną konsultację dotyczącą migracji Twojej strony na VPS. Pomożemy zaplanować i przeprowadzić bezpieczną migrację bez przestojów i utraty danych.

Pamiętaj: Dobra migracja to inwestycja w przyszłość Twojego projektu. Nie oszczędzaj na jakości procesu – korzyści z wydajnego VPS zwrócą się wielokrotnie.

Dobry serwer to nie tylko wydajność

Sama moc obliczeniowa to dopiero początek. To, co naprawdę decyduje o sukcesie Twojego projektu, to prawidłowa konfiguracja, bezpieczeństwo i szybka reakcja w razie problemów.

Dlatego w Netrion nie zostawiamy Cię samemu z technikaliami — oferujemy pełną administrację serwera, w tym:


✅ Indywidualną konfigurację pod Twoje potrzeby
✅ Stałe monitorowanie serwera 24/7
✅ Reakcję na incydenty w czasie rzeczywistym

✅ Aktualizacje, optymalizacje i wsparcie aplikacyjne
✅ Kontakt z doświadczonymi administratorami, nie call center

Dzięki temu możesz się skupić na rozwoju biznesu, a my zajmiemy się resztą.

error: Content is protected !!
Netrion.pl – Profesjonalne serwery VPS i dedykowane
Przegląd prywatności

Ta strona korzysta z ciasteczek, aby zapewnić Ci najlepszą możliwą obsługę. Informacje o ciasteczkach są przechowywane w przeglądarce i wykonują funkcje takie jak rozpoznawanie Cię po powrocie na naszą stronę internetową i pomaganie naszemu zespołowi w zrozumieniu, które sekcje witryny są dla Ciebie najbardziej interesujące i przydatne.