VPS

Setting Up a LAMP Stack on VPS (Linux, Apache, MySQL, PHP) in 2025

Sonam Lama

Administrator

Introduction

Remember when setting up a web server felt like trying to assemble a motorcycle while blindfolded? Those days don’t have to be behind us, but they can be it if you know what you’re doing. Setting up a LAMP stack (Linux, Apache, MySQL, PHP) is still one of the most fundamental skills every web developer and business owner should master, especially if you’re running your own VPS.

At Nest Nepal, we’ve helped hundreds of businesses migrate from shared hosting to VPS, and the first thing they need is a solid LAMP stack setup. Whether you’re hosting a simple business website, running an e-commerce store, or managing multiple client sites, getting your LAMP stack right is crucial for performance, security, and peace of mind.

Today, we’re going to walk through setting up a modern, secure, and optimized LAMP stack on a VPS in 2025. This isn’t your grandfather’s web server setup; we’re talking about current best practices, security hardening, and performance optimization that will make your sites fly.

What Exactly Is a LAMP Stack and Why Does It Still Matter?

Before we dive into the technical details, let’s ensure we’re all on the same page. LAMP is an acronym that stands for:

  • Linux – The operating system
  • Apache – The web server
  • MySQL (or MariaDB) – The database
  • PHP – The programming language

Think of LAMP as the foundation of your digital house. Linux is the foundation you build on, Apache is the structure that holds everything together, MySQL is where you store all your valuable data, and PHP is the electricity that makes everything work.

Why LAMP Still Dominates in 2025

You might wonder, “Isn’t LAMP old technology?” Well, so is the wheel, but we’re still using it because it works brilliantly. Here’s why LAMP remains the go-to choice:

1. Proven Reliability: LAMP has been battle-tested by millions of websites over decades. It’s stable, predictable, and just works.

2. Universal Compatibility: Almost every web application, CMS, or framework supports LAMP. WordPress, Joomla, Drupal, custom PHP applications, they all love LAMP.

3. Cost-Effective: Everything in the LAMP stack is open-source and free. No licensing fees, no vendor lock-in.

4. Massive Community Support: Stuck with a problem? There’s probably a solution already documented somewhere, or thousands of developers ready to help.

5. Performance When Properly Configured: A well-tuned LAMP stack can handle massive traffic loads. Facebook started on LAMP, and many high-traffic sites still use it.

Choosing Your VPS: The Foundation Matters

Before we start installing anything, let’s talk about choosing the right VPS. Not all VPS providers are created equal, and your choice will affect everything we do next.

Minimum Recommendations for LAMP in 2025

ResourceMinimumRecommendedHigh-Traffic
RAM1GB2GB4GB+
CPU1 vCPU2 vCPU4+ vCPU
Storage20GB SSD40GB SSD100GB+ SSD
Bandwidth1TBUnlimitedUnlimited

Operating System Choice

For this guide, we’ll use Ubuntu 22.04 LTS (Long Term Support). Here’s why:

  • 5 years of security updates (until 2027)
  • Excellent hardware compatibility
  • Massive community and documentation
  • APT package manager makes installations easy
  • Regular, predictable update cycles

Choices that work great:

  • CentOS Stream or Rocky Linux (RHEL-based)
  • Debian 12 (super stable)
  • AlmaLinux (CentOS replacement)

Initial Server Setup: Security First

This is crucial; never skip server hardening. I’ve seen too many businesses get hacked because they skipped these basic security steps.

Step 1: Initial Connection and Updates

First, connect to your fresh VPS:
# Connect via SSH (replace with your server IP)
ssh root@your-server-ip

# Update the system completely
apt update && apt upgrade -y

# Install essential packages
apt install -y curl wget vim ufw fail2ban htop

Step 2: Create a Non-Root User

Never run services as root. Create a regular user with sudo privileges:

# Create new user (replace 'nepal' with your preferred username)
adduser nepal

# Add user to sudo group
usermod -aG sudo nepal

# Test sudo access
su - nepal
sudo whoami  # Should return 'root'

Step 3: Configure SSH Security

# Edit SSH configuration
sudo vim /etc/ssh/sshd_config

# Make these changes:
# Port 2222                    # Change from default port 22
# PermitRootLogin no          # Disable root login
# PasswordAuthentication no   # Use keys only (after setting up keys)
# MaxAuthTries 3              # Limit login attempts

