How to Set Up AWS EC2 Ubuntu Server with Apache, Multiple PHP Versions, MySQL, and Certbot
Overview
Introduction
Setting up a server on AWS EC2 Ubuntu involves configuring Apache, multiple PHP versions, MySQL, and SSL certificates for secure and efficient web hosting. This step-by-step guide will walk you through the process of setting up an EC2 instance, installing Apache and multiple PHP versions, configuring MySQL, and securing your websites with SSL via Certbot.
In this tutorial, we'll cover how to set up different PHP versions for different websites, manage databases using phpMyAdmin, and install Certbot to enable HTTPS on your domains. By the end, your AWS EC2 instance will be fully configured to handle multiple websites with varying PHP versions.
1. Launching an EC2 Instance
To get started, you'll need to launch an EC2 instance on AWS and choose Ubuntu as the operating system. Here’s how you do it:
- Login to AWS Console: Navigate to the EC2 dashboard.
- Launch an Instance: Select "Launch Instance" and choose the latest Ubuntu Server AMI.
- Choose Instance Type: For small-scale use, you can select
t2.micro
. - Configure Instance Settings: Set up instance details like storage, tags, and security group rules for HTTP (80), HTTPS (443), and SSH (22).
- Review and Launch: Confirm your settings and launch the instance.
After the instance is running, connect via SSH:
ssh -i /path/to/your/key.pem ubuntu@your-ec2-public-dns
2. Installing Apache
Apache is a reliable web server used to host websites. Install it with:
sudo apt update
This command updates the local package index on your system. It retrieves the latest package information from the repositories configured on your system. This step ensures that when you install or upgrade packages, you are getting the most recent versions available.
sudo apt install apache2
Apache HTTP Server (version 2) on your system. Apache is a widely used web server that enables you to host websites and serve web content.
sudo systemctl enable apache2
Configures the Apache service to start automatically at boot time. Using systemctl enable, you ensure that the Apache server will be up and running whenever the system starts, without needing to manually start it each time.
3. Installing MySQL
Next, install MySQL for managing your databases
Once more, use apt to obtain and install this software:
sudo apt install mysql-server
When asked, affirm the installation by entering Y and hitting ENTER.
After the installation is complete, it's advisable to run a security script that comes pre-installed with MySQL. This script will eliminate some insecure default settings and restrict access to your database system.
sudo mysql_secure_installation
You will receive a prompt to set up the VALIDATE PASSWORD PLUGIN.
The VALIDATE PASSWORD PLUGIN helps assess passwords and enhance security. It evaluates password strength and permits users to set only sufficiently secure passwords. Would you like to configure the VALIDATE PASSWORD plugin?
Press y or Y for Yes, or any other key for No.
If you answer "yes," you will be asked to pick a level of password validation. Keep in mind that if you choose 2 for the strongest level, you will get errors when trying to set any password that doesn't have numbers, uppercase and lowercase letters, and special characters.
sudo systemctl status mysql
There are three tiers of password validation policies:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
No matter if you chose to set up the VALIDATE PASSWORD PLUGIN, your server will next ask you to pick and confirm a password for the MySQL root user. This is different from the system root. The database root user is an admin with full access to the database system.
Even though the default way to log in as the MySQL root user doesn’t require a password, you should still set a strong password for extra security.
If you turned on password validation, you will see how strong the password is that you just entered. The server will then ask if you want to keep that password. If you like your current password, type Y for “yes” at the prompt.
Estimated strength of the password: 100
Would you like to proceed with the given password? (Press y or Y for Yes, any other key for No): y
For the remaining questions, press Y and then hit the ENTER key at each prompt. This will remove some anonymous users, delete the test database, disable remote root logins, and apply the new rules so that MySQL respects the changes right away.
When you're done, check if you can log in to the MySQL console by typing:
sudo mysql
This command will connect you to the MySQL server as the admin user, root. This is done using sudo when you run the command. Here’s an example of what the output might look like:
Output
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 9.0.0-0ubuntu4 (Ubuntu)
Copyright (c) 2000, 2024, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and its affiliates. Other names mentioned may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Enter \c to reset the current input statement.
mysql>
To exit the MySQL console, type:
exit
You might notice that you didn’t need to enter a password to connect as the root user, even though you set one up with the mysql_secure_installation script. This is because the default way to log in as the MySQL admin user uses unix_socket instead of a password.
While this may seem like a security risk, it actually makes the database server more secure. Only system users with sudo privileges can log in as the root MySQL user from the console or from applications running with the same permissions. This means you can’t use the root MySQL user to connect from your PHP application.
Having a password for the root MySQL account is a good backup, in case the authentication method changes from unix_socket to password.
For better security, it’s a good idea to create separate user accounts with limited privileges for each database, especially if you plan to host multiple databases on your server.
4. Installing Multiple PHP Versions
To serve websites with different PHP versions, first, add the necessary PHP repositories:
sudo add-apt-repository ppa:ondrej/php
Adds the Ondřej Surý PPA (Personal Package Archive) to your system, providing the latest PHP packages.
sudo apt update
Updates your package list to include the latest versions from the newly added PPA, ensuring you can install the most current packages.
sudo apt install php7.4 php7.4-fpm
Installs PHP 7.4 and PHP-FPM (FastCGI Process Manager) for PHP 7.4, allowing you to run applications using this version.
sudo apt install php8.0 php8.0-fpm
Installs PHP 8.0 and PHP-FPM for this version, providing the latest features and improvements.
sudo apt install php8.1 php8.1-fpm
Installs PHP 8.1 and PHP-FPM for this version, continuing to add more up-to-date PHP options.
sudo apt install php8.2 php8.2-fpm
Installs PHP 8.2 and PHP-FPM for this version, allowing for the latest enhancements and performance improvements.
sudo apt install php8.3 php8.3-fpm
Installs PHP 8.3 and PHP-FPM for this version, ensuring you have access to the most recent PHP features.
5. Installing phpMyAdmin
phpMyAdmin makes it easy to access and manage your MySQL database through a web interface. To install it, run the following command:
sudo apt-get install phpmyadmin
Next, follow these steps for each prompt:
- Press the "space" key to select
apache2 (*)
, then press the "tab" key and hit "enter" to confirm. - Select "Yes" to configure phpMyAdmin.
- Enter a password for phpMyAdmin.
By default, you cannot log in as the root user through phpMyAdmin. To enable this, follow these steps:
1. Log in to MySQL as the root user:
sudo mysql -u root -p
2. Change the root login to use a password by running this command:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_root_password';
3. Apply the changes by executing:
FLUSH PRIVILEGES;
Make sure to replace 'your_root_password'
with the password you created when installing MySQL.
6. Installing Certbot for SSL
To secure your websites with SSL (Secure Sockets Layer), you can use Certbot, which is a free, open-source tool that automates the process of obtaining and installing SSL certificates from Let’s Encrypt. Follow the steps below to install Certbot and set up SSL for your domain.
1: Install Certbot
Start by installing Certbot and the Apache plugin using the following command:
sudo apt install certbot python3-certbot-apache
- This command installs Certbot along with the necessary Python package for Apache.
2: Obtain an SSL Certificate
After installing Certbot, you can acquire an SSL certificate by executing the following command:
sudo certbot --apache
- This command initiates the process of obtaining an SSL certificate and automatically configures your Apache web server to use it.
3: Follow the Prompts
After running the command, follow the prompts provided by Certbot:
-
Select Your Domain: Certbot will list the domains it found on your server. Choose the domain(s) for which you want to enable HTTPS.
-
Agree to Terms of Service: You’ll need to agree to Let’s Encrypt’s terms of service. Make sure to read through the terms before accepting.
-
Enter Your Email Address: Provide an email address for important account notifications and recovery options. This is optional, but recommended.
-
Enable HTTPS: Certbot will ask if you want to redirect all HTTP traffic to HTTPS. It’s recommended to choose this option to ensure all traffic is secured.
4: Verify SSL Installation
After Certbot finishes, it will notify you that the SSL certificate has been successfully installed. You can verify that your website is accessible via HTTPS by visiting your domain in a web browser. Look for a padlock icon in the address bar, which indicates a secure connection.
5: Automatic Certificate Renewal
Let’s Encrypt certificates are valid for 90 days. Certbot sets up a cron job to automatically renew the certificates before they expire. You can manually test the renewal process by running:
sudo certbot renew --dry-run
This command simulates the renewal process to ensure that it will work correctly when the time comes.
7. Configuring Apache to Use Multiple PHP Versions
To run different versions of PHP on your Apache web server, you'll need to enable the PHP-FPM (FastCGI Process Manager) modules for each version you've installed. This allows Apache to handle PHP requests using the specified PHP version. Follow these steps:
1: Enable Required Modules
Start by enabling the necessary Apache modules that support PHP-FPM. Run the following commands:
sudo a2enmod proxy_fcgi setenvif
proxy_fcgi
: This module allows Apache to communicate with PHP-FPM via FastCGI. It acts as a bridge between Apache and PHP-FPM, enabling the server to process PHP scripts efficiently.setenvif
: This module is used to set environment variables based on request conditions. It helps in managing different PHP configurations based on the requests received.
2: Enable PHP-FPM Configurations
Next, enable the PHP-FPM configuration files for each installed PHP version. Run the following commands:
sudo a2enconf php7.4-fpm
sudo a2enconf php8.0-fpm
sudo a2enconf php8.1-fpm
sudo a2enconf php8.2-fpm
sudo a2enconf php8.3-fpm
Each command enables the corresponding PHP-FPM configuration:
php7.4-fpm
: Enables PHP 7.4 configuration, allowing Apache to handle PHP 7.4 requests.php8.0-fpm
: Enables PHP 8.0 configuration for requests using PHP 8.0.php8.1-fpm
: Enables PHP 8.1 configuration for requests using PHP 8.1.php8.2-fpm
: Enables PHP 8.2 configuration for requests using PHP 8.2.php8.3-fpm
: Enables PHP 8.3 configuration for requests using PHP 8.3.
3: Restart Apache
After enabling the necessary modules and configurations, restart Apache to apply the changes:
sudo systemctl restart apache2
This command reloads the Apache server, allowing it to recognize the newly enabled PHP-FPM configurations.
4: Verify Configuration
To ensure that Apache is properly configured to use multiple PHP versions, you can create a simple PHP file for testing.
1. Create a new PHP file in your web root directory (e.g., /var/www/html
):
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
2. Access the PHP file in your web browser:
Open a web browser and navigate to http://your-server-ip/info.php
http://your-domain.com/info.php
(replace your-server-ip
with your server's IP address). This will display the PHP information page.
Check the PHP version displayed on the page. You can create additional virtual hosts or use .htaccess
files to specify which PHP version to use for different directories or applications.
Create Virtual Hosts for Each Website
For website1.com
using PHP 8.0, create a virtual host configuration:
sudo nano /etc/apache2/sites-available/website1.conf
Add the following configuration:
<VirtualHost *:80> ServerAdmin webmaster@website1.com ServerName website1.com DocumentRoot /var/www/html/website1 <Directory /var/www/html/website1> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <FilesMatch \.php$> SetHandler "proxy:unix:/var/run/php/php8.0-fpm.sock|fcgi://localhost" </FilesMatch> ErrorLog /var/log/apache2/website1_error.log CustomLog /var/log/apache2/website1_access.log combined </VirtualHost>
Repeat these steps for additional websites, adjusting the PHP version as needed.
Enable Virtual Hosts and Restart Apache
Enable the new sites and restart Apache:
sudo a2ensite website1.conf
sudo systemctl restart apache2
8. Setting Permissions
Ensure that the directories for each website have proper permissions:
sudo chown -R www-data:www-data /var/www/html/website1
sudo chown -R www-data:www-data /var/www/html/website2
9. Testing and Troubleshooting
To verify that your configuration is correct, test the Apache configuration:
sudo apachectl configtest
Check logs for any errors:
sudo tail -f /var/log/apache2/error.log
Quick Summary
This guide walks you through the entire process of setting up an AWS EC2 Ubuntu instance with Apache, MySQL, phpMyAdmin, and multiple PHP versions. It also covers securing your websites with SSL certificates using Certbot and configuring Apache to serve different websites with distinct PHP versions.
FAQs
1. Can I install more than one PHP version on my EC2 instance?
Yes, you can install multiple PHP versions and configure Apache to serve different PHP versions for different websites.
2. What is phpMyAdmin, and why should I use it?
phpMyAdmin is a web-based interface that makes it easier to manage MySQL databases, particularly for those who prefer a graphical interface over command-line operations.
3. How do I secure my websites with SSL on an EC2 instance?
You can use Certbot to install and configure SSL certificates for your domains. This ensures HTTPS traffic is securely encrypted.
4. Why should I use PHP-FPM with Apache?
PHP-FPM provides better performance, particularly for high-traffic sites, by handling PHP scripts more efficiently than the traditional mod_php.
5. What instance type should I choose for this setup?
For a basic setup, a t2.micro instance is sufficient. However, for more traffic or resource-heavy applications, a larger instance may be necessary.