FedoraRHEL Based

How To Install LAMP Stack on Fedora 42

Install LAMP Stack on Fedora 42

In this tutorial, we will show you how to install LAMP on Fedora 42. The LAMP stack represents one of the most popular open-source web development environments, providing a robust foundation for hosting dynamic websites and web applications. LAMP stands for Linux, Apache, MySQL/MariaDB, and PHP – a powerful combination that works seamlessly together to deliver reliable web services. In this comprehensive guide, we’ll walk through the complete process of installing and configuring a LAMP stack on Fedora 42, the latest version of this cutting-edge Linux distribution.

Whether you’re a system administrator setting up a production server, a web developer creating a local development environment, or a Linux enthusiast expanding your technical skills, this guide will provide you with detailed instructions to get your LAMP stack up and running efficiently. By the end, you’ll have a fully functional web server environment capable of hosting everything from simple blogs to complex web applications.

Prerequisites

Before diving into the installation process, ensure your system meets the necessary requirements for a smooth LAMP stack deployment on Fedora 42:

  • A system running Fedora 42 with at least 2GB RAM and 20GB disk space
  • Root access or a user account with sudo privileges
  • Basic familiarity with Linux command-line operations
  • Active internet connection for downloading packages
  • Updated package repositories

For optimal performance, especially in production environments, consider allocating additional resources based on your anticipated workload. While a minimal LAMP stack can run on modest hardware, applications with heavy traffic or database operations will benefit from more RAM and faster storage.

System Preparation

Proper system preparation ensures a smooth installation process and optimal performance of your LAMP stack. Follow these essential steps to prepare your Fedora 42 system:

First, update your package repository information and perform a full system upgrade to ensure you have the latest software versions:

sudo dnf clean all
sudo dnf check-update
sudo dnf upgrade -y

Setting a proper hostname helps with system identification and network configuration:

sudo hostnamectl set-hostname your-server-name

Install essential development tools and utilities that will be needed during the installation process:

sudo dnf groupinstall "Development Tools" -y
sudo dnf install wget curl vim -y

Ensure your system time is synchronized correctly, which is crucial for proper logging and certificate validation:

sudo dnf install chrony -y
sudo systemctl enable chronyd
sudo systemctl start chronyd
sudo chronyc tracking

Verify your network connectivity and available disk space before proceeding:

ping -c 3 google.com
df -h

These preparation steps ensure your Fedora 42 system has all the necessary updates and utilities for a successful LAMP stack installation.

Installing Apache Web Server

Apache HTTP Server is the “A” in LAMP and serves as the foundation of our web server environment. It’s renowned for its reliability, flexibility, and extensive module ecosystem. Here’s how to install and configure Apache on Fedora 42:

Install Apache using DNF:

sudo dnf install httpd -y

Once installation completes, start the Apache service and enable it to launch automatically at system boot:

sudo systemctl start httpd
sudo systemctl enable httpd

Verify that the service is running correctly:

sudo systemctl status httpd

You should see output indicating that the service is active and running.

Configure the firewall to allow HTTP (port 80) and HTTPS (port 443) traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Test your Apache installation by opening a web browser and navigating to your server’s IP address:

http://your_server_ip

You should see the default Apache test page, indicating successful installation.

Apache’s main configuration files are located in /etc/httpd/. The primary configuration file is /etc/httpd/conf/httpd.conf, while additional module configurations are stored in /etc/httpd/conf.d/. Familiarize yourself with these locations, as we’ll be modifying them later when integrating with PHP.

Some useful Apache management commands include:

sudo systemctl stop httpd      # Stop Apache
sudo systemctl restart httpd   # Restart Apache
sudo systemctl reload httpd    # Reload configuration without restarting
apachectl configtest           # Test configuration syntax

Installing MariaDB Database Server

MariaDB, a community-developed fork of MySQL, provides the database functionality in our LAMP stack. It offers improved performance, additional storage engines, and enhanced security features compared to MySQL while maintaining compatibility. Here’s how to install and configure MariaDB on Fedora 42:

Install MariaDB server using DNF:

sudo dnf install mariadb-server -y

Start the MariaDB service and enable it to launch at system boot:

sudo systemctl start mariadb
sudo systemctl enable mariadb

Verify the service is running:

sudo systemctl status mariadb

Secure your MariaDB installation using the included security script:

sudo mysql_secure_installation

This script will guide you through several security settings:

  • Setting a root password (recommended)
  • Removing anonymous users
  • Disallowing root login remotely
  • Removing the test database
  • Reloading privilege tables

For all these options, it’s generally recommended to answer “Y” (yes) for enhanced security.

To test your MariaDB installation, log in to the database server:

mysql -u root -p

You’ll be prompted for the root password you set earlier. Once logged in, create a test database and user:

CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

The main configuration file for MariaDB is located at /etc/my.cnf with additional configuration files in /etc/my.cnf.d/. You can adjust various settings to optimize performance based on your system resources and expected workload.

