How to Load Balance a PHP Application on Google Cloud
How to Load Balance a PHP Application on Google Cloud. This guide provides you with detailed and advanced steps to setup a HTTP(S) Layer 7 Load Balancer for your PHP web application on Google Cloud Platform.
You will also setup Cloud SQL for your database, install and configure Apache, PHP and finally configure Google Cloud CDN. Follow this tutorial without missing any steps for a successful setup of auto-scaling of your instances horizontally.
This setup is same as configuring a PHP application with Nginx and Apache where Nginx is placed in front of Apache as a reverse proxy which handles all requests. Google Cloud Load Balancer is also build upon Nginx to intelligently route traffic and manage autoscalings, etc.
Steps to Configure Load Balancing
- Enable APIs and create a Service account.
- Configure Compute Engine instance for Load Balancer.
- Install and Configure Apache.
- Install and Configure PHP
- Create Health Check.
- Create Instance Template.
- Create a Managed Instance Group.
- Reserve Global Region IPv4 and IPv6 addresses.
- Create Load Balancer.
- Install Google Managed SSL Certificate.
- Configure DNS.
- Setup Google Cloud CDN.
Prerequisites
- A running Compute Engine, see the Setting up Compute Engine Instance with Ubuntu 18.04
- Initial Ubuntu Server Set up.
- Setup Google Cloud DNS for your Domain name.
- A running Cloud SQL instance, see How to set up Cloud SQL in Google Cloud
If you have all the above mentioned required requisites done and in place, you can proceed to setup Load Balancing.
Step 1: Enable APIs and create a Service account
Go to APIs and Services and click Enable APIs and Services and enable Cloud SQL API
and Cloud SQL Admin API
Now go to IAM & Admin >> Service accounts and click Create service account
Enter Service account Name
Click Create
Select Role
Cloud SQL >> Cloud SQL Client
Project >> Editor
Click Continue
Click Create Key
Choose Key type as JSON
Click Create
Step 2: Configure Compute Engine Instance
Once you have completed the initial server setup for Ubuntu, you can proceed to install Apache and PHP.
Setup web application directories
Create a directory where your website files will be, here we can choose the html
directory. So your directory structure will look like the one below.
Replace yourdomainname
with your original domain name.
/var/www/html
-- yourdomainname
---- public
The public
directory is your website’s root directory. Go ahead and create those directories.
sudo mkdir -p /var/www/html/yourdomainname/public
Step 3: Install and Configure Apache
Install Apache using the following command.
sudo apt install apache2
Enable firewall for Apache to allow HTTP and HTTPS connections. This needs to be configured if you are using UFW/
sudo ufw allow 'Apache Full'
Once Apache is installed and firewall configured, you can proceed to setup virtual hosts for your website.
Remove the default virtual host first.
sudo a2dissite 000-default
Create new configuration.
sudo nano /etc/apache2/sites-available/yourdomainname.conf
Paste the below Virtual Host configuration in your file.
<VirtualHost *:80>
ServerName yourdomainname.com DocumentRoot /var/www/html/yourdomainname/public <Directory />
Options FollowSymLinks
AllowOverride None
</Directory> <Directory /var/www/html/yourdomainname/public>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
Require all granted
</Directory>
</VirtualHost>
Hit Ctrl + X
followed by Y
and Enter
to save and exit the file.
Enable the new configuration.
sudo a2ensite yourdomainname.conf
Replace your yourdomainname
with the name of the file you created above.
Enable Apache rewrite mode.
sudo a2enmod rewrite
Restart Apache.
sudo systemctl restart apache2
Configure .htaccess
to redirect HTTP traffic to HTTPS. This setup is to a must as we are going to configure Google managed SSL later in HTTP(S) Layer 7 Load Balancer.
sudo nano /var/www/html/yourdomainname/public/.htaccess
Paste the following contents inside it and save the file.
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
Now you can place your website files inside your web root directory (/var/www/html/yourdomainname/public
).
Step 4: Install and Configure PHP 7.4
Now you are good to install PHP. Here we will install PHP 7.4, you can also install your desired version of PHP.
Add the ondrej/php
which has PHP 7.4 package and other required PHP extensions.
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
Once you have added the PPA you can install PHP 7.4 and some commonly used php-extensions
with the following command.
sudo apt install php7.4 libapache2-mod-php7.4 php7.4-common php7.4-mysql php7.4-xml php7.4-xmlrpc php7.4-curl php7.4-gd php7.4-imagick php7.4-cli php7.4-dev php7.4-imap php7.4-mbstring php7.4-opcache php7.4-soap php7.4-zip php7.4-intl php7.4-bcmath unzip mysql-client -y
Modify PHP configuration by editing the php.ini
file.
sudo nano /etc/php/7.4/apache2/php.ini
Hit F6 for search inside the editor and update the following values
upload_max_filesize = 48M
post_max_size = 48M
memory_limit = 256M
max_execution_time = 600
max_input_vars = 5000
max_input_time = 1000
Hit CTRL+X
and Y
to save the configuration and restart Apache for the changes to take effect.
sudo service apache2 restart
Now you have your Compute Engine setup completed and configured it to accept connections from Load Balancer.
Step 5: Setup Cloud SQL
As your Compute Engine instances are created dynamically, you need to connect to Cloud SQL using Cloud SQL Proxy or with Private IP.
Using Cloud SQL Proxy
If you wish to use Cloud SQL proxy to connect Cloud SQL database you use hostname as 127.0.0.1
Using Private IP
This is a straight forward way to connect to Cloud SQL using Private IP. Go to your Cloud SQL Instance and enable Private IP.
Change hostname to PRIVATE_IP_ADDRESS
While using Private IP, make sure you are using the same VPN network.
Step 6: Create Instance Template
Next, stop the VM Instance and go to Compute Engine >> Images and click Create Image.
In Name enter a unique name
In Source select Disk
In Source Disk select the disk of your VM Instance
Click Create
Once the Image is created go to Compute Engine >> Instance templates and click Create instance template
In Name enter name
of the template
In Machine type choose 1 vCPU 3.75 GB RAM
In the Boot Disk click Change and click the Custom images tab.
Choose the Image that you created earlier
In the Boot disk type select SSD persistent disk
Click Select
In Identity and API access choose Allow full access to all Cloud APIs
In Firewall check both Allow HTTP traffic
and Allow HTTPS traffic
Step 7: Cloud SQL Proxy connection
If you are using the Private IP address to connect to Cloud SQL, you can skip the startup script.
In the Management tab find the Startup script and enter the following
#! /bin/bash
sudo apt update
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
chmod +x cloud_sql_proxy
sudo mkdir /cloudsql; sudo chmod 777 /cloudsql
./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306
Replace the INSTANCE_CONNECTION_NAME with your Cloud SQL connection name
In the Networking tab make sure Premium
is selected in Network Service Tier
Click Create
Step 8: Create a Managed Instance Group
Goto Compute Engine >> Instance groups and click Create instance group
In Name enter name
In Location choose Single-zone
In Region choose your preferred region
Click Specify port name mapping
In Port name enter http
and in Port numbers enter 80
In Group type choose Managed instance group
In Instance template select the instance template you just created
Leave everything to default and click Create
Step 9: Reserve Global Region IPv4 and IPv6 Address
Go to VPC network >> External IP addresses and click Reserve Static IP Address
In Name enter a name
for IPv4 address
In Network Service Tier choose Premium
In IP version choose IPv4
In Type choose Global
Click Reserve
If you wish to use IPv6 address you need to upgrade your account to increase the quota limit, because Google Cloud limits IP reservation to one per region during trial period.
Click Reserve Static IP Address
In Name enter a name
for IPv6 address
In Network Service Tier choose Premium
In IP version choose IPv6
In Type choose Global
Click Reserve
Step 10: Create Load Balancer
Go to Network Services >> Load Balancing and Click Create Load Balancer
In the HTTP(S) Load Balancing click Start Configuration
Backend configuration
Enter a name for your Load Balancer and click Backend configuration
In Backend services & backend buckets select Backend service >> Create backend service
Enter a name for your backend service
In Backend Type choose Instance group
In Backends select the Instance group you created
In Port numbers enter 80
In Balance mode choose Utilization
Click Done
Check Enable Cloud CDN
Step 11: Create Health Check
In Health Check click create health check
In Name enter a health check name
In Protocol select TCP
In Port enter 80
In Proxy protocol select None
In Check Interval enter 10
In Timeout enter 5
In Healthy threshold enter 2
In Unhealthy threshold enter 3
Click Save and Continue
Step 12: Frontend Configuration with Google managed SSL
Enter a name for your IPv4 frontend configuration
In Protocol select HTTPS
In IP version select IPv4
In IP address select the IP4 address
you reserved
In Certificate select Create Certificate
Enter a name for your certificate
In Create mode choose to Create Google-managed certificate
In Domains enter *.yourdomainname.com
This setting will issue a Google managed Let’sEncrypt Certificate.
Attention: Once you have created a certificate it will be in the PROVISION status. Once the certificate is ACTIVE, you’ll have SSL issues for a few minutes with the error message ERR_SSL_VERSION_OR_CIPHER_MISMATCH. It took 15 minutes for mine to have everything up and running.
Now in Frontend configuration click Done
Click Add Frontend IP and Port
Enter a name for your IPv6 frontend configuration
In Protocol select HTTPS
In IP version select IPv6
In IP address select the IPv6 address
you reserved
In Certificate select the certificate you just created
Click Done
That’s all now your Backend and Frontend are configured
Step 13: Configure DNS and Setup Cloud CDN
Click Create
Now Goto Network services >> Cloud DNS and click your domain name
Edit the A record and replace the IPv4 address with your newly reserved IPv4 address
.
Click Add record set
In Resource record type select AAAA
record
Enter the IPv6 address
that you reserved
Goto Goto Network services >> Cloud CDN and click Add origin
In Origin select the Load balancer
you just created.
Click Add
Now go to Network services >> Load Balancing and wait for 10–15 minutes for the Load Balancing settings to propagate. Once done you will see a green check mark which indicates everything is fine.
Next you can set up Cloud Armor to secure your application.
Alright! done. Hope this helps to configure HTTP(S) Layer 7 Load Balancing on Google Cloud with CDN
Conclusion
Now you have learned how to configure Load balancing for a PHP website on Google Cloud.
Thanks for your time. If you face any problem or any feedback, please leave a comment below.