DebianDebian Based

How To Install LAMP Stack on Debian 13

Install LAMP Stack on Debian 13

The LAMP stack remains one of the most powerful and versatile web development platforms available today. This comprehensive collection of open-source technologies—Linux, Apache, MariaDB, and PHP—provides developers and system administrators with everything needed to create dynamic, high-performance websites and web applications. Debian 13 “Trixie,” released in August 2025, offers excellent support for modern LAMP stack implementations with enhanced security features and improved performance optimizations.

Installing a LAMP stack on Debian 13 provides numerous advantages for web hosting environments. The stability of Debian combined with the flexibility of Apache, the reliability of MariaDB, and the versatility of PHP creates an ideal foundation for both small projects and enterprise-level applications. This tutorial will guide you through every step of the installation process, from initial system preparation to advanced security hardening.

Whether you’re a seasoned Linux administrator or a developer new to server management, this guide provides detailed instructions, troubleshooting tips, and best practices to ensure a successful LAMP stack deployment. By the end of this tutorial, you’ll have a fully functional web server environment ready for hosting dynamic websites, content management systems, or custom web applications.

Prerequisites and System Requirements

Before beginning the LAMP stack installation on Debian 13, several prerequisites must be met to ensure optimal performance and compatibility. Understanding these requirements prevents common installation issues and establishes a solid foundation for your web server environment.

Hardware Requirements

Debian 13 with a LAMP stack requires adequate system resources to function effectively. The minimum hardware specifications include 2 GB of RAM, though 4 GB or more is recommended for production environments handling multiple websites or significant traffic volumes. Storage requirements start at 20 GB minimum, with 50 GB or more recommended to accommodate future growth, log files, and database storage needs.

The system must use a 64-bit (x86_64) processor architecture, as this is the standard for modern server deployments and ensures compatibility with current security features and performance optimizations. Additionally, a stable internet connection is essential for downloading packages and receiving security updates throughout the installation process.

Software Prerequisites

A fresh Debian 13 installation provides the cleanest starting point for LAMP stack deployment. The system should be updated with the latest security patches and package updates before beginning the installation process. Root access or a user account with sudo privileges is mandatory for installing system-level packages and modifying configuration files.

Basic command-line knowledge significantly improves the installation experience, though this guide provides detailed explanations for each command. Familiarity with text editors like nano or vim proves helpful for configuration file modifications, and understanding of basic networking concepts assists with firewall and virtual host configurations.

Pre-installation Checklist

Creating a comprehensive backup of existing configurations protects against potential data loss during the installation process. This precaution is particularly important when upgrading existing systems or installing LAMP stack components on servers with existing services.

Verify that essential network ports (80 for HTTP and 443 for HTTPS) are available and not currently in use by other services. Check the system architecture compatibility to ensure all LAMP stack components will function correctly on your Debian 13 installation.

System Preparation

Proper system preparation forms the foundation for a successful LAMP stack installation. This phase involves updating the operating system, configuring basic security measures, and ensuring the network environment supports web server operations.

Updating Debian 13 System

Begin by updating the package repository information and upgrading all installed packages to their latest versions. Execute the following commands to ensure your system has the most recent security patches and software updates:

sudo apt update && sudo apt upgrade -y

This process may take several minutes depending on your internet connection and the number of packages requiring updates. The package update process is crucial for maintaining system security and ensuring compatibility with the LAMP stack components you’ll install.

After the update completes, consider rebooting the system to ensure all kernel updates and system changes take effect properly. This step prevents potential conflicts during the LAMP stack installation process.

Security Preparation

Implementing basic security measures before installing web server components protects your system from potential vulnerabilities. Configure the Uncomplicated Firewall (UFW) to control network access to your server:

sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing

These commands establish a secure baseline by blocking unauthorized incoming connections while allowing necessary outbound traffic. Additional firewall rules will be configured as each LAMP stack component is installed.

Create a dedicated user account for web server administration if you haven’t already done so. This practice follows the principle of least privilege and reduces security risks associated with using the root account for routine tasks.

Network Configuration