Installing PHP and Extensions

PHP is the “P” in LAMP and serves as the scripting language that processes dynamic content on your web server. Fedora 42 provides PHP 8.x with numerous improvements in performance and security. Here’s how to install PHP and essential extensions:

Install PHP and common extensions:

sudo dnf install php php-mysqlnd php-gd php-cli php-curl php-mbstring php-xml php-json php-zip php-fpm php-intl php-bcmath -y

This command installs PHP along with several commonly used extensions:

  • php-mysqlnd: MySQL Native Driver for database connectivity
  • php-gd: Graphics library for image manipulation
  • php-curl: Client URL library for making HTTP requests
  • php-mbstring: Multibyte string handling
  • php-xml: XML parsing
  • php-json: JSON manipulation
  • php-zip: ZIP file handling
  • php-fpm: FastCGI Process Manager
  • php-intl: Internationalization functions
  • php-bcmath: Arbitrary precision mathematics

After installation, restart Apache to integrate with PHP:

sudo systemctl restart httpd

Configure PHP by editing the php.ini file:

sudo nano /etc/php.ini

Key settings to adjust for development environments include:

display_errors = On
display_startup_errors = On
error_reporting = E_ALL
memory_limit = 128M
post_max_size = 64M
upload_max_filesize = 64M
max_execution_time = 300
date.timezone = Your/Timezone

For production environments, consider disabling error display and setting more restrictive limits.

Verify your PHP installation by creating a test file:

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

Add the following content:

<?php phpinfo(); ?>

Access this file in your web browser:

http://your_server_ip/info.php

You should see a page displaying detailed information about your PHP installation and configuration. This confirms that PHP is working correctly with Apache.

Configuring LAMP Components

Proper configuration ensures that all components of your LAMP stack work together efficiently. This section covers essential configuration tasks to integrate Apache, PHP, and MariaDB.

Apache and PHP Integration

Apache needs to know how to handle PHP files. This integration is typically handled automatically during installation, but you should verify it:

Check that the PHP module is loaded in Apache by examining:

sudo nano /etc/httpd/conf.d/php.conf

This file should contain directives that tell Apache to process .php files using the PHP interpreter.

If you’re using PHP-FPM for improved performance, configure it by editing:

sudo nano /etc/httpd/conf.d/php-fpm.conf

Virtual Hosts Configuration

Virtual hosts allow you to host multiple websites on a single server. Create a virtual host configuration:

sudo nano /etc/httpd/conf.d/vhost.conf

Add a basic virtual host configuration:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/example
    ErrorLog /var/log/httpd/example_error.log
    CustomLog /var/log/httpd/example_access.log combined
    
    <Directory /var/www/html/example>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Create the document root directory:

sudo mkdir -p /var/www/html/example
sudo chown -R apache:apache /var/www/html/example

SELinux Configuration

Fedora uses SELinux for enhanced security. Configure it properly to allow Apache to access your web files:

sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
sudo restorecon -Rv /var/www/html

If you’re storing files outside the default directories:

sudo setsebool -P httpd_can_network_connect_db 1
sudo setsebool -P httpd_can_network_connect 1

After making these configuration changes, test your Apache configuration and restart the service:

sudo apachectl configtest
sudo systemctl restart httpd

Testing the Complete LAMP Stack

To verify that all components of your LAMP stack are working together correctly, create a test script that connects to your database:

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

Add the following content (adjust credentials as needed):

<?php
$dbhost = 'localhost';
$dbuser = 'testuser';
$dbpass = 'password';
$dbname = 'testdb';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Database connection successful!";