# Restart SSH service
sudo systemctl restart ssh

Important: Set up SSH keys before disabling password authentication!

Step 4: Configure Firewall

# Configure UFW (Uncomplicated Firewall)
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH on your custom port
sudo ufw allow 2222

# Allow HTTP and HTTPS
sudo ufw allow 80
sudo ufw allow 443

# Enable firewall
sudo ufw enable

# Check status
sudo ufw status

Installing Linux Components

Your VPS likely came with Linux already installed, but let’s make sure we have everything optimized.

System Optimization

# Install additional useful packages
sudo apt install -y software-properties-common apt-transport-https ca-certificates

# Configure timezone (important for logs and cron jobs)
sudo timedatectl set-timezone Asia/Kathmandu

# Verify timezone setting
timedatectl

# Configure automatic security updates
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Memory and Swap Configuration

# Check current memory
free -h

# Create swap file (recommended: 2x RAM for servers with <2GB RAM)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Make swap permanent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Optimize swap usage (optional)
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Installing Apache: Your Web Server Foundation

Apache remains the most popular web server globally, and for good reason. It’s flexible, well-documented, and handles almost any scenario you can throw at it.

Step 1: Install Apache

# Install Apache
sudo apt install -y apache2

# Start and enable Apache
sudo systemctl start apache2
sudo systemctl enable apache2

# Check status
sudo systemctl status apache2

# Test installation
curl http://localhost

You should see the Apache default page HTML.

Step 2: Configure Apache Security

# Edit main Apache configuration
sudo vim /etc/apache2/conf-enabled/security.conf

# Add or modify these settings:
ServerTokens Prod
ServerSignature Off

# Edit Apache main config
sudo vim /etc/apache2/apache2.conf

# Add these security headers (at the end):
# Hide Apache version
ServerTokens Prod
ServerSignature Off

# Prevent access to .htaccess files
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

Step 3: Enable Essential Apache Modules

# Enable important modules
sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
sudo a2enmod deflate
sudo a2enmod expires

# Restart Apache to load modules
sudo systemctl restart apache2

Step 4: Create Your First Virtual Host

# Create directory for your website
sudo mkdir -p /var/www/mysite.com

# Set proper ownership
sudo chown -R $USER:www-data /var/www/mysite.com

# Create a simple index file
echo "<h1>Welcome to My Site!</h1>" | sudo tee /var/www/mysite.com/index.html

# Create virtual host configuration
sudo vim /etc/apache2/sites-available/mysite.com.conf

Add this configuration:
<VirtualHost *:80>
    ServerAdmin admin@mysite.com
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot /var/www/mysite.com
    
    <Directory /var/www/mysite.com>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/mysite.com_error.log
    CustomLog ${APACHE_LOG_DIR}/mysite.com_access.log combined
</VirtualHost>

# Enable the site
sudo a2ensite mysite.com.conf

# Disable default site (optional)
sudo a2dissite 000-default.conf

# Test configuration
sudo apache2ctl configtest

# Reload Apache
sudo systemctl reload apache2

Installing MySQL: Your Data Powerhouse

MySQL is where all your website data lives. In 2025, we have some great options, but let’s go with MariaDB, it’s MySQL-compatible but with better performance and features.

Step 1: Install MariaDB

# Install MariaDB server
sudo apt install -y mariadb-server mariadb-client

# Start and enable MariaDB
sudo systemctl start mariadb
sudo systemctl enable mariadb

# Check status
sudo systemctl status mariadb

Step 2: Secure MariaDB Installation

This is critical – never skip this step:

# Run security script
sudo mysql_secure_installation

Answer the prompts like this:

  • Set root password: Yes (choose a strong password)
  • Remove anonymous users: Yes
  • Disallow root login remotely: Yes
  • Remove test database: Yes
  • Reload privilege tables: Yes

Step 3: Configure MariaDB for Performance

# Edit MariaDB configuration
sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf

Add these optimizations under [mysqld]:
# Performance tuning for small to medium sites
innodb_buffer_pool_size = 128M
innodb_log_file_size = 32M
innodb_file_per_table = 1
innodb_flush_method = O_DIRECT

