
How to Install Linux Apache MySQL PHP (LAMP) Stack on Ubuntu 24
The LAMP stack (Linux, Apache, MySQL, PHP) remains one of the most popular server environments for web development, powering everything from personal blogs to enterprise applications. Installing LAMP on Ubuntu 24 gives developers and system administrators a robust, open-source foundation for hosting dynamic websites and web applications. This guide will walk you through the complete installation process, covering each component in detail, troubleshooting common issues, and sharing optimization tips that’ll save you headaches down the road.
Understanding the LAMP Stack Components
Before diving into the installation, let’s break down what each component brings to the table. The LAMP stack works as a cohesive unit where each layer handles specific responsibilities:
- Linux (Ubuntu 24) – The operating system foundation providing security, process management, and hardware abstraction
- Apache – The web server handling HTTP requests, serving static files, and routing dynamic content to PHP
- MySQL – The relational database management system storing and retrieving application data
- PHP – The server-side scripting language processing dynamic content and database interactions
The beauty of LAMP lies in its proven stability and extensive community support. Unlike newer stacks like MEAN or Django, LAMP has decades of battle-tested deployment scenarios and extensive documentation for virtually any use case you’ll encounter.
Prerequisites and System Preparation
Before starting the installation, ensure your Ubuntu 24 system meets the basic requirements. You’ll need root or sudo access, at least 1GB of RAM (2GB recommended), and about 5GB of free disk space for a basic setup.
First, update your package repository and upgrade existing packages:
sudo apt update && sudo apt upgrade -y
Install essential build tools and dependencies that you’ll likely need later:
sudo apt install curl wget software-properties-common apt-transport-https -y
Installing Apache Web Server
Apache remains the most widely deployed web server, handling about 25% of all websites globally. Its modular architecture and extensive configuration options make it ideal for both development and production environments.
Install Apache using Ubuntu’s package manager:
sudo apt install apache2 -y
Enable and start the Apache service:
sudo systemctl enable apache2
sudo systemctl start apache2
Verify Apache is running correctly:
sudo systemctl status apache2
Test your installation by opening a browser and navigating to http://localhost
or your server’s IP address. You should see the Apache2 Ubuntu Default Page.
Configure the firewall to allow HTTP and HTTPS traffic:
sudo ufw allow 'Apache Full'
Apache Configuration Essentials
Apache configuration files are located in /etc/apache2/
. The main configuration file is apache2.conf
, but you’ll typically work with virtual host files in /etc/apache2/sites-available/
.
Enable useful Apache modules:
sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
The rewrite
module is essential for URL rewriting (crucial for most modern web applications), ssl
enables HTTPS support, and headers
allows header manipulation for security and caching.
Installing MySQL Database Server
MySQL continues to dominate the relational database landscape, especially in web development. For Ubuntu 24, you’ll get MySQL 8.0, which includes significant performance improvements and new features like JSON support and improved security.
Install MySQL server:
sudo apt install mysql-server -y
Start and enable MySQL service:
sudo systemctl enable mysql
sudo systemctl start mysql
Run the security installation script to improve MySQL’s default security:
sudo mysql_secure_installation
This script will prompt you through several security-related questions:
- Setup password validation plugin (recommended for production)
- Set root password (use a strong password)
- Remove anonymous users (yes)
- Disallow root login remotely (yes for security)
- Remove test database (yes)
- Reload privilege tables (yes)
MySQL Initial Configuration
Connect to MySQL as root:
sudo mysql -u root -p
Create a database and user for your applications:
CREATE DATABASE webapp_db;
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'secure_password_here';
GRANT ALL PRIVILEGES ON webapp_db.* TO 'webapp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
This approach follows the principle of least privilege – your applications shouldn’t use the root MySQL user.
Installing PHP and Essential Modules
Ubuntu 24 includes PHP 8.3 by default, which offers significant performance improvements over previous versions, including JIT compilation and better type system support.
Install PHP and commonly needed modules:
sudo apt install php libapache2-mod-php php-mysql php-curl php-gd php-mbstring php-xml php-zip php-json php-cli -y
Here’s what each module provides:
Module | Purpose | Common Use Cases |
---|---|---|
php-mysql | MySQL database connectivity | Database operations, PDO connections |
php-curl | HTTP client functionality | API calls, web scraping, external service integration |
php-gd | Image processing | Thumbnail generation, image manipulation, captcha |
php-mbstring | Multi-byte string handling | UTF-8 support, internationalization |
php-xml | XML parsing and generation | RSS feeds, SOAP APIs, configuration files |
php-zip | Archive file handling | File compression, backup systems, package management |
Restart Apache to load the PHP module:
sudo systemctl restart apache2
PHP Configuration Optimization
Edit the PHP configuration file to optimize for your use case:
sudo nano /etc/php/8.3/apache2/php.ini
Key settings to consider adjusting:
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
max_input_vars = 3000
These settings accommodate larger file uploads and longer-running scripts, which are common requirements for modern web applications.
Testing Your LAMP Installation
Create a PHP info file to verify everything is working correctly:
sudo nano /var/www/html/info.php
Add the following content:
<?php
phpinfo();
?>
Visit http://localhost/info.php
in your browser. You should see a detailed PHP configuration page showing all loaded modules and settings.
Create a more comprehensive test that includes database connectivity:
sudo nano /var/www/html/test.php
<?php
echo "<h1>LAMP Stack Test</h1>";
// Test PHP
echo "<h2>PHP Version: " . phpversion() . "</h2>";
// Test MySQL connection
$servername = "localhost";
$username = "webapp_user";
$password = "secure_password_here";
$dbname = "webapp_db";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<p style='color: green;'>Database connection: SUCCESS</p>";
} catch(PDOException $e) {
echo "<p style='color: red;'>Database connection failed: " . $e->getMessage() . "</p>";
}
// Test Apache modules
$modules = apache_get_modules();
echo "<h3>Apache Modules:</h3><ul>";
foreach(['mod_rewrite', 'mod_ssl', 'mod_headers'] as $mod) {
$status = in_array($mod, $modules) ? "β" : "β";
echo "<li>$mod: $status</li>";
}
echo "</ul>";
?>
Remember to delete these test files once you’ve verified everything works:
sudo rm /var/www/html/info.php /var/www/html/test.php
Common Issues and Troubleshooting
Even with a straightforward installation, you might encounter some common issues. Here are the most frequent problems and their solutions:
Apache Won’t Start
Check for configuration errors:
sudo apache2ctl configtest
View detailed error logs:
sudo journalctl -u apache2.service
Common causes include port conflicts (something else using port 80) or syntax errors in configuration files.
PHP Not Processing
If PHP files are downloading instead of executing, check if the PHP module is enabled:
sudo a2enmod php8.3
sudo systemctl restart apache2
Verify PHP is listed in Apache modules:
apache2ctl -M | grep php
MySQL Connection Issues
Check if MySQL is running:
sudo systemctl status mysql
Test connection manually:
mysql -u webapp_user -p -h localhost webapp_db
Common issues include incorrect credentials, missing user privileges, or the MySQL server not binding to localhost properly.
Permission Problems
Web files need proper ownership and permissions:
sudo chown -R www-data:www-data /var/www/html/
sudo chmod -R 755 /var/www/html/
For files that need write access (uploads, cache), use 775:
sudo chmod -R 775 /var/www/html/uploads/
Performance Optimization and Best Practices
A basic LAMP installation works fine for development, but production environments need additional optimization.
Apache Performance Tuning
Configure Apache’s Multi-Processing Module (MPM) for better performance:
sudo nano /etc/apache2/mods-available/mpm_prefork.conf
<IfModule mpm_prefork_module>
StartServers 4
MinSpareServers 20
MaxSpareServers 40
MaxRequestWorkers 200
MaxConnectionsPerChild 4500
</IfModule>
Enable compression and caching:
sudo a2enmod deflate
sudo a2enmod expires
sudo a2enmod cache
sudo systemctl restart apache2
MySQL Optimization
Edit MySQL configuration for better performance:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Add or modify these settings in the [mysqld] section:
[mysqld]
innodb_buffer_pool_size = 512M
query_cache_type = 1
query_cache_size = 64M
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
Restart MySQL after changes:
sudo systemctl restart mysql
PHP Performance Configuration
Install and configure PHP OPcache for significant performance gains:
sudo apt install php8.3-opcache -y
Configure OPcache in php.ini:
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=12
opcache.max_accelerated_files=4000
opcache.validate_timestamps=1
opcache.revalidate_freq=2
Security Hardening
Security should be a primary concern, especially for production deployments.
Apache Security
Hide Apache version information:
sudo nano /etc/apache2/conf-available/security.conf
Set these values:
ServerTokens Prod
ServerSignature Off
Enable the security configuration:
sudo a2enconf security
sudo systemctl restart apache2
MySQL Security
Disable the MySQL history file to prevent password leakage:
echo 'export MYSQL_HISTFILE=/dev/null' >> ~/.bashrc
Configure MySQL to use SSL connections:
sudo mysql -u root -p
ALTER USER 'webapp_user'@'localhost' REQUIRE SSL;
FLUSH PRIVILEGES;
PHP Security
Modify php.ini for better security:
expose_php = Off
allow_url_fopen = Off
allow_url_include = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
Real-World Use Cases and Applications
The LAMP stack powers an enormous variety of applications across different industries:
Content Management Systems
Popular CMS platforms like WordPress, Drupal, and Joomla are built specifically for LAMP environments. WordPress alone powers over 40% of all websites globally, making LAMP knowledge essential for web developers.
E-commerce Platforms
Major e-commerce solutions like Magento, OpenCart, and PrestaShop run on LAMP stacks. These platforms handle millions of transactions daily, demonstrating LAMP’s scalability when properly configured.
Custom Web Applications
Many businesses run custom-built applications on LAMP stacks, from inventory management systems to customer portals. The stack’s flexibility allows developers to build everything from simple CRUD applications to complex multi-tier systems.
Alternative Stack Comparisons
While LAMP remains popular, understanding alternatives helps make informed architectural decisions:
Stack | Components | Best For | Learning Curve |
---|---|---|---|
LAMP | Linux, Apache, MySQL, PHP | Traditional web apps, CMS, e-commerce | Low |
LEMP | Linux, Nginx, MySQL, PHP | High-traffic sites, better performance | Low-Medium |
MEAN | MongoDB, Express, Angular, Node.js | Single-page applications, real-time apps | Medium-High |
Django | Python, Django, PostgreSQL | Rapid development, data-heavy applications | Medium |
LAMP’s main advantages include extensive documentation, huge community support, and proven stability. However, for high-concurrency applications, LEMP (replacing Apache with Nginx) often provides better performance.
Integration with Modern Development Tools
Modern development workflows often integrate LAMP stacks with additional tools and services.
Version Control Integration
Set up automated deployments with Git hooks:
cd /var/www/html
sudo git init
sudo git remote add origin https://github.com/yourusername/your-project.git
sudo chown -R www-data:www-data .git/
Containerization
While this guide covers traditional installation, many developers now use Docker for LAMP stacks. This approach provides better environment consistency and easier deployment scaling.
Monitoring and Logging
Install log monitoring tools:
sudo apt install logwatch -y
Configure logrotate for Apache and MySQL logs to prevent disk space issues:
sudo nano /etc/logrotate.d/apache2
Next Steps and Advanced Topics
Once you have a basic LAMP stack running, consider these advanced topics:
- SSL/TLS Configuration – Set up Let’s Encrypt certificates for HTTPS
- Load Balancing – Configure multiple Apache instances behind a load balancer
- Database Replication – Set up MySQL master-slave replication for high availability
- Caching Solutions – Implement Redis or Memcached for application-level caching
- Monitoring – Deploy Nagios, Zabbix, or modern solutions like Prometheus for system monitoring
The Apache HTTP Server Documentation and MySQL Documentation provide comprehensive references for advanced configuration options.
Remember that while LAMP stacks are relatively straightforward to set up, mastering performance optimization, security hardening, and troubleshooting comes with experience. Start with simple projects and gradually work your way up to more complex deployments as you become comfortable with each component’s intricacies.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.