Linux Server Optimization: Best Practices for Web Hosting
Optimizing Linux servers for web hosting environments requires a comprehensive approach that balances performance, security, and reliability. In this article, I’ll share proven techniques that have helped me maintain high-performing web hosting infrastructure.
Note: Always test configuration changes in a staging environment before applying them to production servers.
Performance Optimization
1. Kernel Parameter Tuning
One of the first steps in server optimization is tuning kernel parameters for web hosting workloads. Key parameters to adjust include:
- Network optimizations: Increase buffer sizes for better network performance
- File descriptor limits: Set appropriate limits for concurrent connections
- Memory management: Optimize swap usage and dirty page ratios
Here’s a sample configuration for /etc/sysctl.conf:
# Network optimizationsnet.core.rmem_max = 16777216net.core.wmem_max = 16777216net.ipv4.tcp_rmem = 4096 65536 16777216net.ipv4.tcp_wmem = 4096 65536 16777216
# File descriptor limitsfs.file-max = 2097152fs.nr_open = 2097152
# Memory managementvm.swappiness = 10vm.dirty_ratio = 15vm.dirty_background_ratio = 52. Web Server Configuration
For Apache servers, optimize the configuration based on your server’s resources:
| Parameter | Recommended Value | Purpose |
|---|---|---|
| ServerLimit | 16 | Maximum number of child processes |
| MaxRequestWorkers | 400 | Maximum simultaneous connections |
| ThreadsPerChild | 25 | Threads per child process |
| MaxConnectionsPerChild | 10000 | Restart workers after N requests |
Security Hardening
SSH Configuration
Secure SSH access with these recommended settings:
Use default port 22→ Change to non-standard port (e.g., 2222)- Disable root login
- Use key-based authentication only
- Set appropriate timeout values
- Limit authentication attempts
Example /etc/ssh/sshd_config:
Port 2222Protocol 2PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesMaxAuthTries 3Warning: Make sure you have SSH key access configured before disabling password authentication!
Firewall Setup
Implement a robust firewall using UFW or iptables:
# Basic UFW configurationufw default deny incomingufw default allow outgoingufw allow 2222/tcp # SSHufw allow 80/tcp # HTTPufw allow 443/tcp # HTTPSufw enableMonitoring and Alerting
System Monitoring Checklist
Track these key metrics for optimal performance:
- CPU usage monitoring
- Memory utilization tracking
- Disk space monitoring
- Network traffic analysis
- Service status checks
- Log file size monitoring
- SSL certificate expiration alerts
Log Management
Implement centralized log management with proper rotation:
Click to see logrotate configuration example
/var/log/apache2/*.log { daily missingok rotate 52 compress delaycompress notifempty create 640 www-data adm postrotate /etc/init.d/apache2 reload > /dev/null endscript}Automation Scripts
Automated Backups
Create automated backup scripts for:
- Website files backup - Daily incremental, weekly full
- Database backup and restoration - Hourly transaction logs
- Configuration files backup - After any change
- Automated cleanup of old backups (30-day retention)
Sample backup script:
#!/bin/bash# backup.sh - Automated backup script
DATE=$(date +%Y%m%d_%H%M%S)BACKUP_DIR="/backups"SITES_DIR="/var/www"
# Create backup directorymkdir -p $BACKUP_DIR/$DATE
# Backup websitestar -czf $BACKUP_DIR/$DATE/websites.tar.gz $SITES_DIR
# Backup databasesmysqldump --all-databases > $BACKUP_DIR/$DATE/databases.sql
# Clean old backups (keep 30 days)find $BACKUP_DIR -type d -mtime +30 -exec rm -rf {} \;
echo "✓ Backup completed: $DATE"Health Check Script
Monitor server health with automated checks:
#!/bin/bash
# Check disk spaceDISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')if [ $DISK_USAGE -gt 80 ]; then echo "⚠ Disk usage is ${DISK_USAGE}%" | mail -s "Disk Space Alert" $ALERT_EMAILfiPerformance Testing
Load Testing Tools
Use these tools to validate your optimizations:
| Tool | Purpose | Command Example |
|---|---|---|
| Apache Bench | HTTP load testing | ab -n 1000 -c 10 http://example.com/ |
| wrk | Modern HTTP benchmarking | wrk -t12 -c400 -d30s http://example.com/ |
| siege | Stress testing | siege -c 100 -t 60s http://example.com/ |
Monitoring Tools
Implement real-time monitoring:
htop- Process monitoring with color outputiotop- I/O usage by processiftop- Network bandwidth monitoringnethogs- Network usage per process
Conclusion
Server optimization is an ongoing process that requires regular monitoring and adjustment. By implementing these best practices, you can significantly improve your server’s:
- Performance metrics
- Security posture
- System reliability
- Resource utilization
Remember to:
Test changes in staging first → Monitor metrics → Document modifications → Review regularly
The key to successful server optimization is understanding your specific workload requirements and continuously monitoring performance metrics to ensure your optimizations are effective.
Written by Dzubayyan Ahmad | System Administrator & SRE