# Query cache (helps with read-heavy sites)
query_cache_type = 1
query_cache_size = 16M
query_cache_limit = 1M

# Connection settings
max_connections = 50
thread_cache_size = 8

# Binary logging (important for backups)
log-bin = mysql-bin
expire_logs_days = 7

# Restart MariaDB to apply changes
sudo systemctl restart mariadb

Step 4: Create a Database and User

# Connect to MariaDB as root
sudo mysql -u root -p

# Create a database for your website
CREATE DATABASE mysite_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Create a user for your website
CREATE USER 'mysite_user'@'localhost' IDENTIFIED BY 'strong_password_here';

# Grant privileges
GRANT ALL PRIVILEGES ON mysite_db.* TO 'mysite_user'@'localhost';

# Refresh privileges
FLUSH PRIVILEGES;

# Exit MySQL
EXIT;

Step 5: Test Database Connection

# Test connection with new user
mysql -u mysite_user -p mysite_db

# Run a test query
SHOW DATABASES;
EXIT;

Installing PHP: Bringing Your Sites to Life

PHP powers over 70% of the web, including WordPress, and in 2025, PHP 8.3 is the sweet spot for performance and compatibility.

Step 1: Add PHP Repository and Install

# Add Ondřej's PHP repository (most up-to-date PHP versions)
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

# Install PHP 8.3 and essential modules
sudo apt install -y php8.3 php8.3-fpm php8.3-mysql php8.3-common php8.3-cli

Step 2: Install Essential PHP Extensions

# Install commonly needed PHP extensions
sudo apt install -y php8.3-curl php8.3-gd php8.3-intl php8.3-mbstring \
php8.3-soap php8.3-xml php8.3-xmlrpc php8.3-zip php8.3-bcmath \
php8.3-imagick php8.3-redis php8.3-memcached

# For Apache integration
sudo apt install -y libapache2-mod-php8.3

Step 3: Configure PHP for Production

# Edit PHP configuration
sudo vim /etc/php/8.3/apache2/php.ini

Find and modify these settings:
; Security settings
expose_php = Off
allow_url_fopen = Off
allow_url_include = Off

; Performance settings
memory_limit = 256M
max_execution_time = 300
max_input_time = 300
post_max_size = 32M
upload_max_filesize = 32M
max_file_uploads = 20

; Session security
session.cookie_httponly = 1
session.use_strict_mode = 1
session.cookie_secure = 1

; Timezone
date.timezone = "Asia/Kathmandu"

; Error reporting (disable in production)
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

Step 4: Configure PHP-FPM (Recommended)

PHP-FPM provides better performance and resource management:

# Start and enable PHP-FPM
sudo systemctl start php8.3-fpm
sudo systemctl enable php8.3-fpm

# Configure PHP-FPM pool
sudo vim /etc/php/8.3/fpm/pool.d/www.conf

Key settings to modify:
; Process management
pm = dynamic
pm.max_children = 20
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm.max_requests = 500

; Security
security.limit_extensions = .php

; Performance monitoring
pm.status_path = /fpm-status
ping.path = /fpm-ping

Step 5: Enable Apache PHP-FPM Module

# Enable required modules
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.3-fpm

# Restart services
sudo systemctl restart apache2
sudo systemctl restart php8.3-fpm

Step 6: Test PHP Installation

# Create a PHP info file
echo "<?php phpinfo(); ?>" | sudo tee /var/www/mysite.com/info.php

# Test PHP processing
curl http://your-server-ip/info.php

Important: Remove the info.php file after testing for security!

Testing Your Complete LAMP Stack

Let’s create a simple test to ensure everything works together:

Create a Database Connection Test

# Create a comprehensive test file
sudo vim /var/www/mysite.com/test.php

Add this content:
<?php
// Database connection test
$servername = "localhost";
$username = "mysite_user";
$password = "strong_password_here";
$dbname = "mysite_db";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<h2>✅ Database Connection: SUCCESS</h2>";
    
    // Test query
    $stmt = $pdo->query("SELECT VERSION() as version");
    $version = $stmt->fetch();
    echo "<p>MySQL Version: " . $version['version'] . "</p>";
    
} catch(PDOException $e) {
    echo "<h2>❌ Database Connection: FAILED</h2>";
    echo "<p>Error: " . $e->getMessage() . "</p>";
}

