Skip to content

Set Up a LAMP Stack on a Linux Server – Run Classic PHP Applications

Learn how to efficiently set up a LAMP stack for hosting dynamic PHP websites on a Linux VPS

12 November 20267 min read45 Views0 helpful

Introduction

The LAMP stack is a popular collection of open-source software components configured together to make hosting dynamic websites easy—with a particular focus on PHP websites and apps. The acronym stands for: Linux as the operating system, Apache as the web server, MySQL as the database, and PHP for processing. In this guide, we’ll show you how to set up a LAMP stack on a Linux VPS, including a detailed step-by-step explanation and an example of a to-do list website.

Preparation

First, connect to your server via SSH. If you’re not sure how to do this, check out our Initial Access (SSH) guide.

In this guide, we use Ubuntu as the Linux distribution. The commands are identical on Debian and similar on other distributions, but the syntax may differ slightly. Make sure an operating system is installed and that you’re connected via SSH.

As always, update all packages before installation with the following command:

Code
// Ubuntu & Debian
sudo apt update

// CentOS
sudo yum update

// OpenSUSE
sudo zypper up

// Fedora
sudo dnf upgrade --refresh

Installation

The installation can be divided into the individual core components of the LAMP stack: first the Apache web server, then the MySQL database, and finally PHP. During installation, we’ll set up a test website written in PHP that accesses the MySQL database. Each web request will then be processed and served by Apache.

Set Up Apache

Apache is the web server that processes incoming web requests and delivers responses. Install it with the following command:

Code
sudo apt install apache2

After installation, make sure the appropriate firewall rules are in place so the web server can be reached from the internet. In this example, we use the UFW firewall, since Apache has a registered application profile for it.

If you use a different firewall, make sure port 80 (HTTP) is open. Find out more about firewalls on Linux in our Managing the Firewall guide.

Enable the UFW firewall and create a rule for SSH:

Code
# Regel für SSH erstellen
sudo ufw allow OpenSSH

# UFW Firewall aktivieren
sudo ufw enable
Warning

Make sure you have an SSH rule in the UFW firewall! Without it, you won’t be able to connect via SSH after enabling the firewall if you lose your current session!

Now create the rule for Apache and check the rules:

Code
# Regel für Apache erstellen
sudo ufw allow in "Apache Full"

# UFW Firewall Status prüfen
sudo ufw status
Tip

Use ufw app list to see which profiles are available. Apache Full means that both HTTP (port 80) and HTTPS (port 443) are allowed.

You should see Apache and Apache (v6) with ALLOW, confirming that the firewall is configured correctly. Other rules, such as the one for SSH, should also be displayed.

With the firewall open for Apache, you can now test whether Apache is working. Open your server’s IP address in a browser: http://[deine_ip_adresse]

If everything is working, you should see a default welcome page. If not, check the status with: systemctl status apache2

Set Up MySQL

Next, install MySQL, which serves as the database for storing data relationally. Install it with:

Code
sudo apt install mysql-server

After installation, we recommend running the security script to secure your MySQL server. This is optional, but highly recommended. Run it with:

Code
sudo mysql_secure_installation

The script will guide you through the setup interactively. First, you’ll be asked about password validation. We recommend choosing Y to allow only secure passwords, then selecting MEDIUM (1) or STRONG (2).

You’ll then be asked whether to remove the anonymous user and disable root login from outside the server. We recommend confirming both with Y to improve security.

Finally, you’ll be asked whether to remove the test database and reload the privilege tables. We also recommend choosing Y here.

Check whether MySQL is running by logging in:

Code
sudo mysql -u root

If you see a welcome message, everything worked. Enter quit to exit the MySQL console.

Set Up PHP

The final LAMP component is PHP. Installation is straightforward:

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

Check the installation with:

Code
php -v

If a version number is displayed, PHP is working correctly.

Tip: PHP extensions

You may need additional PHP extensions for specific use cases. View a list with:

Code
apt search php- | less

Use the arrow keys to scroll and Q to exit. To install an extension:

Code
sudo apt install [php_extension] [...]

You can install multiple extensions at once, separated by spaces.

We recommend adjusting the directory index order so that index.php is loaded before .html. Open the file:

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

Move index.php to the beginning of the list:

Code
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

Save with CTRL + X, confirm with Y, and press ENTER. Restart Apache:

Code
sudo systemctl restart apache2

Create a Test Website

Once all LAMP components are installed, we’ll create a test website to show how they work together. This is optional, but helpful for understanding how to build your own websites.

We’ll create a small to-do list in PHP that retrieves and displays entries from a MySQL database. We’ll use zapdocs.example.com as the example domain. You must create an A DNS record for the domain that points to your server’s IP address. For help, see our Domain Records guide.

Info

You can also work without a domain and replace [your_domain] with any name. You can then access the site using the IP address. However, in this case, you should remove the ServerName line from the virtual host file.

Configure Apache

Websites are usually stored in the /var/www directory. By default, it contains an html directory with a default page. If you’re hosting multiple websites, we recommend creating a separate directory for each domain.

Create a directory for your domain:

Code
sudo mkdir /var/www/[your_domain]

Create a new virtual host configuration file:

Code
sudo nano /etc/apache2/sites-available/[your_domain].conf

