BLOG POSTS
    MangoHost Blog / How to Install LAMP Stack on Ubuntu – Complete Setup
How to Install LAMP Stack on Ubuntu – Complete Setup

How to Install LAMP Stack on Ubuntu – Complete Setup

The LAMP stack (Linux, Apache, MySQL, PHP) remains one of the most popular web development environments for building dynamic websites and applications. This powerful combination provides everything you need to run PHP-based applications like WordPress, Laravel, or custom web projects. In this comprehensive guide, you’ll learn how to install and configure each component of the LAMP stack on Ubuntu, troubleshoot common issues, and optimize your setup for production use.

Understanding the LAMP Stack Components

Before diving into installation, let’s break down what each component brings to the table:

  • Linux (Ubuntu): The operating system that provides the foundation
  • Apache: The web server that handles HTTP requests and serves web pages
  • MySQL: The relational database management system for data storage
  • PHP: The server-side scripting language for dynamic content generation
Component Default Port Configuration Location Log Location
Apache 80 (HTTP), 443 (HTTPS) /etc/apache2/ /var/log/apache2/
MySQL 3306 /etc/mysql/ /var/log/mysql/
PHP N/A /etc/php/ Varies by configuration

Prerequisites and System Preparation

You’ll need a fresh Ubuntu server (18.04 LTS or newer recommended) with root or sudo access. Whether you’re running this on a local virtual machine or a cloud server, ensure you have at least 1GB of RAM and 10GB of storage space.

First, update your system packages:

sudo apt update && sudo apt upgrade -y

Step 1: Installing Apache Web Server

Apache is the most widely used web server, powering about 40% of all websites. Install it using Ubuntu’s package manager:

sudo apt install apache2 -y

Enable Apache to start automatically on boot and start the service:

sudo systemctl enable apache2
sudo systemctl start apache2

Verify the installation by checking the service status:

sudo systemctl status apache2

You should see output indicating that Apache is active and running. Test by navigating to your server’s IP address in a web browser – you should see the Apache2 Ubuntu Default Page.

Configuring UFW Firewall

If you’re using Ubuntu’s UFW firewall, allow HTTP and HTTPS traffic:

sudo ufw allow 'Apache Full'

Step 2: Installing MySQL Database Server

MySQL handles data storage and retrieval for your applications. Install the MySQL server package:

sudo apt install mysql-server -y

Secure your MySQL installation by running the security script:

sudo mysql_secure_installation

This script will prompt you to:

  • Set up the validate password plugin (recommended for production)
  • Set a strong root password
  • Remove anonymous users
  • Disable remote root login
  • Remove the test database
  • Reload privilege tables

Test your MySQL installation:

sudo mysql -u root -p

You should be able to log in and see the MySQL prompt. Exit with exit;

Creating a Database User

For security reasons, create a dedicated database user instead of using root for applications:

sudo mysql -u root -p

CREATE USER 'webuser'@'localhost' IDENTIFIED BY 'secure_password_here';
GRANT ALL PRIVILEGES ON *.* TO 'webuser'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;

Step 3: Installing PHP

PHP processes server-side code and integrates with both Apache and MySQL. Install PHP along with commonly needed extensions:

sudo apt install php libapache2-mod-php php-mysql php-cli php-curl php-json php-cgi php-xml php-mbstring php-zip -y

This command installs:

  • php: Core PHP interpreter
  • libapache2-mod-php: Apache module for PHP
  • php-mysql: MySQL connectivity
  • php-cli: Command-line interface
  • php-curl, php-json, php-xml, php-mbstring, php-zip: Common extensions

Configure Apache to prioritize PHP files over HTML by editing the dir.conf file:

sudo nano /etc/apache2/mods-enabled/dir.conf

Move index.php to the front of the list:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Restart Apache to apply changes:

sudo systemctl restart apache2

Step 4: Testing Your LAMP Stack

Create a PHP info file to verify all components are working together:

sudo nano /var/www/html/info.php

Add this content:

<?php
phpinfo();
?>

Visit http://your_server_ip/info.php in your browser. You should see a detailed PHP information page showing your PHP version, loaded extensions, and configuration details.

For security, remove this file after testing:

sudo rm /var/www/html/info.php

Testing Database Connectivity

Create a simple PHP script to test MySQL connectivity:

sudo nano /var/www/html/db_test.php

Add this code (replace credentials with your own):

