Complete LAMP Stack Installation on Ubuntu

By Anurag Singh

Updated on Apr 09, 2025

Complete LAMP Stack Installation on Ubuntu

In this tutorial, we'll learn complete LAMP stack installation on Ubuntu with security hardening.

Below is a detailed guide on how to install and secure a LAMP stack (Linux, Apache, MySQL/MariaDB, and PHP). While there are variations across distributions, the fundamental concepts remain the same. The following steps illustrate best practices and the latest security considerations to help you build a reliable and secure environment.

Prerequisites

Before proceeding, make sure you have the following in place:

  • A Fresh Ubuntu 24.04 dedicated server or KVM VPS.
  • Root or Sudo Privileges: You should have sudo privileges to install packages and make system-wide changes.
  • A Valid Domain Name (Optional but Recommended)

1. Choose and Prepare Your Linux Distribution

The "L" in LAMP stands for Linux. You can use popular distributions such as Ubuntu, Debian, CentOS, or Fedora. In this guide, commands generally cater to Ubuntu-like systems (using apt), but the steps can be adapted for other distributions.

Update the system

sudo apt update && sudo apt upgrade -y

Keeping your system updated ensures that you have the latest security patches.

Create a non-root user (if needed)

sudo adduser lampuser
sudo usermod -aG sudo lampuser

Avoid operating as the root user for daily tasks; use a non-root account with sudo privileges.

2. Install Apache

Apache is one of the most widely used web servers and provides robust, stable service.

Install Apache

sudo apt install apache2 -y

Verify that Apache is running

systemctl status apache2

Alternatively, open a web browser and navigate to http://server_ip/; you should see the default Apache page.

Configure firewall (UFW)

sudo ufw allow 'Apache'
sudo ufw reload
sudo ufw status

Only allow the minimum required ports (typically 80 for HTTP and 443 for HTTPS).

3. Install MySQL or MariaDB

Both MySQL and MariaDB can be used interchangeably in a LAMP stack. MariaDB is a community-driven fork of MySQL and often the default on certain distributions.

Install database server

# For MySQL:
sudo apt install mysql-server -y

# For MariaDB:
sudo apt install mariadb-server -y

Start and enable the service

sudo systemctl enable mysql
sudo systemctl start mysql

Secure the database server

sudo mysql_secure_installation

You will be prompted to set a strong root password, remove anonymous users, disallow remote root login, and remove test databases.

Create a dedicated database user (optional but recommended)

Using the MySQL shell:

sudo mysql -u root -p

Once in the shell:

CREATE DATABASE my_database;
CREATE USER 'my_user'@'localhost' IDENTIFIED BY 'MyStrongPassword!';
GRANT ALL PRIVILEGES ON my_database.* TO 'my_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

This practice keeps different applications isolated with distinct credentials.

4. Install and Configure PHP

PHP handles the server-side logic of your web applications.

Install PHP and the Apache PHP module

sudo apt install php libapache2-mod-php php-mysql -y

php-mysql (or php-mysqli) ensures that PHP can communicate with your database.

For more functionality, install additional PHP extensions (e.g., php-xml, php-curl, php-gd, etc.) as needed.

Verify the installed PHP version

php -v

Configure Apache to prefer PHP files

Edit /etc/apache2/mods-enabled/dir.conf if necessary. Ensure the index.php line appears before index.html:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html
</IfModule>

Test PHP processing

Create a test file:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

Navigate to http://server_ip/info.php in your browser. You should see detailed PHP information. Remove this file (info.php) once testing is complete to avoid exposing sensitive information.

5. Basic Apache Configuration Hardening

Apache has several directives and modules that you can tweak for better security.

Hide server information

Edit /etc/apache2/conf-available/security.conf:

ServerTokens Prod
ServerSignature Off

This hides version info from error pages and server headers.

Disable directory listing

Within your site’s configuration (e.g., /etc/apache2/sites-available/000-default.conf or your custom vhost file), ensure:

<Directory /var/www/html>
    Options -Indexes
</Directory>