// PHP information
echo "<h2>✅ PHP Working</h2>";
echo "<p>PHP Version: " . phpversion() . "</p>";
echo "<p>Server Time: " . date('Y-m-d H:i:s') . "</p>";

// Apache information  
echo "<h2>✅ Apache Working</h2>";
echo "<p>Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "</p>";
echo "<p>Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "</p>";

// Test file operations
$testFile = '/tmp/lamp_test.txt';
if (file_put_contents($testFile, 'LAMP Stack Test')) {
    echo "<h2>✅ File System: Working</h2>";
    unlink($testFile);
} else {
    echo "<h2>❌ File System: Issues detected</h2>";
}

echo "<h2>🎉 LAMP Stack is Ready!</h2>";
?>

Visit http://your-server-ip/test.php to see the results.

Performance Optimization

Now that everything’s working, let’s make it fast.

Apache Performance Tuning

# Edit Apache main config
sudo vim /etc/apache2/apache2.conf

Add these optimizations:
# Performance settings
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15

# Enable compression
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>

# Enable caching
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/ico "access plus 1 year"
</IfModule>

MySQL/MariaDB Performance Tuning

# Install MySQLTuner for recommendations
sudo apt install -y mysqltuner

# Run tuner after your site has been running for a while
sudo mysqltuner

Enable OPcache for PHP

# Edit PHP configuration
sudo vim /etc/php/8.3/apache2/php.ini

Add these OPcache settings:
; OPcache settings
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

Security Hardening

Install and Configure ModSecurity

# Install ModSecurity
sudo apt install -y libapache2-mod-security2

# Enable module
sudo a2enmod security2

# Download OWASP Core Rule Set
cd /etc/modsecurity
sudo git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git
sudo mv owasp-modsecurity-crs/crs-setup.conf.example owasp-modsecurity-crs/crs-setup.conf

# Configure ModSecurity
sudo vim /etc/apache2/mods-enabled/security2.conf