// Create a test table
$sql = "CREATE TABLE IF NOT EXISTS test_table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
    echo "<br>Test table created successfully";
} else {
    echo "<br>Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Access this file in your browser:

http://your_server_ip/dbtest.php

If you see “Database connection successful!” and “Test table created successfully,” your LAMP stack is properly configured and operational.

Security Best Practices

Securing your LAMP stack is crucial, especially for production environments. Implement these security measures to protect your web server:

Apache Security

Configure Apache with enhanced security headers:

sudo nano /etc/httpd/conf.d/security.conf

Add these directives:

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

PHP Security

Enhance PHP security by modifying php.ini:

sudo nano /etc/php.ini

Change these settings:

expose_php = Off
display_errors = Off
log_errors = On
allow_url_fopen = Off
allow_url_include = Off
session.cookie_httponly = 1
session.cookie_secure = 1

Database Security

Implement principle of least privilege for database users:

mysql -u root -p
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON application_db.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

File Permissions

Set secure file permissions for web content:

sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;
sudo chown -R apache:apache /var/www/html

Firewall Configuration

Configure firewalld to allow only necessary services:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --permanent --add-port=22/tcp
sudo firewall-cmd --reload

Regularly update all components of your LAMP stack to patch security vulnerabilities:

sudo dnf update httpd mariadb-server php -y

Performance Optimization

Optimize your LAMP stack for improved performance with these configuration adjustments:

Apache Optimization

Edit the Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Optimize these settings:

# Enable keep-alive connections
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

# Enable compression
LoadModule deflate_module modules/mod_deflate.so
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript

# Enable caching
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresDefault "access plus 2 days"
</IfModule>

MariaDB Optimization

Edit the MariaDB configuration:

sudo nano /etc/my.cnf.d/server.cnf

Add these optimizations in the [mysqld] section:

[mysqld]
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
query_cache_size = 32M
query_cache_limit = 2M
key_buffer_size = 32M
max_connections = 150

Adjust these values based on your server’s available memory.

PHP Optimization

Enable PHP OpCache by editing:

sudo nano /etc/php.d/10-opcache.ini

Optimize these settings:

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

Configure PHP-FPM for better performance:

sudo nano /etc/php-fpm.d/www.conf

Adjust these settings:

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

After making these changes, restart all services:

sudo systemctl restart httpd
sudo systemctl restart php-fpm
sudo systemctl restart mariadb

Troubleshooting Common Issues

Even with careful installation, issues can arise. Here are solutions to common LAMP stack problems:

Apache Not Starting

If Apache fails to start, check the error log:

sudo systemctl status httpd
sudo journalctl -xe
sudo cat /var/log/httpd/error_log

Common issues include:

  • Port conflicts: Ensure nothing else is using port 80/443
  • Configuration syntax errors: Run apachectl configtest
  • Permission problems: Check SELinux contexts with ls -Z /var/www/html

PHP Processing Errors

If PHP files are not being processed correctly:

  1. Verify PHP is installed: php -v
  2. Check if Apache recognizes PHP: Look for php.conf in /etc/httpd/conf.d/
  3. Enable error reporting in php.ini:
    display_errors = On
    error_reporting = E_ALL

If you see a blank page or 500 error when accessing PHP files, check PHP error logs:

sudo cat /var/log/php-fpm/www-error.log

Database Connection Issues

If your application cannot connect to MariaDB:

  1. Verify MariaDB is running: sudo systemctl status mariadb
  2. Test connection from command line: mysql -u user -p
  3. Check user privileges:
    SHOW GRANTS FOR 'user'@'localhost';
  4. Ensure the database user has the correct permissions

SELinux may block database connections from web applications. Enable the necessary boolean:

sudo setsebool -P httpd_can_network_connect_db 1

Permission Problems

If you encounter “Permission denied” errors in your logs:

sudo chown -R apache:apache /var/www/html
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;

For SELinux-related issues:

sudo restorecon -Rv /var/www/html

Log file locations for debugging:

  • Apache logs: /var/log/httpd/
  • PHP logs: /var/log/php-fpm/ or Apache error log
  • MariaDB logs: /var/log/mariadb/

Advanced Configuration

Enhance your LAMP stack with these advanced configurations:

Installing phpMyAdmin

phpMyAdmin provides a web interface for managing your MariaDB databases:

sudo dnf install phpMyAdmin -y

Secure phpMyAdmin by editing its Apache configuration:

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

Add access restrictions:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   <IfModule mod_authz_core.c>
     # Apache 2.4
     Require local
     Require ip 192.168.1.0/24  # your trusted network
   </IfModule>
</Directory>

Setting Up SSL/TLS

Secure your web server with HTTPS:

sudo dnf install mod_ssl openssl -y

Generate a self-signed certificate (for testing):

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/pki/tls/private/apache-selfsigned.key -out /etc/pki/tls/certs/apache-selfsigned.crt

Configure SSL in Apache:

sudo nano /etc/httpd/conf.d/ssl.conf

Update the certificate paths and add security enhancements:

SSLCertificateFile /etc/pki/tls/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/pki/tls/private/apache-selfsigned.key
SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
SSLHonorCipherOrder on

For production environments, consider using Let’s Encrypt for free, trusted certificates.

Database Backup Strategy

Set up automated database backups:

sudo nano /etc/cron.daily/mariadb-backup

Add this script:

#!/bin/bash
BACKUP_DIR="/var/backups/mariadb"
DATETIME=$(date +%Y-%m-%d_%H-%M-%S)
BACKUP_FILE="$BACKUP_DIR/all-databases_$DATETIME.sql.gz"

# Create backup directory if it doesn't exist
mkdir -p $BACKUP_DIR
chmod 700 $BACKUP_DIR

# Perform backup
mysqldump --all-databases -u root -p'root_password' | gzip > $BACKUP_FILE
chmod 600 $BACKUP_FILE

# Delete backups older than 7 days
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete

Make the script executable:

sudo chmod +x /etc/cron.daily/mariadb-backup

Congratulations! You have successfully installed LAMP. Thanks for using this tutorial for installing the LAMP Stack on Fedora 42 Linux system. For additional help or useful information, we recommend you check the Fedora 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