Verify that your server’s network configuration supports web hosting requirements. Ensure that ports 80 (HTTP) and 443 (HTTPS) are available for Apache web server operations. If you plan to use a domain name, configure DNS settings to point your domain to the server’s IP address.

For local development environments, note the server’s IP address for testing purposes. Production deployments should have proper domain name resolution configured before proceeding with the installation.

Installing Apache Web Server

Apache HTTP Server serves as the foundation of your LAMP stack, handling incoming web requests and serving content to visitors. Debian 13 includes Apache 2.4 in its default repositories, providing a stable and feature-rich web server platform.

Apache Installation Process

Install Apache web server using the APT package manager with the following command:

sudo apt install apache2 -y

The installation process automatically creates necessary system users, sets up configuration directories, and installs essential Apache modules. After installation completes, start and enable the Apache service to begin automatically at system boot:

sudo systemctl start apache2
sudo systemctl enable apache2

Verify the Apache installation by checking the service status:

sudo systemctl status apache2

A successful installation displays an “active (running)” status, indicating that Apache is operational and ready to serve web content.

Apache Configuration

Apache’s main configuration file resides at /etc/apache2/apache2.conf, while site-specific configurations are stored in the /etc/apache2/sites-available/ directory. The default Apache configuration provides a solid starting point for most web hosting needs.

Examine the default Apache configuration to understand the document root location and basic server settings:

sudo nano /etc/apache2/sites-available/000-default.conf

The default document root is /var/www/html/, where you’ll place website files. Apache automatically serves the index.html file when visitors access your server’s root directory.

Configure Apache to prioritize PHP files over HTML files by editing the directory index configuration. This ensures that PHP-powered websites function correctly when both index.php and index.html files exist.

Apache Security Configuration

Enhance Apache security by hiding server version information that could assist potential attackers. Edit the Apache configuration file to include security directives:

sudo nano /etc/apache2/conf-available/security.conf

Add or modify the following lines to improve security:

ServerTokens Prod
ServerSignature Off

These settings minimize the information Apache reveals about your server configuration. Disable directory listing to prevent unauthorized browsing of server directories:

Options -Indexes

Firewall Configuration for Apache

Configure the firewall to allow HTTP and HTTPS traffic to reach your Apache web server:

sudo ufw allow 'Apache Full'

This command opens both ports 80 and 443 for web traffic. Alternatively, you can open specific ports individually:

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

Test the Apache installation by navigating to your server’s IP address in a web browser. You should see the default Apache welcome page, confirming that the web server is functioning correctly.

Installing MariaDB Database Server

MariaDB provides the database foundation for your LAMP stack, offering robust data storage and retrieval capabilities for dynamic web applications. Debian 13 includes MariaDB 11.8, which delivers enhanced performance and security features compared to earlier versions.

MariaDB Installation

Install MariaDB server and client packages using the following command:

sudo apt install mariadb-server mariadb-client -y

The installation process creates the necessary database files, system users, and service configurations. After installation, start and enable the MariaDB service:

sudo systemctl start mariadb
sudo systemctl enable mariadb

Verify that MariaDB is running properly:

sudo systemctl status mariadb

A successful installation shows an “active (running)” status, indicating that the database server is operational and ready for configuration.

MariaDB Security Configuration

Secure your MariaDB installation using the built-in security script that removes default accounts and settings:

sudo mysql_secure_installation

This interactive script guides you through several security enhancements:

  1. Set a strong root password when prompted
  2. Remove anonymous user accounts that allow unauthorized access
  3. Disable remote root login to prevent external administrative access
  4. Remove the test database that serves no production purpose
  5. Reload privilege tables to apply security changes immediately

Choose strong passwords using a combination of uppercase letters, lowercase letters, numbers, and special characters. Document the root password securely, as you’ll need it for database administration tasks.

Database Performance Tuning

Optimize MariaDB performance by adjusting configuration settings in the main configuration file:

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Consider adjusting the following parameters based on your server’s available memory:

innodb_buffer_pool_size = 1G
query_cache_size = 64M
max_connections = 200

These settings improve database performance for typical web hosting workloads. Adjust values based on your server’s RAM allocation and expected database load.

Testing Database Installation

Test the MariaDB installation by connecting to the database console:

sudo mysql -u root -p

Create a test database and user account to verify functionality:

CREATE DATABASE test_db;
CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

This test confirms that MariaDB is functioning correctly and can create databases and user accounts for your web applications.

Installing PHP and Extensions

PHP serves as the dynamic scripting language in your LAMP stack, processing server-side code and generating dynamic web content. Debian 13 includes PHP 8.4, which offers improved performance, enhanced security features, and modern language capabilities.

PHP Installation

Install PHP along with essential modules for Apache integration and MariaDB connectivity:

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

This command installs the PHP interpreter, Apache integration module, MySQL connectivity support, and commonly required extensions for web development. The installation automatically configures Apache to process PHP files.

Restart Apache to activate the PHP module:

sudo systemctl restart apache2

Verify the PHP installation by checking the installed version:

php -v

Essential PHP Extensions

Install additional PHP extensions commonly required for web applications and content management systems:

sudo apt install php-json php-opcache php-readline php-bcmath php-intl -y

These extensions provide JSON processing capabilities, performance optimization through opcaching, command-line interaction support, mathematical functions, and internationalization features.

The OPcache extension significantly improves PHP performance by storing compiled script bytecode in memory, reducing the need for script parsing on subsequent requests. This optimization is particularly beneficial for high-traffic websites.

PHP Configuration

Configure PHP settings by editing the main configuration file:

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

Adjust important security and performance settings:

expose_php = Off
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300

These settings hide PHP version information from HTTP headers, increase memory limits for complex applications, allow larger file uploads, and extend execution time for resource-intensive scripts.

Apache-PHP Integration

Ensure Apache prioritizes PHP files over static HTML files by configuring the directory index:

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

Modify the DirectoryIndex directive to prioritize index.php:

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

Restart Apache to apply the configuration changes:

sudo systemctl restart apache2

This configuration ensures that PHP-powered websites display correctly when both PHP and HTML index files exist in the same directory.

Testing LAMP Stack Installation

Comprehensive testing verifies that all LAMP stack components function correctly together. This validation process identifies potential configuration issues before deploying production websites.

Creating PHP Test Files

Create a PHP information file to verify PHP installation and configuration:

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

Add the following PHP code:

<?php
phpinfo();
?>

Access the PHP information page by navigating to http://your_server_ip/info.php in a web browser. The page displays comprehensive information about PHP configuration, loaded extensions, and system environment.

Review the PHP information page to confirm that essential extensions are loaded and configuration settings match your requirements. Pay particular attention to the MySQL/MariaDB extension status and file upload limits.

Database Connectivity Testing

Create a PHP script to test database connectivity between PHP and MariaDB:

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

Add database connection test code:

<?php
$servername = "localhost";
$username = "test_user";
$password = "secure_password";
$dbname = "test_db";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Database connection successful!";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Access the database test script through your web browser to verify that PHP can successfully connect to MariaDB. A successful connection confirms that all LAMP stack components are functioning together correctly.

Web Server Functionality Test

Create a simple HTML page to test basic Apache functionality:

sudo nano /var/www/html/test.html

Add basic HTML content:

<!DOCTYPE html>
<html>
<head>
    <title>LAMP Stack Test</title>
</head>
<body>
    <h1>LAMP Stack Installation Successful!</h1>
    <p>Apache, MariaDB, and PHP are working correctly.</p>
</body>
</html>

Access the test page to confirm that Apache serves static content properly. This basic test validates the web server’s fundamental operation.

Security Verification

Remove test files after completing the validation process to prevent security risks:

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

The PHP information file reveals detailed system information that could assist potential attackers, making its removal essential for production environments.

Advanced Configuration and Optimization

Advanced LAMP stack configuration enhances performance, security, and functionality for production web hosting environments. These optimizations prepare your server for handling real-world web applications and traffic loads.

Virtual Host Configuration

Virtual hosts enable hosting multiple websites on a single server, each with distinct domain names and configurations. Create a virtual host for your primary website:

sudo nano /etc/apache2/sites-available/your_domain.conf

Add virtual host configuration:

<VirtualHost *:80>
    ServerName your_domain.com
    ServerAlias www.your_domain.com
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/your_domain_error.log
    CustomLog ${APACHE_LOG_DIR}/your_domain_access.log combined
</VirtualHost>

Create the document root directory and set proper permissions:

sudo mkdir -p /var/www/your_domain
sudo chown -R www-data:www-data /var/www/your_domain
sudo chmod -R 755 /var/www/your_domain

Enable the virtual host and disable the default site:

sudo a2ensite your_domain.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2

Performance Optimization

Optimize Apache performance by configuring the appropriate Multi-Processing Module (MPM) based on your server’s resources and expected traffic patterns. The prefork MPM works well for most PHP applications:

sudo nano /etc/apache2/mods-available/mpm_prefork.conf

Adjust MPM settings for your server’s capabilities:

<IfModule mpm_prefork_module>
    StartServers 5
    MinSpareServers 5
    MaxSpareServers 10
    MaxRequestWorkers 150
    MaxConnectionsPerChild 0
</IfModule>

Enable PHP OPcache for improved script performance:

sudo nano /etc/php/8.4/apache2/conf.d/10-opcache.ini

Configure OPcache settings:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

Monitoring and Logging

Configure log rotation to manage disk space usage by Apache and PHP log files:

sudo nano /etc/logrotate.d/apache2

Ensure proper log rotation settings are configured to prevent log files from consuming excessive disk space. Regular log maintenance is essential for long-term server stability.

Install monitoring tools to track server performance and resource usage:

sudo apt install htop iotop -y

These tools provide real-time insights into system performance, helping you identify potential bottlenecks or resource constraints.

Backup Configuration

Implement automated backup procedures for your web files and databases. Create a simple backup script:

sudo nano /usr/local/bin/backup_lamp.sh

Add backup functionality:

#!/bin/bash
BACKUP_DIR="/backups"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup web files
tar -czf $BACKUP_DIR/web_files_$DATE.tar.gz /var/www/

# Backup databases
mysqldump --all-databases > $BACKUP_DIR/databases_$DATE.sql
gzip $BACKUP_DIR/databases_$DATE.sql

Make the script executable and schedule it to run regularly:

sudo chmod +x /usr/local/bin/backup_lamp.sh

Security Hardening

Comprehensive security hardening protects your LAMP stack from common threats and vulnerabilities. These measures establish multiple layers of defense against potential attacks.

System-Level Security

Configure a robust firewall using UFW to control network access:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 'Apache Full'
sudo ufw enable

Install and configure Fail2Ban to automatically block IP addresses exhibiting suspicious behavior:

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

Create custom Fail2Ban configurations for Apache and SSH protection:

sudo nano /etc/fail2ban/jail.local

Add protection rules:

[DEFAULT]
bantime = 1800
findtime = 600
maxretry = 3