Add this configuration:
<IfModule security2_module>
    SecRuleEngine On
    SecRequestBodyAccess On
    SecResponseBodyAccess On
    SecResponseBodyMimeType text/plain text/html text/xml
    SecDataDir /tmp/
    Include /etc/modsecurity/owasp-modsecurity-crs/crs-setup.conf
    Include /etc/modsecurity/owasp-modsecurity-crs/rules/*.conf
</IfModule>

Set Up Automatic Backups

# Create backup script
sudo vim /usr/local/bin/lamp-backup.sh

#!/bin/bash
# LAMP Stack Backup Script

BACKUP_DIR="/backups"
DATE=$(date +%Y%m%d_%H%M%S)
DB_USER="root"
DB_PASS="your_root_password"

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup databases
mysqldump -u $DB_USER -p$DB_PASS --all-databases > $BACKUP_DIR/all_databases_$DATE.sql

# Backup web files
tar -czf $BACKUP_DIR/webfiles_$DATE.tar.gz /var/www/

# Backup Apache configuration
tar -czf $BACKUP_DIR/apache_config_$DATE.tar.gz /etc/apache2/

# Clean old backups (keep last 7 days)
find $BACKUP_DIR -type f -mtime +7 -delete

echo "Backup completed: $DATE"

# Make script executable
sudo chmod +x /usr/local/bin/lamp-backup.sh

# Add to crontab (daily at 2 AM)
echo "0 2 * * * /usr/local/bin/lamp-backup.sh" | sudo crontab -

Installing SSL Certificates with Let’s Encrypt

Never run a website without HTTPS in 2025. Let’s Encrypt makes it free and automatic.

Install Certbot

# Install snapd
sudo apt install -y snapd

# Install certbot via snap
sudo snap install --classic certbot

# Create symlink
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Get an SSL Certificate

# Get certificate for your domain
sudo certbot --apache -d mysite.com -d www.mysite.com

# Test automatic renewal
sudo certbot renew --dry-run

Certbot automatically configures Apache for HTTPS and sets up auto-renewal.

Monitoring and Maintenance

Install System Monitoring

# Install htop for process monitoring
sudo apt install -y htop iotop nethogs

# Install log analysis tools
sudo apt install -y logwatch goaccess

# Configure logwatch for daily reports
sudo vim /etc/cron.daily/00logwatch

Set Up Log Rotation

# Configure logrotate for Apache logs
sudo vim /etc/logrotate.d/apache2

/var/log/apache2/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /etc/init.d/apache2 reload > /dev/null
    endscript
}

Troubleshooting Common Issues

Apache Won’t Start

# Check for configuration errors
sudo apache2ctl configtest

# Check detailed error logs
sudo tail -f /var/log/apache2/error.log

# Check if port is already in use
sudo netstat -tulpn | grep :80

MySQL Connection Issues

# Check MySQL status
sudo systemctl status mariadb

# Check MySQL error logs
sudo tail -f /var/log/mysql/error.log

# Test MySQL connection
mysql -u root -p -e "SELECT 1"

PHP Not Processing

# Check PHP-FPM status
sudo systemctl status php8.3-fpm

# Check PHP-FPM error logs
sudo tail -f /var/log/php8.3-fpm.log

# Verify Apache PHP module
apache2ctl -M | grep php

High Memory Usage

# Check memory usage
free -h
sudo htop

# Check which processes are using most memory
ps aux --sort=-%mem | head -10

# Optimize MySQL memory usage
sudo mysqltuner

Scaling Your LAMP Stack

Adding Multiple Sites

# Create new site structure
sudo mkdir -p /var/www/site2.com
sudo chown -R $USER:www-data /var/www/site2.com

# Create virtual host
sudo vim /etc/apache2/sites-available/site2.com.conf

# Enable site
sudo a2ensite site2.com.conf
sudo systemctl reload apache2

Load Balancing with Multiple Servers

For high-traffic scenarios, consider:

  • nginx as a reverse proxy in front of Apache
  • Database replication for read scaling
  • Redis/Memcached for session storage
  • CDN integration for static assets

Performance Monitoring

# Install monitoring tools
sudo apt install -y netdata

# Access monitoring dashboard
# Visit: http://your-server:19999

2025 Best Practices Summary

  1. Always use HTTPS – No exceptions
  2. Regular security updates – Set up automatic updates
  3. Monitor performance – Use tools like netdata or New Relic
  4. Backup everything – Database, files, and configurations
  5. Use PHP-FPM – Better performance than mod_php
  6. Enable OPcache – Significant PHP performance boost
  7. Configure firewalls – UFW + fail2ban minimum
  8. Log monitoring – Set up alerts for errors
  9. Use strong passwords – For all accounts and databases
  10. Regular maintenance – Updates, cleanup, optimization

Conclusion: Your LAMP Stack Journey

LAMP

Congratulations! You’ve just built a production-ready LAMP stack that can power everything from a simple business website to a complex web application. This isn’t just any LAMP stack – this is a 2025-optimized, secure, and performance-tuned foundation that can grow with your needs.

What you’ve accomplished here puts you in the top tier of web developers and system administrators. Many agencies and freelancers in Nepal still struggle with proper server setup, but you now have the skills to deploy and manage professional-grade web hosting infrastructure.

The LAMP stack you’ve built today includes:

  • Security hardening that protects against common attacks
  • Performance optimization that can handle significant traffic
  • Monitoring and backup systems for reliable operations
  • SSL encryption for user trust and SEO benefits
  • Scalable architecture ready for growth

Remember, this is a foundation, not a destination. As your sites grow and your needs evolve, you can add caching layers (Redis, Memcached), implement load balancing, set up database clustering, or even migrate to cloud-native architectures.

But for now, you have something powerful: a solid, secure, fast web server that you understand inside and out. That’s invaluable knowledge in today’s digital economy, whether you’re building sites for local businesses in Kathmandu, serving international clients, or launching the next big Nepali startup.

Keep learning, keep optimizing, and most importantly, keep building amazing things on the foundation you’ve created today. The Nepal tech scene is growing rapidly, and skilled system administrators who truly understand their infrastructure are in high demand.

Your LAMP stack is ready. Now go build something awesome on it.

Need help with advanced LAMP stack configurations, performance tuning, or scaling to handle high traffic? The team at Nest Nepal has years of experience optimizing web servers for businesses of all sizes. Whether you’re launching your first VPS or managing multiple production servers, we’re here to help you succeed.

Leave a Reply

Your email address will not be published. Required fields are marked *