How to Install Apache, MySQL, PHP (LAMP Stack) on Debian 12?
The installation of the LAMP stack is required to build a dynamic website or a web application on a Debian 12 server. It consists of four essential open-source components: Linux, Apache, MySQL, and PHP. Together, the below tools create a powerful and efficient web server setup.
- Linux provides a stable and secure environment. It acts as the foundation for your system.
- Apache is a popular web server. It is responsible for handling incoming web requests and serving your website content.
- MySQL acts as a backend database.
- Lastly, PHP processes the dynamic content of your website and makes it interactive.
Below are the pre-requisites. You need to complete these initial setup tasks before installation.
- Deploy Debian 12 on a server using a cloud provider service like Cantech
- Point a domain to your server. Set up a new A record that maps your domain to the server’s public IP. Example: app.example.com.
- Access your server via SSH. Log in as a non-root user with sudo privileges.
- Update your system. Run the command below to refresh package lists and install any pending updates.
sudo apt update && sudo apt upgrade -y
Now, let’s get started with the setup process of LAMP.
Install Apache on Debian 12
Apache is included in Debian’s official package repository by default, so installation becomes simple. Follow the steps below to get Apache up and running –
=> Install Apache
Use the following command to install Apache. It gets the latest version of Apache and installs it on your server.
sudo apt install apache2 -y
=> Verify that the installed Apache version is set up correctly after installation. For that, check its version –
sudo apachectl -v
The output should display details about the Apache version and its build date.
=> Start the Apache Service
Start serving web pages by starting the Apache service with this command –
sudo systemctl start apache2
This command ensures that Apache is actively running on your server.
=> Enable Apache to Start on Boot
Enable Apache to launch automatically so that you need not start it manually every time the server reboots –
sudo systemctl enable apache2
This step makes sure Apache starts whenever your server is turned on.
=> Check Apache Service Status
Verify whether Apache is running properly with the following command –
sudo systemctl status apache2
You should see an output showing the service as active and running if Apache is running.
Installing MySQL on Debian 12
This guide will take you through every step to get MySQL running on your server.
Step 1 – Add the MySQL APT Repository
=> Download the latest MySQL repository setup file using the following command –
sudo wget https://dev.mysql.com/get/mysql-apt-config_0.8.32-1_all.deb
You need to get the most up-to-date version of MySQL.
=> Then, install the downloaded package –
sudo dpkg -i mysql-apt-config_0.8.32-1_all.deb
This step configures your system to fetch MySQL from the official repositories.
=> Select MySQL Server & Cluster and press Enter when prompted. Next, choose the version of MySQL you want to install. (The recommended version is mysql-8.4-lts.)
Press Enter to confirm your selection and save changes.
Step 2 – Update Package List and Install MySQL
=> Refresh the package list so that your system recognizes the newly added MySQL repository –
sudo apt update
=> Install the MySQL server package with all required dependencies –
sudo apt install mysql-server -y
Step 3 – Set Up the Root User Password
- You will be prompted to set a password for the root database user. Enter a strong password and press Enter.
- Re-enter the password to confirm it.
Step 4 – Verify MySQL Installation
=> Check the installed MySQL version with this command –
mysql --version
A sample output may look like this –
mysql Ver 8.4.2 for Linux on x86_64 (MySQL Community Server - GPL)
=> Start the MySQL service –
sudo systemctl start mysql
=> Enable MySQL to start automatically when the server boots –
sudo systemctl enable mysql
=> Verify that MySQL is running properly –
sudo systemctl status mysql
You should see a message stating “MySQL Community Server is operational”. This means everything is working fine.
Step 5 – Secure the MySQL Installation
=> Run the security script to remove unsafe default settings –
sudo mysql_secure_installation
- Enter the root password (you set earlier) when you are prompted.
- Type ‘Y’ for password validation. This ensures that all user passwords meet security
- standards.Choose a password validation level –
0 (LOW) – Minimum length of 8 characters.
1 (MEDIUM) – Requires numbers, uppercase letters, and special characters.
2 (STRONG) – Includes dictionary checks for extra security. - Enter 2 for maximum security and press Enter.
- Type N – when asked to change the root password. This will keep the existing one.
- Type Y to remove anonymous users.
- Select Y to disallow root login remotely.
- Y to delete the test database for security.
- Again type Y to reload privileges to apply the changes.
Installing and Configuring PHP on Debian 12
PHP must be installed correctly with PHP-FPM (FastCGI Process Manager) for better performance. Also, it needs proper configuration for seamless communication between Apache and PHP.
Step 1 – Install PHP and PHP-FPM
=> Run the following command to install PHP and FPM. This ensures that PHP scripts are processed efficiently.
sudo apt install php php-fpm -y
=> Install additional PHP modules to enable database interaction and other functionalities –
sudo apt install php-mysql php-cli libapache2-mod-php -y
=> Check the installed PHP version to confirm successful installation with the below command –
php -v
Step 2 – Start and Enable PHP-FPM Service
=> This command activates PHP-FPM so that Apache can process PHP files.
sudo systemctl start php8.2-fpm
=> Ensuring PHP-FPM starts automatically prevents downtime after a server restarts.
sudo systemctl enable php8.2-fpm
=> Check PHP-FPM status to confirm whether the PHP-FPM service is running properly.
sudo systemctl status php8.2-fpm
Step 3 – Configure PHP-FPM for Apache
=> Apache must communicate with PHP-FPM for processing PHP scripts. Activate the FastCGI module for the same –
sudo a2enmod proxy_fcgi
=> Check active PHP-FPM socket path. The below command verifies the Unix socket used by PHP-FPM.
ss -pl | grep php
The output will display the active socket path, typically /run/php/php8.2-fpm.sock.
=> Enable PHP-FPM Configuration for Apache –
sudo a2enconf php8.2-fpm
=> Restart Apache for Changes to Take Effect –
sudo systemctl restart apache2
Step 4 – Modify PHP-FPM Configuration
=> Open PHP-FPM Configuration File –
Use a text editor to modify the PHP-FPM pool settings.
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
=> Ensure the following values are correctly assigned in the file
[www] user = www-data group = www-data listen.owner = www-data listen.group = www-data listen = /run/php/php8.2-fpm.sock
=> Adjust Process Management Settings
Modify the following directives based on your server resources.
pm = dynamic pm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 10
=> Save and Exit the File
=> Restart PHP-FPM Service to Apply Changes
sudo systemctl restart php8.2-fpm
Configure Apache with PHP-FPM on Debian 12
Apache can process PHP scripts separately from the web server with PHP-FPM (FastCGI Process Manager). This improves performance and reduces resource usage.
To make this setup work, Apache needs to communicate with PHP-FPM using the proxy_fcgi module and a Unix socket. Below are the steps to configure Apache with PHP-FPM on Debian 12.
1 Create an Apache Virtual Host Configuration
Apache uses virtual hosts to serve websites, so you need to create a new virtual host configuration file for your application.
Open the Apache configuration directory and create a new file –
sudo nano /etc/apache2/sites-available/website.conf
Next, add the following configuration (replacing app.example.com with your actual domain name and [email protected] with your administrator email) –
<VirtualHost *:80> ServerAdmin [email protected] ServerName app.example.com DocumentRoot /var/www/html DirectoryIndex index.html index.php <Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <FilesMatch \.php$> SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/" </FilesMatch> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
2 Understand the Configuration
Handle each line in the virtual host file carefully, as each of them plays a role in handling requests correctly –
- <VirtualHost *:80>
Means it configures Apache to listen on port 80 for incoming HTTP requests. - ServerAdmin [email protected]
The admin email where server errors will be reported - ServerName app.example.com
The domain name to which this configuration applies. - DocumentRoot /var/www/html
Tells Apache where to find the website’s files. - DirectoryIndex index.html index.php
which file should be loaded when a visitor accesses the root directory. - <Directory /var/www/html>
Sets rules for the web root directory - <FilesMatch \.php$>
This directs Apache to handle .php files using PHP-FPM. - SetHandler “proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/”
Configures Apache to pass PHP requests to the PHP-FPM service - ErrorLog and CustomLog
Location where Apache stores error and access logs.
3 Disable the Default Apache Virtual Host Configurations
sudo a2dissite 000-default
4 Activate the New Virtual Host
Activate the new configuration for your website –
sudo a2ensite website
5 Test Apache Configuration
Check if there are any syntax errors in the configuration before restarting Apache –
sudo apachectl configtest
Syntax OK output means everything is set up correctly.
6 Restart Apache
Apply the changes by restarting the Apache service –
sudo systemctl restart apache2
7 HTTP Traffic Through Firewall
Ensure Apache can receive traffic on port 80 if your firewall is enabled –
sudo ufw allow 80/tcp
=> Reload the firewall to apply changes –
sudo ufw reload
8 Test PHP-FPM Integration
You need to confirm that Apache and PHP are working together. Create a PHP test file for the same.
=> Create a new index.php file in your web root directory –
sudo touch /var/www/html/index.php
=> Add the following PHP code
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/index.php
=> Open your browser and go to –
http://app.example.com/index.php
You should see a PHP information page displaying the server configuration. This means everything is working.
Configure Security With Server
Apache runs on HTTP port 80 by default so it transmits data in plain text. This can expose sensitive information to attackers.
You must enable HTTPS by setting up an SSL certificate and securing Apache with a firewall. Below are the steps to configure your server properly and protect your website –
Configuring the Uncomplicated Firewall (UFW)
UFW (Uncomplicated Firewall) is a simple tool to control network traffic. It ensures that only authorized connections are allowed.
=> Make sure your website is accessible so allow HTTP (port 80) and HTTPS (port 443):
sudo ufw allow 80/tcp sudo ufw allow 443/tcp
=> Reload the firewall to apply changes
sudo ufw reload
=> Verify the firewall status
sudo ufw status
You will see rules allowing traffic on ports 80 and 443 if configured correctly.
Generating an SSL Certificate with Let’s Encrypt
=> Install Certbot for Apache. It is a free tool that automates SSL certificate installation –
sudo apt install certbot python3-certbot-apache -y
=> Generate an SSL certificate
Replace app.example.com with your actual domain name:
sudo certbot --apache --agree-tos --redirect --email [email protected] -d app.example.com
=> Verify SSL certificate renewal
Certificates expire in 90 days. Certbot automatically renews them, but you can test the process manually.
sudo certbot renew --dry-run
=> Restart Apache to apply changes
sudo systemctl restart apache2
=> Test your website’s SSL setup
Open your browser and visit:
https://app.example.com
You will see a padlock icon in the address bar if everything is configured correctly. This indicates a secure connection.
Testing the Installation with a Sample Database Application
=> Log in to MySQL
mysql -u root -p
=> Create a new database as a sample
CREATE DATABASE CantechDB; USE CantechDB;
=> Next, run the below to create a database user
CREATE USER 'db_user'@'localhost' IDENTIFIED BY 'StrongP@ssw0rd!'; GRANT ALL PRIVILEGES ON CantechDB.* TO 'db_user'@'localhost'; FLUSH PRIVILEGES;
=> Exit MySQL
exit;
=> Create a PHP script to insert data
sudo nano /var/www/html/insert.php
=> Add the following PHP code –
<?php $conn = new mysqli("localhost", "db_user", "StrongP@ssw0rd!", "CantechDB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $conn->query("CREATE TABLE IF NOT EXISTS CantechTable (id INT AUTO_INCREMENT PRIMARY KEY, message VARCHAR(255))"); $conn->query("INSERT INTO CantechTable (message) VALUES ('Hello from Cantech!')"); echo "Record added!"; $conn->close(); ?>
=> Save and close the file.
This PHP application connects to the MySQL database as db_user. It checks if the CantechTable table exists in the VultrDB database and creates a new one if not.
A successful connection gives a “Greetings from Cantech” record to the table.
=> Create a script to display data
sudo nano /var/www/html/display.php
=> Add this code –
<?php $conn = new mysqli("localhost", "db_user", "StrongP@ssw0rd!", "CantechDB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = $conn->query("SELECT * FROM CantechTable"); while ($row = $result->fetch_assoc()) { echo "<h1>" . $row["id"] . " : " . $row["message"] . "</h1><br>"; } $conn->close(); ?>
=> Save and close the file.
=> Test the scripts in your browser
Insert Data: http://app.example.com/insert.php
View Data: http://app.example.com/display.php
“Hello from Cantech!” displayed means your Apache, MySQL, and PHP setup is working perfectly.
Conclusion
You have now installed all the necessary components with LAMP stack on Debian 12 for dynamic web development. You are now ready to deploy full-fledged websites, applications, and databases with ease.