Insert this template and replace [your_domain] with your domain:

Code

    ServerName [your_domain]
    ServerAlias www.[your_domain]
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/[your_domain]
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

Save and exit with CTRL + X, Y, and ENTER. Check the syntax:

Code
sudo apache2ctl configtest

Enable the new virtual host:

Code
sudo a2ensite [your_domain]
Info: Not using a domain?

If you’re not using a domain, remove or comment out the ServerName line (using #) and disable the default host:

Code
sudo a2dissite 000-default

Restart Apache:

Code
sudo systemctl restart apache2

Create the Website

The directory is currently empty, so let’s create the to-do website.

Prepare the Database

Log in to MySQL:

Code
sudo mysql -u root

Create a new database and table:

Code
# Datenbank erstellen
CREATE DATABASE todowebsite;

# Datenbank auswählen
USE todowebsite;

# Tabelle erstellen
CREATE TABLE todoitems (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    is_completed BOOLEAN DEFAULT FALSE,
    creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Add a few sample entries:

Code
INSERT INTO todoitems (name, is_completed) VALUES ('Create ZAP-Docs Guide', 0);
INSERT INTO todoitems (name, is_completed) VALUES ('Buy a ZAP-Hosting Server', 1);
INSERT INTO todoitems (name, is_completed) VALUES ('Join ZAP-Hosting Discord', 0);
INSERT INTO todoitems (name, is_completed) VALUES ('Have a great day!', 0);

Create a dedicated user for the website:

Code
# Benutzer erstellen
# Ersetze [your_password] durch dein Passwort
CREATE USER todo@localhost IDENTIFIED BY '[your_password]';

# Rechte vergeben (als ein Befehl kopieren)
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER
ON todowebsite.*
TO todo@localhost;

# Rechte neu laden
FLUSH PRIVILEGES;

Exit the MySQL console with quit.

PHP Website Files

Create the PHP file for the to-do page:

Code
sudo nano /var/www/[your_domain]/index.php

Insert the following code. It connects to the database and displays the to-do entries.

Important

Replace [your_password] with the password you assigned to the todo user.

Code
<?php
// MySQL-Verbindung vorbereiten
$servername = "localhost";
$username = "todo";
$password = "[your_password]";
$dbname = "todowebsite";

// Verbindung erstellen
$conn = new mysqli($servername, $username, $password, $dbname);

// Verbindung prüfen, bei Fehler abbrechen
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL-Abfrage, um Einträge abzurufen
$sql = "SELECT id, name, is_completed, creation_date FROM todoitems ORDER BY creation_date DESC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="de">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>To-Do Liste</title>
  </head>
  <body>
      <h1>Coole To-Do Liste :D</h1>
      <p>Für unseren coolen ZAP-Hosting Guide: <a href="https://zap-hosting.com/guides/docs/vserver-linux-lamp-stack">https://zap-hosting.com/guides/docs/vserver-linux-lamp-stack</a></p>
      <ul>
          <?php
          // Prüfen, ob Ergebnisse vorhanden sind
          if ($result->num_rows > 0) {
              // Durch alle Einträge iterieren
              foreach ($result as $entry) {
                  echo "<li>";
                  // Name anzeigen, htmlspecialchars schützt vor XSS
                  echo htmlspecialchars($entry["name"]);

                  // Status anzeigen
                  if ($entry["is_completed"]) {
                      echo " <strong>(Erledigt)</strong>";
                  } else {
                      echo " <strong>(Offen)</strong>";
                  }

                  // Erstellungsdatum anzeigen
                  echo " - Erstellungsdatum: " . htmlspecialchars($entry['creation_date']);
                  echo "</li>";
              }
          } else {
              // Falls keine Einträge vorhanden sind
              echo "<li>Keine To-Do-Einträge gefunden.</li>";
          }
          ?>
      </ul>
  </body>
</html>

<?php
// Verbindung schließen
$conn->close();
?>

Save and exit with CTRL + X, Y, and ENTER.

Test the Website

You’ve successfully set up a test to-do website that uses all the LAMP components!

Now access it using the domain (HTTP/port 80) that you defined in the virtual host, for example, zapdocs.example.com. It should look like this:

Conclusion

Congratulations, you’ve successfully installed and configured the LAMP stack! As a next step, we strongly recommend setting up a domain and an SSL certificate so your website can be accessed securely. See our Certbot Guide, which focuses on the Apache plugin, and follow the interactive setup to quickly get a certificate for your domain.

If you have any questions or run into problems, our support team is here to help every day! 🙂

Free tools

Related tools for servers and developers

View all

FAQ

Frequently asked questions

Linux as the operating system, Apache as the web server, MySQL as the database, and PHP for processing—a popular combination for hosting dynamic PHP websites.
LAMP uses Apache as its web server, while LEMP uses Nginx (Engine X). The rest of the stack (Linux, MySQL, and PHP) is the same.
Run sudo apt install apache2. Then make sure port 80 (HTTP) is open in your firewall.

Feedback

Was this article helpful?

Your feedback helps us prioritize and improve content.

0 of 0 people found this article helpful.

Personal support

Need more help than the guide provides?

Our ZAP-Hosting support team knows your product — briefly describe your issue and we'll help you personally.

Zappy knows this guide and answers you right in the chat.