[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log

[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/*access.log

Apache Security Hardening

Enhance Apache security by hiding server information and restricting access to sensitive directories:

sudo nano /etc/apache2/conf-available/security.conf

Configure security settings:

ServerTokens Prod
ServerSignature Off
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"

Enable the headers module and apply security configurations:

sudo a2enmod headers
sudo a2enconf security
sudo systemctl restart apache2

Database Security

Secure MariaDB by implementing proper user privilege management and network restrictions. Create database users with minimal required privileges:

CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON app_database.* TO 'app_user'@'localhost';
FLUSH PRIVILEGES;

Configure MariaDB to listen only on localhost unless remote access is specifically required:

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Ensure the bind-address setting restricts network access:

bind-address = 127.0.0.1

PHP Security Settings

Harden PHP configuration by disabling dangerous functions and implementing security restrictions:

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

Configure security-focused PHP settings:

disable_functions = exec,passthru,shell_exec,system,proc_open,popen
expose_php = Off
allow_url_fopen = Off
allow_url_include = Off
display_errors = Off
log_errors = On

These settings prevent execution of potentially dangerous functions while maintaining application functionality for legitimate use cases.

Installing phpMyAdmin (Optional)

phpMyAdmin provides a web-based interface for MariaDB database administration, simplifying database management tasks for users who prefer graphical interfaces over command-line tools.

phpMyAdmin Installation

Install phpMyAdmin using the APT package manager:

sudo apt install phpmyadmin -y

During installation, select Apache as the web server and choose to configure the database automatically. Provide a secure password for the phpMyAdmin administrative user when prompted.

phpMyAdmin Configuration

Configure phpMyAdmin security settings to restrict access and enhance protection:

sudo nano /etc/phpmyadmin/config.inc.php

Add security enhancements:

$cfg['ForceSSL'] = true;
$cfg['LoginCookieValidity'] = 3600;
$cfg['Servers'][$i]['AllowNoPassword'] = false;

Create an Apache configuration file for phpMyAdmin access:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Add access restrictions:

<Directory /usr/share/phpmyadmin>
    Require ip 127.0.0.1
    Require ip ::1
    # Add your IP addresses here
    # Require ip your.ip.address.here
</Directory>

Enable the phpMyAdmin configuration:

sudo a2enconf phpmyadmin
sudo systemctl restart apache2

Security Considerations

Implement additional security measures for phpMyAdmin access. Consider using HTTP authentication for an extra security layer:

sudo htpasswd -c /etc/apache2/.htpasswd admin_user

Configure Apache to require HTTP authentication for phpMyAdmin access by adding authentication directives to the phpMyAdmin configuration file.

Troubleshooting Common Issues

Understanding common LAMP stack issues and their solutions helps maintain a stable web hosting environment. These troubleshooting techniques resolve frequent problems encountered during installation and operation.

Installation Problems

Package dependency conflicts may occur during installation. Resolve conflicts by updating package lists and fixing broken dependencies:

sudo apt update
sudo apt --fix-broken install
sudo apt autoremove

Service startup failures often result from configuration errors or port conflicts. Check service status and log files for specific error messages:

sudo systemctl status apache2
sudo journalctl -u apache2 -n 50

Port conflicts prevent services from starting correctly. Identify processes using required ports:

sudo netstat -tlnp | grep :80
sudo netstat -tlnp | grep :3306

Configuration Issues

PHP files displaying as plain text instead of executing indicates Apache-PHP integration problems. Verify that the PHP module is enabled:

sudo a2enmod php8.4
sudo systemctl restart apache2

Database connection failures commonly result from incorrect credentials or service issues. Test database connectivity manually:

mysql -u username -p -h localhost database_name

Virtual host problems may prevent websites from loading correctly. Check virtual host configuration syntax:

sudo apache2ctl configtest

Performance Issues

Memory allocation errors occur when PHP applications exceed configured limits. Monitor memory usage and adjust PHP settings:

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

Slow database queries impact website performance. Enable MySQL slow query log to identify problematic queries:

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Add slow query logging:

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

Best Practices and Maintenance

Maintaining a LAMP stack requires ongoing attention to security updates, performance monitoring, and system maintenance. These best practices ensure long-term stability and security.

Regular Maintenance Tasks

Establish a schedule for system updates and security patches. Create a maintenance script that automates routine tasks:

#!/bin/bash
# System updates
apt update && apt upgrade -y

# Log rotation
logrotate -f /etc/logrotate.conf

# Database optimization
mysqlcheck --all-databases --auto-repair --optimize

# Clean temporary files
apt autoremove -y
apt autoclean

Monitor disk usage regularly to prevent storage-related issues:

df -h
du -sh /var/log/*
du -sh /var/www/*

Security Best Practices

Implement regular security audits using automated tools and manual reviews. Keep detailed logs of system changes and access patterns. Monitor security advisories for LAMP stack components and apply updates promptly.

Configure automated security updates for critical packages while maintaining control over major version changes that might affect application compatibility.

Performance Monitoring

Establish baseline performance metrics and monitor key indicators regularly. Track CPU usage, memory consumption, disk I/O, and network traffic to identify trends and potential issues before they impact users.

Use tools like top, htop, and iotop to monitor real-time system performance. Configure alerts for critical thresholds to enable proactive problem resolution.

Congratulations! You have successfully installed LAMP. Thanks for using this tutorial to install the latest version of the LAMP Stack on Debian 13 “Trixie” system. For additional help or useful information, we recommend you check the official LAMP website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button