How to Set Up a LAMP Stack on Ubuntu


A LAMP stack (Linux, Apache, MySQL/MariaDB, and PHP) is essential for hosting websites and web applications. This guide explains how to install and configure a LAMP stack on Ubuntu.


1. Install Apache (The Web Server)

  1. Update Package Lists:
   sudo apt update
  1. Install Apache:
   sudo apt install apache2
  1. Verify Installation:
  • Open your browser and visit http://localhost.
  • You should see the Apache default page.
  1. Helpful Link:
    Learn more about configuring Apache at Apache’s official documentation.

2. Install MySQL or MariaDB (The Database Server)

  1. Install MySQL:
   sudo apt install mysql-server
  1. Secure MySQL Installation:
    Run the security script to set up a root password and remove unnecessary features:
   sudo mysql_secure_installation
  1. Check MySQL Service:
    Ensure it’s running:
   sudo systemctl status mysql
  1. Using MariaDB Instead:
    MariaDB is a popular MySQL fork. Install it using:
   sudo apt install mariadb-server
  1. Resource:
    For in-depth database security practices, check MySQL’s security guide.

3. Install PHP (The Server-Side Language)

  1. Install PHP and Required Modules:
   sudo apt install php libapache2-mod-php php-mysql
  1. Check PHP Version:
    Verify installation:
   php -v
  1. Test PHP:
  • Create a PHP info file:
    bash sudo nano /var/www/html/info.php
    Add this line:
    php <?php phpinfo(); ?>
  • Visit http://localhost/info.php in your browser.
  1. Helpful Link:
    Refer to the PHP documentation for advanced configurations.

4. Adjust Apache to Serve PHP Files

  1. Prioritize PHP Files:
    Edit Apache’s configuration file:
   sudo nano /etc/apache2/mods-enabled/dir.conf

Move index.php to the front of the list.

  1. Restart Apache:
   sudo systemctl restart apache2
  1. More Info:
    Apache-specific PHP integration tips can be found in this DigitalOcean guide.

5. Configure Firewall (Optional)

  1. Allow Apache Through UFW:
    If UFW (Uncomplicated Firewall) is enabled, allow Apache traffic:
   sudo ufw allow in "Apache"
   sudo ufw enable
  1. Verify Firewall Rules:
   sudo ufw status

6. Test the LAMP Stack

  1. Host a Test Page:
    Create an HTML or PHP file in /var/www/html and access it via your browser.
  2. Access MySQL:
    Open the MySQL shell:
   sudo mysql
  1. Benchmark Your Stack:
    Tools like Apache JMeter can simulate traffic to test performance.

7. Troubleshooting

  1. Apache Not Starting:
    Check logs for errors:
   sudo journalctl -xe
  1. MySQL Connection Issues:
    Verify credentials and permissions. For help, visit the MySQL troubleshooting guide.
  2. PHP Errors:
    Enable error reporting in your PHP script or modify php.ini:
   sudo nano /etc/php/7.x/apache2/php.ini
  1. More Help:
    Search for solutions on Ask Ubuntu if issues persist.

Leave a Reply

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