<?php
$servername = "localhost";
$username = "webuser";
$password = "your_password";

try {
    $pdo = new PDO("mysql:host=$servername", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully to MySQL server";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Performance Optimization and Configuration

Apache Optimization

For better performance, consider these Apache tweaks:

sudo nano /etc/apache2/apache2.conf

Add these lines for basic optimization:

# Hide Apache version information
ServerTokens Prod
ServerSignature Off

# Optimize for moderate traffic
StartServers 2
MinSpareServers 6
MaxSpareServers 12
MaxRequestWorkers 100

PHP Configuration

Edit PHP settings for better performance and security:

sudo nano /etc/php/7.4/apache2/php.ini

Key settings to adjust:

memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
date.timezone = "America/New_York"

MySQL Optimization

Basic MySQL tuning for small to medium applications:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Add under [mysqld] section:

innodb_buffer_pool_size = 256M
query_cache_type = 1
query_cache_size = 16M
max_connections = 100

Restart services after configuration changes:

sudo systemctl restart apache2
sudo systemctl restart mysql

Common Issues and Troubleshooting

Apache Won’t Start

Check for configuration errors:

sudo apache2ctl configtest

View detailed error logs:

sudo tail -f /var/log/apache2/error.log

MySQL Access Denied

If you get authentication errors, try accessing MySQL as root:

sudo mysql

Then reset the root password:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new_password';
FLUSH PRIVILEGES;

PHP Not Executing

If PHP files download instead of executing:

sudo a2enmod php7.4
sudo systemctl restart apache2

Permission Issues

Set proper ownership for web files:

sudo chown -R www-data:www-data /var/www/html/
sudo chmod -R 755 /var/www/html/

Alternative Stack Comparisons

Stack Web Server Database Language Best For
LAMP Apache MySQL PHP Traditional web apps, WordPress
LEMP Nginx MySQL PHP High-traffic sites, better performance
MEAN Express MongoDB JavaScript Modern web applications, APIs
XAMPP Apache MySQL PHP Local development (Windows/Mac/Linux)

Real-World Use Cases and Applications

The LAMP stack powers numerous popular applications:

  • Content Management Systems: WordPress, Drupal, Joomla
  • E-commerce Platforms: Magento, OpenCart, PrestaShop
  • Custom Web Applications: Laravel, CodeIgniter, Symfony projects
  • Learning Management Systems: Moodle, Canvas
  • Forum Software: phpBB, vBulletin

Production Deployment Example

Here’s a typical workflow for deploying a Laravel application:

# Create virtual host
sudo nano /etc/apache2/sites-available/myapp.conf

<VirtualHost *:80>
    ServerName myapp.com
    DocumentRoot /var/www/myapp/public
    
    <Directory /var/www/myapp/public>
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/myapp_error.log
    CustomLog ${APACHE_LOG_DIR}/myapp_access.log combined
</VirtualHost>

# Enable site and rewrite module
sudo a2ensite myapp.conf
sudo a2enmod rewrite
sudo systemctl restart apache2

Security Best Practices

Implement these security measures for production environments:

  • Keep all components updated regularly
  • Use strong passwords and consider key-based authentication
  • Configure fail2ban to prevent brute force attacks
  • Enable SSL/TLS certificates (Let’s Encrypt is free)
  • Disable unnecessary Apache modules
  • Configure proper file permissions
  • Regular database backups
  • Use a Web Application Firewall (WAF)

Install and configure fail2ban for additional security:

sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Monitoring and Maintenance

Set up basic monitoring to keep your LAMP stack healthy:

# Check service status
sudo systemctl status apache2 mysql

# Monitor resource usage
htop
df -h
free -m

# Check logs for errors
sudo tail -f /var/log/apache2/error.log
sudo tail -f /var/log/mysql/error.log

Consider setting up automated backups for your databases:

#!/bin/bash
# Simple backup script
DATE=$(date +%Y%m%d_%H%M%S)
mysqldump -u root -p --all-databases > /backup/mysql_backup_$DATE.sql
gzip /backup/mysql_backup_$DATE.sql

Your LAMP stack is now ready for development and production use. Whether you’re hosting this on a VPS or dedicated servers, this setup provides a solid foundation for web applications. Remember to regularly update your components and monitor system performance as your applications grow.

For additional configuration options and advanced features, consult the official documentation: Apache Documentation, MySQL Documentation, and PHP Documentation.



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.

Leave a reply

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