Product docs and API reference are now on Akamai TechDocs.
Search product docs.
Search for “” in product docs.
Search API reference.
Search for “” in API reference.
Search Results
 results matching 
 results
No Results
Filters
Install a LAMP Stack on Rocky Linux 9 (CentOS 8 Replacement)
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
If you’re moving from CentOS 8 to a compatible operating system, this guide walks you through installing a LAMP stack on Rocky Linux 9. The process and commands are nearly identical to what you’re used to on CentOS 8 making migration straightforward.
CentOS 8 reached end-of-life in December 2021 and is no longer supported or safe for production use. Rocky Linux 9 is the recommended replacement–a free, open-source, enterprise-grade OS created by the original CentOS founder. It’s fully compatible with RHEL 9 and serves as a drop-in replacement with the same package manager (dnf) and system structure.
What is a LAMP Stack?
A LAMP stack is a collection of four open-source software components that work together to run dynamic websites and web applications. The name is an acronym:
- Linux: The operating system running the server
- Apache: The web server software that delivers web pages to visitors and handles web requests
- MariaDB: Database server
- PHP: The programming language that processes logic and creates dynamic content
Prerequisites
Before installing the LAMP stack, ensure you have:
- A server or virtual machine with Rocky Linux 9 already installed
- Root access or a user account with sudo privileges
- Basic familiarity with the Linux command line
- An active internet connection
Install Apache
Apache is the web server component that handles HTTP requests and serves web pages.
Update the system package index:
sudo dnf update -y
If the system is already fully updated, you might see Nothing to do. or Complete!. Either message indicates success. The key is that there are no error messages and the command returns you to the command prompt.
Install Apache:
sudo dnf install httpd -y
At the end you should see the key indicators of success: httpd-[version] [and other packages]
Complete!
Start the Apache service:
sudo systemctl start httpd
Silently returns to the prompt when successful.
Enable Apache to start automatically on boot:
sudo systemctl enable httpd
If you see Create symlink... automatic reboot is enabled.
Verify Apache is running:
sudo systemctl status httpdYou should see output indicating the service is
active (running):● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled) Active: active (running) since Mon 2025-10-13 10:23:45 UTC; 5s ago
To exit and get back to your command prompt:
Press q (for quit) to END.
Test Apache
After configuring the firewall, test Apache by visiting your server’s IP address http://your_server_ip (replace with your actual IP address). You should see the default Rocky Linux Apache test page.
Install MariaDB
MariaDB is the database component that stores and manages data for your applications.
Install MariaDB server:
sudo dnf install mariadb-server -y
You will see “Complete!” when it has successfully installed.
Start the MariaDB service:
sudo systemctl start mariadbEnable MariaDB to start automatically on boot:
sudo systemctl enable mariadbSecure the MariaDB installation by running the security script:
sudo mysql_secure_installationFollow the prompts:
- Press **Enter** when asked for the current root password (there isn't one yet)
Type Y to change the root password, then enter and confirm a strong password
mysql -u root -p)
- Create databases and users
- Perform database administration tasks- Type Y to remove anonymous users
- Type Y to disallow root login remotely
- Type Y to remove the test database
- Type Y to reload privilege tables
Verify MariaDB is running:
sudo systemctl status mariadbYou should see output indicating the service is “active (running)”. Press q (for quit) to END.
Install PHP
PHP is the programming language that makes websites interactive and personalized. It processes user actions (like logging in, submitting forms, or searching) and creates customized web pages based on data stored in the database.
Install PHP and common modules:
sudo dnf install php php-mysqlnd php-fpm php-opcache php-gd php-xml php-mbstring -yThis installs:
php: Core PHP interpreterphp-mysqlnd: MySQL Native Driver for database connectivityphp-fpm: FastCGI Process Manager for better performancephp-opcache: Opcode cache for improved performancephp-gd: Graphics library supportphp-xml: XML processing supportphp-mbstring: Multi-byte string support
Restart Apache to load PHP:
sudo systemctl restart httpd
Returns to the prompt silently when successful.
Verify the PHP version:
php -vYou should see output showing PHP version 8.0 or higher:
PHP 8.0.30 (cli) (built: Aug 3 2023 17:13:08) ( NTS gcc x86_64 )
Test PHP Processing
Create a test PHP file to verify that Apache can process PHP code correctly.
- Create a PHP info file:
sudo nano /var/www/html/info.phpAdd the following content:
- File: /var/www/html/info.php
1 2 3 4<?php phpinfo(); ?>
Save and exit the file (Ctrl+X, then Y, then Enter).
Set appropriate permissions:
sudo chown apache:apache /var/www/html/info.phpSilently returns to the prompt when successful.
- Visit
http://your_server_ip/info.phpin a web browser. You should see a detailed PHP information page showing PHP version, loaded modules, and configuration.
Remove the info.php file after testing, as it exposes sensitive system information:
sudo rm /var/www/html/info.phpTest Database Connectivity
Verify that PHP can connect to MariaDB. This confirms all three components of your LAMP stack are working together.
Create a test database:
sudo mysql -u root -pEnter the root password you created during
mysql_secure_installation.You should see the MariaDB prompt:
MariaDB [(none)]>The `[(none)]` indicates you're not currently using any specific database, which is expected at this point.
At this MariaDB prompt, run these commands:
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;Create a PHP test file:
sudo nano /var/www/html/db_test.phpAdd the following content:
- File: /var/www/html/db_test.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17<?php $servername = "localhost"; $username = "test_user"; $password = "secure_password"; $dbname = "test_db"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully to database!"; $conn->close(); ?>
Visit
http://your_server_ip/db_test.phpin a browser. You should see “Connected successfully to database!”Clean up test files:
sudo rm /var/www/html/db_test.php sudo mysql -u root -p -e "DROP DATABASE test_db; DROP USER 'test_user'@'localhost';"
Enter your MariaDB root password when prompted. The command will silently return to the prompt when successful, having removed the test database and test user.
Security Hardening for Production
The basic installation above is suitable for development and testing only. Production environments require immediate security hardening. Within minutes of exposing a server to the internet, automated bots will begin probing for vulnerabilities. A newly created server can receive hundreds of failed login attempts within the first hour.
Modern servers face constant, automated attacks from across the internet. This section implements essential security measures to protect your LAMP stack from common threats including brute-force attacks, unauthorized access, and application-level vulnerabilities.
Security Prerequisites
Before hardening the LAMP stack, secure SSH access to your server. SSH is the most frequently attacked service on internet-facing systems–as mentioned, new servers often receive hundreds of unauthorized login attempts within the first hour.
Complete these essential security steps first:
- Securing Your ServerSSH Hub - Create non-root user, configure SSH keys, disable root login
- How to Use Fail2ban to Secure Your Server - Automatically block repeated failed login attempts.
- [What is Fail2Ban with Setup & Configuration? (Detailed Guide)](https://runcloud.io/blog/what-is-fail2ban)
These guides must be completed before proceeding with LAMP stack hardening to ensure your server has basic protection against the most common attack vectors.
Configure Firewall
Rocky Linux 9 uses firewalld to manage network traffic. A properly configured firewall defines your network perimeter, blocking all traffic except explicitly allowed services. This minimizes exposure and prevents unauthorized access.
- Verify firewalld is running:
sudo systemctl status firewalldThe output should show enabled and active (running). If firewalld is not running or not enabled to start on boot, enable and start it:
sudo systemctl enable --now firewalld- Allow HTTP and HTTPS for web traffic for your web server:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=httpsThe --permanent flag ensures these rules persist across reboots.
- If you changed SSH to a non-standard port (recommended for security), allow it:
sudo firewall-cmd --permanent --add-port=2222/tcp- Reload the firewall to apply changes:
sudo firewall-cmd --reload- Confirm that
http,https, andsshappear under services, and any custom SSH port appears under ports.
sudo firewall-cmd --list-all public (active)
services: cockpit dhcpv6-client http https ssh
ports:2222 with whatever port number you configured for SSH. Common non-standard SSH ports include 2222, 2200, or any port above 1024 that isn’t in use.Configure SELinux
Rocky Linux 9 has SELinux (Security-Enhanced Linux) enabled by default. SELinux provides mandatory access control, limiting the damage an attacker can cause even if they compromise a service. Never disable SELinux in production environments.
- Verify SELinux is enforcing:
getenforce Enforcing- If your web applications need to connect to remote databases or send email, configure the appropriate SELinux booleans:
# Allow Apache to connect to remote databases
sudo setsebool -P httpd_can_network_connect_db 1
# Allow Apache to send email
sudo setsebool -P httpd_can_sendmail 1-P flag makes the setting persistent across reboots.Then verify both:
getsebool httpd_can_network_connect_db httpd_can_sendmailExpected output:
httpd_can_network_connect_db --> on
httpd_can_sendmail --> on- Set correct SELinux contexts for web content:
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
sudo restorecon -Rv /var/www/htmlCheck the SELinux context of the directory:
ls -Z /var/www/html
ls -Zd /var/www/html system_u:object_r:httpd_sys_content_t:s0 /var/www/htmlThe httpd_sys_content_t context allows Apache to serve files from this directory.
Secure Apache Configuration
- Hide Apache version information by editing the Apache configuration:
sudo nano /etc/httpd/conf/httpd.confAdd or modify these lines:
- File: /etc/httpd/conf/httpd.conf
1 2 3ServerTokens Prod ServerSignature Off
Disable directory listing by ensuring this line exists in your configuration:
- File: /etc/httpd/conf/httpd.conf
1 2Options -Indexes FollowSymLinks
Restart Apache to apply changes:
sudo apachectl configtest sudo systemctl restart httpd sudo systemctl status httpd
Expected output:
- First command:
Syntax OK - Second command: Silent return to prompt (no output)
- Third command: Shows
active (running)andStarted The Apache HTTP Server
Secure MariaDB
- Edit the MariaDB configuration:
sudo nano /etc/my.cnf.d/mariadb-server.cnfAdd these security settings under the
[mysqld]section:- File: /etc/my.cnf.d/mariadb-server.cnf
1 2 3 4[mysqld] bind-address = 127.0.0.1 local-infile = 0
Restart MariaDB:
sudo systemctl restart mariadb- Verify MariaDB is running:
sudo systemctl status mariadbSecure PHP Configuration
- Edit the PHP configuration:
sudo nano /etc/php.iniModify these security-related settings:
- File: /etc/php.ini
1 2 3 4 5 6 7 8expose_php = Off display_errors = Off log_errors = On error_log = /var/log/php/error.log disable_functions = exec,passthru,shell_exec,system,proc_open,popen allow_url_fopen = Off allow_url_include = Off
Create the PHP log directory:
sudo mkdir -p /var/log/php
sudo chown apache:apache /var/log/php- Restart Apache:
sudo systemctl restart httpdInstall and Configure ModSecurity (Optional)
ModSecurity is a web application firewall (WAF) that provides additional protection against common web attacks.
- Install ModSecurity:
These steps enhance the security of your LAMP Stack on Rocky Linux 9, especially for production environments or public-facing servers.
sudo dnf install mod_security -yExpected output: The terminal will display a summary ending with “Complete!” indicating successful installation.
- Enable and start ModSecurity:
Restart Apache to load the ModSecurity module:
sudo systemctl restart httpdA silent return to the prompt indicates success.
- Verify ModSecurity is loaded:
To confirm that Mod Security is active, use the following command:
sudo httpd -M | grep securityThis lists all loaded Apache modules and filters for ModSecurity. If installed correctly, you should see:
security2_module (shared)apachectl -M. Using httpd -M is more reliable on Rocky Linux 9.For detailed ModSecurity configuration and rules:
Apache Modsecurity module: A practical guide - Sling Academy.
How to Install Modsecurity 2 OWASP CRS with Apache on Ubuntu 24.04/22.04/20.04 - LinuxCapable.
For advanced rule sets and customization, see the OWASP ModSecurity Core Rule Set and Sling Academy’s practical guide.
Enable Automatic Security Updates
Security vulnerabilities are discovered constantly. Manually checking for and applying updates creates dangerous gaps where your server remains vulnerable to known exploits. Automatic security updates ensure critical patches are applied promptly, reducing the window of exposure to attacks. This is essential for production servers that need continuous protection without manual intervention. So, it keeps the LAMP stack infrastructure (Apache, MariaDB, PHP, OS) patched and secure automatically.
- Install the
dnf-automaticpackage:
sudo dnf install dnf-automatic -yExpected output: The terminal will display a summary ending with “Complete!” indicating successful installation.
- Configure automatic updates by editing the configuration:
sudo nano /etc/dnf/automatic.confSet
apply_updatestoyes:- File: /etc/dnf/automatic.conf
1 2 3[commands] apply_updates = yes
Enable and start the automatic update timer:
sudo systemctl enable --now dnf-automatic.timerConfigure Log Rotation
Log rotation is enabled by default: Rocky Linux 9 includes logrotate as part of its base system, and it’s configured to rotate logs for common services like Apache (httpd) and MariaDB:
ls /etc/logrotate.d/Lists all service-specific rotation configs.
To see configuration files for
httpdandmariadb:
cat /etc/logrotate.d/httpd
cat /etc/logrotate.d/mariadbThese files define how logs are rotated-for example: weekly rotation, retention of four weeks, and compression of older logs.
Post-Install Best Practices
For production environments, implement regular backups:
- Database backups: Use
mysqldumpor MariaDB’s backup tools - Web content backups: Regularly backup
/var/www/html - Configuration backups: Backup
/etc/httpdand/etc/my.cnf.d - Off-site storage: Store backups in a separate location
Install SSL/TLS Certificate
For production websites, always use HTTPS with a valid SSL/TLS certificate.
Migration-Specific Considerations
If you’re migrating an existing site from CentOS 8:
Application Compatibility
- Test all applications on Rocky Linux 9 before going live
- Check PHP version compatibility (Rocky 9 may have newer PHP)
- Verify all PHP extensions are installed
Data Migration
- Export databases from CentOS 8:
mysqldump -u root -p --all-databases > backup.sql - Transfer web files:
rsync -avz /var/www/html/ user@new-server:/var/www/html/ - Import databases to Rocky Linux 9:
mysql -u root -p < backup.sql - Verify file permissions after transfer
Testing Checklist
- All pages load correctly
- Database connections work
- Forms submit properly
- File uploads function
- SSL certificate installed and working
- Redirects work correctly
- Cron jobs migrated and running
Conclusion
Rocky Linux 9 provides a stable, long-term CentOS 8 replacement with identical commands and structure. The LAMP stack installation is straightforward, but production deployment requires the security hardening steps outlined above.
Key takeaways:
- Installation process identical to CentOS 8
- Never disable SELinux - configure it properly
- Production hardening is mandatory, not optional
- Test thoroughly before migrating production workloads
Additional Resources
- Linode’s LAMP Installation Guide - Complete installation walkthrough
- Rocky Linux Official SELinux Documentation: - Applicable to Rocky Linux 9
- Rocky Linux Official ModSecurity/WAF Guide: - Advanced web application firewall
This page was originally published on