-Indexes prevents Apache from listing files if an index file is missing.

Enable HTTPS

Install SSL modules:

sudo apt install python3-certbot-apache -y

Obtain a free Let’s Encrypt SSL certificate:

sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

Certbot will configure Apache to redirect HTTP to HTTPS by default.

6. PHP Hardening

PHP configurations can significantly impact security. The default settings often reveal too much information or allow insecure behavior.

Edit php.ini file

Located in /etc/php/8.x/apache2/php.ini (version may vary). Look for these directives:

expose_php = Off
display_errors = Off
log_errors = On
post_max_size = 16M
upload_max_filesize = 16M
max_execution_time = 30
memory_limit = 256M

Adjusting these values helps mitigate DoS attacks and leak of sensitive info.

Use the latest PHP version
Older versions may no longer receive security patches. Using the latest stable PHP helps reduce known vulnerabilities.

Disable dangerous PHP functions (optional)
Consider disabling functions like exec, shell_exec, system, etc., if your application does not require them. This can prevent malicious code from executing system-level commands.

7. Database Hardening

Beyond the basic mysql_secure_installation, consider these best practices to lock down your database server:

Use strong passwords
Ensure every user has a robust password. Avoid reusing credentials.

Remove or limit remote access
If your database does not need remote access, bind MySQL/MariaDB to 127.0.0.1 in /etc/mysql/mysql.conf.d/mysqld.cnf (or /etc/mysql/mariadb.conf.d/50-server.cnf):

bind-address = 127.0.0.1

Principle of least privilege
Grant each application user only the privileges they need (SELECT, INSERT, UPDATE, DELETE) rather than ALL PRIVILEGES.

8. Firewall Configuration

A properly configured firewall helps limit your server’s exposure.

UFW (Uncomplicated Firewall)

If you haven’t already enabled UFW:

sudo ufw enable

Allow specific ports:

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Check status:

sudo ufw status

Limit SSH access

If possible, restrict SSH connections to trusted IP addresses:

sudo ufw allow from <trusted_IP> to any port 22
sudo ufw deny 22

Alternatively, change the default SSH port to something nonstandard.

9. Additional Security Tools

Several tools and configurations add an extra layer of defense:

Fail2ban

Monitors logs and bans IPs with repeated invalid login attempts:

sudo apt install fail2ban -y

Edit /etc/fail2ban/jail.local to customize rules for SSH, Apache, and other services.

Intrusion Detection/Prevention
Tools like OSSEC or Snort can monitor system activity for suspicious behavior.

SELinux/AppArmor
Most Ubuntu/Debian systems use AppArmor by default, while CentOS/Fedora often rely on SELinux. Make sure the relevant security module is enforced or in a mode that suits your environment’s requirements.

Regular backups
Implement an automated backup strategy for your web files, databases, and configurations. Store these backups offsite or in a secure remote location.

10. Keep Everything Up to Date

Security is an ongoing process. Even the most secure setup requires periodic maintenance to stay protected.

Enable automatic updates (if feasible)

On Ubuntu/Debian, you can configure unattended upgrades:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

Manually update packages

Regularly run:

sudo apt update && sudo apt upgrade -y

Regular software audits
Check installed packages, remove unused modules, and keep an eye on known security advisories.

11. Test, Monitor, and Review

Once you have your LAMP stack and security measures in place, you should test your configuration thoroughly.

Check Apache logs (/var/log/apache2/) and MySQL logs (/var/log/mysql/) for errors or unusual activity.

Scan ports to confirm only necessary ports are open:

sudo apt install nmap
nmap -sS your_server_ip

Implement a monitoring solution like Nagios, Zabbix, or a cloud service for real-time alerts.

Conclusion

A LAMP stack provides a robust environment for hosting dynamic websites and applications. However, installation is just the beginning. Ongoing security hardening measures—using strong credentials, restricting access, keeping software updated, and continuously monitoring—are paramount to ensuring your server remains protected. By combining these recommended best practices, you’ll create a LAMP stack that’s both efficient and secure for your application needs.