WordPress on Amazon EC2 makes a very flexible and powerful web development combo. WordPress is a great choice because it has a huge theme and plugin ecosystem, and it is very user-friendly (non-technical people can use it comfortably).
Amazon EC2 is highly scalable and practically unlimited and Amazon Web Services (AWS) provides a whole suite of website and application management tools that most people find useful at one point or another.
If you are a beginner at web development and want to setup your first website/blog, or if you’re a professional looking to specifically learn how to host WordPress on Amazon EC2, or if you’re anywhere in-between, I’m sure you will find this article very helpful.
I have deliberately included a lot of details and configuration options/choices in this article. If you already know what you’re doing, feel free to skip the sections you don’t need.
Some Terminology
WordPress is a free and open source blogging tool and a Content Management System (CMS) based on PHP and MySQL. It is designed to make your life easier when you want to build a website or blog for yourself. With WordPress, you can get very far without having to worry about coding and html. But be warned, you still need some computer skills (and maybe some coding skills) in order to make a site that looks good and more importantly, functions correctly.
If you are wondering what a Content Management System is, then take a look at WordPress, Drupal or Joomla. This article focuses on WordPress.
Amazon Elastic Compute Cloud (Amazon EC2) is a Web-based service that allows business subscribers to run application programs in the Amazon.com computing environment. It provides resizable computing capacity in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your need to invest in hardware up front, so you can develop and deploy applications faster. You can use Amazon EC2 to launch as many or as few virtual servers as you need, configure security and networking, and manage storage. Amazon EC2 enables you to scale up or down to handle changes in requirements or spikes in popularity, reducing your need to forecast traffic.
Amazon Web Services (AWS) is a collection of remote computing services that together make up a cloud computing platform, offered over the Internet by Amazon.com. The most central and well-known of these services are Amazon EC2 and Amazon S3.
At the time of this writing, Amazon is still the biggest cloud provider. Newbies to cloud computing would definitely want to check out AWS.
Note: If this is your first time working with AWS, you might want to take advantage of the free tier. Here’s how it’s described on the AWS site:
To help new AWS customers get started in the cloud, AWS is introducing a free usage tier. The free tier can be used for anything you want to run in the cloud: launch new applications, test existing applications in the cloud, or simply gain hands-on experience with AWS.
With the free tier, you can play with an EC2 micro instance for a whole year for free! You also get a number of other services for free for one year depending on your interests. However, you will need a valid credit card to register.
WordPress On Amazon EC2: Two Options
To set up WordPress on Amazon EC2, you have the option to grab a pre-made LAMP/WordPress image from Bitnami.
“Bitnami provides free, ready to run environments for your favorite open source web applications and frameworks, including Drupal, Joomla!, WordPress, PHP, Rails, Django and many more.”
Note however that Bitnami has a fair amount of magic under the hood that might give you trouble. So in this article instead of going with the Bitnami option, I will describe the entire WordPress on Amazon EC2 process from scratch. This way, if you encounter any issues, you know it is your own fault 🙂 (makes things much easier to fix).
Assuming you have signed up for Amazon Web Services, proceed to the next section to learn how to launch an Ubuntu instance on Amazon EC2. Eventually, we will setup WordPress on this EC2 instance.
Launching The Ubuntu EC2 Instance
Step 1:
Open up your AWS Management Console and on the EC2 tab, we need to create an Instance. Press the blue ‘Launch Instance’ button.
Your screen might look a little different because I already have a running instance.
Step 2:
You will be presented with a large selection of Amazon Machine Images (AMIs) to choose from. I use Ubuntu Server 12.04 LTS.
Check the “Free tier only” box to show only AMIs that are eligible for the free tier described earlier.
Step 3:
Your next option is to choose the Instance type you require. This is basically how much grunt you’re going to need. For a small blog site or if you are just testing stuff out, you should be okay with a micro instance, but for anything else you’ll need to choose something more powerful. A micro instance comes with 613MB of memory.
Most of the remaining instance details can be left default, but on the “Configure Instance” page, you might want to consider enabling Termination Protection so you don’t accidentally terminate the instance, which would delete your virtual machine and any data on it.
Step 4:
Next you need to create a key pair. This essentially works like a password to access your server. Just give it a name and click ‘Create and Download your Key Pair’, and save the generated .pem file in a safe place.
Note: If you lose this file you may not be able to access the instance anymore. Also note that this key pair is unique to (and will only work for) the OOTB ubuntu user. If you create new user(s) as we shall do later in this tutorial, you will need to generate key pairs for each user that needs to SSH into the Amazon EC2 instance. The process is a little different and is explained later in this article.
Connect To The Ubuntu EC2 Instance Via SSH
I assume that by now, you would have already created and saved a key pair for your Ubuntu instance.
The last step in launching an EC2 Ubuntu instance is to create a security group, which is a set of firewall port rules. We will only deal with the SSH rules now because that’s all we need to remotely access our server and setup VNC.
Select the SSH protocol and enter the IP (or range of IPs) to allow. This will open up the SSH port in the firewall for the defined IP(s).
Complete the wizard by clicking “Review and Launch”.
Assign An Elastic IP To The Instance
By default, an EC2 instance is not assigned a public IP address. It is private. You can change this by creating an Elastic IP address (which is a public IP address that belongs to your AWS account) and associating this IP with your instance. This will make your EC2 instance accessible from the Internet.
Step 1: On the EC2 tab of your AWS console, press “Elastic IPs”
Step 2: Now press “Allocate New Address”
Step 3: You will be asked to select where you want to use the EIP. Select EC2 and press allocate
Step 4: Now select the newly created Elastic IP and press “Associate Address”
Step 5: Select your EC2 Instance from the list and press “Yes Associate”
Going forward, we can now access our EC2 instance with the IP address we just assigned.
Install PuTTY On Your Client Machine
Go to the PuTTY download page and download and install the Windows installer version of PuTTY. Please install everything in the package or at least make sure you install PuTTYgen.
Remember we created and saved a .pem file previously? Once you’ve installed PuTTY, run the PuTTYgen program and convert your private key .pem file into a PuTTY private key .ppk file. Here’s how:
- Click the Load button, select the All Files option, select the .pem file you downloaded from Amazon EC2, and click Open
- Click OK on the prompt that appears
- For increased security you can create a password that you must enter when connecting via SSH with this private key. If desired, enter a password in the Key Passphrase and Confirm Passphrase fields
- Click the Save Private Key button, choose a safe and secure location, and click Save
Now open the PuTTY program and make the following configuration changes:
- For the Host Name, enter something like this ubuntu@75.101.166.76 where 75.101.166.76 is the Elastic IP address you created and assigned to your instance
- In the Connection tab, select SSH then select Auth. Click the Browse button, select the .ppk file you generated with PuTTYgen and click Open
- Select Tunnels under the SSH settings. Enter 9000 for the Source Port and localhost:5901 for the Destination and then click Add
- Go back to the Session tab and you can save this configuration by entering a name in the textbox under Saved Sessions and clicking Save
Now you can connect to your Ubuntu Server via the PuTTY terminal, click Open on the PuTTY program. Then log in as the ubuntu user. If you created a password when you generated your PuTTY private key, enter it, otherwise just connect.
I’m assuming that you have already logged into your server via SSH as the ubuntu user.
A lot of the commands in this article also require root access, so each time I connect to the instance I’ll just run one command to elevate my permissions. Otherwise I would need to prefix everything with ‘sudo’.
Type:
sudo su
Now update the pre-installed packages:
apt-get update apt-get upgrade
Install Apache On The Ubuntu EC2 Instance
If you did not choose an Amazon AWS AMI which pre-installed Apache, you will need to install it now.
apt-get install apache2
If it works fine, then you should be able to hit http://yourhostname.com to view the Apache web server default page.
If you have assigned an Elastic IP to your Amazon EC2 instance, replace yourhostname.com with your Elastic IP address.
If you haven’t assigned an Elastic IP to your instance, then replace yourhostname.com with the public DNS value for the EC2 instance.
The public DNS value looks something like this: ec2-75-101-166-76.compute-1.amazonaws.com
If Apache was correctly installed, your browser will return a page like this:
<html><body><h1>It works!</h1> <p>This is the default web page for this server.</p> <p>The web server software is running but no content has been added, yet.</p> </body></html>
You can also see the status of the Apache service using:
service apache2 status
And the output should be something like this:
Apache2 is running (pid 3918)
In case Apache is running but web page does not work, you may need to make sure that port 80 is open using security groups on the AWS console (security groups were discussed earlier).
Install PHP5 On The Ubuntu EC2 Instance
To install PHP on your server, run the following commands one by one from the terminal:
apt-get install php5 apt-get install libapache2-mod-php5
And then restart Apache:
/etc/init.d/apache2 restart
Note: If your PHP installation fails with a message such as “Unable to fetch some archives…” then run the following command and repeat the above process:
apt-get update
Now, your web files placed in /var/www/ can be accessed in the browser either via your Public DNS or using your Elastic IP.
Let’s create a test PHP file to make sure that we have PHP running properly. Use the following command to do so:
cd /var/www/ vi info.php
- Type i to start the insert mode
- Type <?php phpinfo() ?>
- Hit the Escape key to leave the insert mode
- Type :wq to save the file and quit the vi editor
We just created a file using the vi editor. If you hate having to edit files from the command prompt, you can easily do this via FTP by installing either FileZilla or WinSCP.
Now open http://yourhostname.com/info.php in the browser. Remember to replace yourhostname.com with either your public DNS or your Elastic IP address. You should see the installed php info. The page will look similar to this:
Configure Amazon EC2 And Apache
In this section, I explain a number of additional configurations I like to make on my Amazon EC2 server and Apache service.
The default server configurations are usually not sufficient for a real production server.
For example, when it is freshly installed, Apache will show the same web page to every host name that points to it. So while you can put your web pages directly in /var/www/ this will only work if you intend to have ONLY ONE website hosted on your server.
In most practical situations, you would want to be able to run as many websites as you like from your single Amazon EC2 instance with a single Elastic IP address.
Even if you’re just starting out with Amazon EC2 and only have one website in mind, you would probably want to set up your server so that no major changes are required if/when you later decide to host more sites.
Among other things, I explain how to do this later in this section by running several name-based web sites on a single IP address using virtual hosts.
Before proceeding, I recommend at this point that you map your Elastic IP address to a domain name in DNS. That way, we will not need to enter an actual IP address (or the EC2 public DNS value) into Apache configurations files.
Going forward, I will assume that you have done the DNS mapping and that your domain name is abc.com
Create A New Linux User [adduser]
So far we have been working with the default ubuntu user. For many reasons, it makes sense to add a new user (let’s call him userx) that we will work with going forward.
While logged in as the ubuntu user, run the adduser command as shown below (add sudo if necessary). The adduser command is very easy to use because it prompts you for each piece of information:
adduser userx
As soon as you type this command, Ubuntu will automatically start the process:
- Type in and confirm your password
- Enter in the user’s information. This is not required, pressing enter will automatically fill in the field with the default information
- Press Y (or enter) when Ubuntu asks you if the information is correct
Congratulations – you have just added a new user.
Grant The User Root Privileges
You are much better off using a user with root privileges. While still logged in as the ubuntu user, run the following command (add sudo at the beginning if you get a permissions error):
adduser userx sudo
Create A New Linux User [useradd]
Alternatively, you may choose to add a new user using the useradd command. Run the following command while logged in as the ubuntu user (add sudo if necessary):
useradd userx
The useradd command adds the user, but without any extra options your user won’t have a password or a home directory.
Note: If you get a message saying that the command is not found, try using the full path, like this:
/usr/sbin/useradd userx
You can use the -d option to set the home directory for the user. The -m option will force useradd to create the home directory. Then use the passwd command to set the password for the account. You can alternatively set a password using -p on the useradd command.
useradd -d /home/userx -m userx passwd userx
This will create the user named userx and give them their own home directory in /home/userx. The files in the new home directory are copied from the /etc/skel folder, which contains default home directory files. If you wanted to set default values for your users, you would do so by modifying or adding files in the /etc/skel directory.
Grant The User Root Privileges
As before, while still logged in as the ubuntu user, run the following command (add sudo at the beginning if you get a permissions error):
adduser userx sudo
Note:
Although you have just created a new user with a password, you MAY NOT be able to log in with the new user credentials. Because…
If you used the Amazon Linux AMI to launch your instance, the password login feature is already disabled by default and you must use a public/private key pair to SSH into the instance. This is much more secure.
You can use the AWS Management Console to create the key pair or you can use a third-party tool like ssh-keygen (a tool provided with the standard OpenSSH installation) and import the public key to EC2.
If you’re using a third-party AMI or one you’ve created, the AMI may not have the password authentication option disabled by default. You should take a moment to verify and disable that option.
We need a unique key pair for each Amazon EC2 user. The key pair we already have will only work for the ubuntu user and not for our newly created userx.
Continue reading to learn how to create key pairs for newly created users.
Key Generation And Distribution For New EC2 Users
In a previous section of this article, I showed you how to generate the initial key pair for the ubuntu user.
You’ll also need to create similar key pairs for all users who require access to your instances.
To create a key pair for userx, run the following command while logged in as the ubuntu user:
ssh-keygen -f userx
We could call the keys whatever we want. But for simplicity’s sake, we just name it userx according to the user name. Here’s how it runs:
ubuntu@ip-10-146-175-45:~$ ssh-keygen -f userx Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in userx. Your public key has been saved in userx.pub. The key fingerprint is: ad:bb:1c:42:68:00:3a:8f:f3:9a:a9:c1:39:50:77:42 ubuntu@ip-10-146-175-45 The key's randomart image is: +--[ RSA 2048]----+ |. E | |.. . | |o o o . | | = o + . | |+ . o . S . | |oo.. . . | |.+. . o | | =. o o | |* +. | +-----------------+ ubuntu@ip-10-146-175-45:~$
Two files will be created:
- userx (private key)
- userx.pub (public key)
The files will be saved in /home/ubuntu
Using FTP (or the terminal) move the public key to /home/userx and move the private key to your local machine (this is the machine where you plan to run PuTTY from).
Now we need to place the public key into their SSH authorized keys file. Run these commands one by one while logged in as the ubuntu user:
cd ~userx sudo mkdir .ssh sudo chmod 700 .ssh sudo chown userx:userx .ssh sudo cat userx.pub | sudo tee -a .ssh/authorized_keys sudo chmod 600 .ssh/authorized_keys sudo chown userx:userx .ssh/authorized_keys
Convert The Private Key To PuTTY Format [.ppk]
Run the PuTTYgen program and convert your private key file into a PuTTY private key .ppk file.
Here’s how:
- Click the Load button, select the All Files option, select the private key file, and click Open
- Click OK on the prompt that appears
- For increased security you can create a password that you must enter when connecting via SSH with this private key. If desired, enter a password in the Key Passphrase and Confirm Passphrase fields
- Click the Save Private Key button, choose a safe and secure location, and click Save
Now open the PuTTY program and make the following configuration changes:
- For the Host Name, enter something like this userx@abc.com where abc.com is your domain name which has been mapped to your the Elastic IP address in DNS
- In the Connection tab, select SSH then select Auth. Click the Browse button, select the .ppk file you generated with PuTTYgen and click Open
- Select Tunnels under the SSH settings. Enter 9000 for the Source Port and localhost:5901 for the Destination and then click Add
- Go back to the Session tab and you can save this configuration by entering a name in the textbox under Saved Sessions and clicking Save
You can now connect to your Amazon EC2 instance as the newly created user (userx) using SSH.
Now let us make userx have passwordless sudo just like the ubuntu user does.
Run sudo Command With No Password
At the end of /etc/sudoers there is a line that looks like a comment:
#includedir /etc/sudoers.d
However this line actually includes the contents of that directory inside of which is the file /etc/sudoers.d/90-cloudimg-ubuntu. Which has this content:
# ubuntu user is default user in cloud-images. # It needs passwordless sudo functionality. ubuntu ALL=(ALL) NOPASSWD:ALL
To give userx passwordless sudo behavior, add this line to the bottom of that file:
userx ALL=(ALL) NOPASSWD:ALL
Then perform a restart of the sudo service:
sudo service sudo restart
Going forward, userx will now have passwordless sudo functionality.
Hosting Multiple Websites On Amazon EC2 With Apache
Now that you have your own Amazon EC2 server, you might want to host multiple websites of your own or even start hosting websites for your friends or customers.
Even if you plan on running only one website for now, it makes sense to get set up properly with the capability to host multiple websites anytime you want.
When it is freshly installed, Apache will show the same web page to every host name that points to it. So while you can put your web pages directly in /var/www/ this will only work if you intend on only having one website hosted on your server.
Creating Virtual Hosts
Apache can host more than just one website. Indeed, it is possible to use Apache in a way so as to act like a web host for an unlimited number of web sites. This method of virtual hosting is made possible by setting up “virtual hosts” within your Apache server.
At the most basic level, there are only two directories that need to be used when setting up virtual hosts: /etc/apache2/sites-available/ and /etc/apache2/sites-enabled/.
In Apache2, to create virtual hosts on your server, you will need to add a file to your sites-available directory that corresponds to the virtually hosted website.
You can just think of this like this:
One sites-available file = One hosted website
To demonstrate this, let us pretend to host two websites abc.com and xyz.com on our Amazon EC2 server. However, you can host as many other websites as you want on your server. To do that, simply repeat the same operations as described below, but adapting them to the name of the other websites.
1. Make two new “sites-available” files
In the /etc/apache2/sites-available/ directory, you will see a default file called “default”. Use this as a template for your virtual host files. To to this, simply make two new copies of it, and then rename the copies to something else.
I like to name each sites-available file as the domain name of the website that will be hosted (this is only for clarity, you can call them whatever you want). This will allow easily identifying the files on your server.
So the two files will be named: abc.com and xyz.com
2. Edit the new “sites-available” files
Now you need to edit the files you have just created so that they will work for the websites you want to host on your server.
Start by opening each of them in your favorite text editor (or via FTP) and edit them so that they each contain the name of the website you want to host respectively.
So for the abc.com website, /etc/apache2/sites-available/abc.com will look something like this:
<VirtualHost *:80> ServerAdmin userx@abc.com ServerName abc.com ServerAlias www.abc.com abc.com DocumentRoot /home/userx/aws/abc.com <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /home/userx/aws/abc.com/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> (...) </VirtualHost>
And for the xyz.com website, /etc/apache2/sites-available/xyz.com will look something like this:
<VirtualHost *:80> ServerAdmin userx@xyz.com ServerName xyz.com ServerAlias www.xyz.com xyz.com DocumentRoot /home/userx/aws/xyz.com <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /home/userx/aws/xyz.com/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> (...) </VirtualHost>
Notice that we are no longer working with the default directory (/var/www), we are now hosting our websites inside the home folder of the new user (userx) which we created in the previous section.
Be sure to add the ServerName line, which is not in the default file.
The DocumentRoot line is where you specify the directory the web pages of each website will go on your server. You can make up anything you want to identify this, but be sure that you have already this directory.
NOTE: While there is no limit to how many websites you want to virtually host (all you need to do is to create a new file in the sites-available directory), the more websites that you host on your server, the slower your server will be.
3. Link from “sites-enabled”
Finally, you need to create a symbolic link to your new files in the /etc/apache2/sites-enabled/ directory.
To do this type:
cd /etc/apache2/sites-enabled
This will move you to the sites-enabled folder. Now type:
ln -s /etc/apache2/sites-available/abc.com ln -s /etc/apache2/sites-available/xyz.com
This will create links to your newly-created virtual host files.
Alternatively you can use a2ensite and a2dissite to enable and disable your new domain configuration.
To enable your new domain configurations, you type this:
a2ensite abc.com a2ensite xyz.com
And to disable the abc.com and xyz.com configurations you can type:
a2dissite abc.com a2dissite xyz.com
4. Restart apache
When done, be sure to restart Apache so that your changes will be taken into consideration by your server:
/etc/init.d/apache2 restart
For minor changes in configuration you can just reload the configuration of Apache, this will have a smaller impact on your running site.
/etc/init.d/apache2 reload
That is all! Do not forget that you need to point the domains of the websites that you are hosting to your Amazon EC2 Elastic IP address in DNS.
Should You Install MySQL Server?
At this point in the process of setting up WordPress on Amazon EC2, you need to decide on which MySQL database solution you want. You have two options:
Option 1 — Install MySQL on your Amazon EC2 instance.
Option 2 — Use Amazon Relational Database Service (Amazon RDS) for MySQL.
For a long time, Option 1 was the only way to run MySQL on the cloud. You setup an instance, install MySQL and maintain it yourself – this meant patching it, managing backups, handling replication failures, etc. Then Amazon RDS came along and can be thought of as a PaaS (Platform as a Service) for MySQL – it hides all the complexities behind the scenes and you only concern yourself with the database and not the database software.
This article explains how to implement both Option 1 and Option 2.
But first, lets get some more background about Amazon RDS and discuss a few things you need to consider before you make your choice.
What Is Amazon RDS?
Amazon Relational Database Service (Amazon RDS) is a web service that makes it easy to set up, operate, and scale a relational database in the cloud. It provides cost-efficient and resizable capacity while managing time-consuming database administration tasks, freeing you up to focus on your applications and business.
Read more here…
Amazon RDS makes it easy to set up, operate, and scale MySQL deployments in the cloud. With Amazon RDS, you can deploy scalable MySQL deployments in minutes with cost-efficient and resizable hardware capacity. Amazon RDS frees you up to focus on application development by managing time-consuming database administration tasks including backups, software patching, monitoring, scaling and replication.
Read more here…
Running on Amazon RDS means that:
- AWS will take care of provisioning the infrastructure capacity you request and installing the database software.
- Automated backups will be performed by Amazon RDS as configured with point-in-time recovery options. You may also manually initiate a DB snapshot to backup your DB in a known state. RDS offers backup retention for up to the last 35 days.
- Amazon RDS will apply patches that are security and durability related.
- Amazon RDS will manage synchronous data replication across physically distinct locations (Multi-AZ deployments).
- With Multi-AZ deployments, Amazon RDS will perform automatic failovers in case of certain failures or planned maintenance such that your application can resume database operations without the need for manual administrative intervention.
- Amazon RDS will create ‘Read Replicas’ (similar to MySQL Slaves) as requested for read intensive workloads.
- AWS will monitor the compute and storage resource utilization of your DB Instance, for no additional charge, via Amazon CloudWatch.
You also get the flexibility to manage most of these things with a few clicks from the AWS Management Console.
With all of these database management benefits from Amazon RDS, is there any reason to even consider NOT using RDS? Read further 😉
Why You May NOT Want Amazon RDS
We discussed some of the many benefits of using Amazon RDS for MySQL in the previous section.
Here are some reasons why you may NOT want to use Amazon RDS and instead go the traditional route of installing MySQL on your Amazon EC2 instance:
- Amazon RDS is not free. Besides the usual Amazon EC2 fees, you will pay extra if you want to use Amazon RDS. See here for Amazon RDS pricing.
- Amazon RDS does not allow as much configuration flexibility as running MySQL in an EC2 instance. With Amazon RDS, you’re beholden to Amazon for your database. Locking in with Amazon RDS means when you hit a bug, your hands are a bit tied. But with your own database server installed on EC2, you have control over all the nuts and bolts of your technology.
- Amazon RDS lacks support for User-Defined Functions.
- With Amazon RDS, you cannot use the Federated Storage Engine.
- With Amazon RDS, you lose the ability to have the one extra connection available for emergency access.
Note: While I have a bias towards Amazon RDS (if you don’t mind the extra cost), I am not recommending any particular option here. The pros and cons of Amazon RDS versus your own MySQL on EC2 discussed in this article are merely for your information.
Let us now discuss how you may implement either database option.
Option 1: Install MySQL On Amazon EC2
The process for installing MySQL is similar to the process we followed for installing PHP. Use the following command in terminal to install MySQL:
apt-get install mysql-server
During installation process you will be asked to enter and confirm a password for the MySQL “root” user. Keep this password safe in your memory because this will be required to access the database later on.
Since we need to run PHP5 with MySQL, we will also install the PHP module for MySQL using the following commands:
apt-get install php5-mysql apt-get install libapache2-mod-auth-mysql
At this point, we could create a database from the command line and just proceed with WordPress installation using that database. But I like to have a nice UI based tool for managing the database instead of the command line. So let’s proceed and install phpMyAdmin.
phpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. phpMyAdmin supports a wide range of operations on MySQL, MariaDB and Drizzle. Frequently used operations (managing databases, tables, columns, relations, indexes, users, permissions, etc) can be performed via the user interface, while you still have the ability to directly execute any SQL statement.
Install phpMyAdmin For MySQL On Amazon EC2
Use the following command to install phpMyAdmin:
apt-get install phpmyadmin
When asked to “…choose the web server that should be be automatically configured to run phpMyAdmin” select apache2
When asked if you want to “Configure database for phpMyAdmin with dbconfig-common” choose Yes
Follow the rest of the instructions on screen and remember the password that you enter in each field.
After the installation of phpMyAdmin is complete we need to configure our Apache to make phpMyAdmin accessible via browser.
Use the following command to do this:
ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
Now reload Apache to make the changes take effect:
/etc/init.d/apache2 reload
Now you can access phpmyadmin in your browser like this:
http://abc.com/phpmyadmin where abc.com is your domain name that has been mapped to your Amazon EC2 Elastic IP address.
You will be prompted for username and password. For username, type root and for password, enter the password for the root user (you defined this password during the MySQL installation process).
At this point, I recommend creating another user specifically for WordPress (instead of the default root user). You will find the Add new user button under the Privileges tab in phpMyAdmin. Let’s call the new user wpuser.
Also create a database specifically for WordPress. Let’s call the database wpdb.
You now have all essential elements on your virtual server for running WordPress and everything is working perfectly. So if you selected this option (installing MySQL on Amazon EC2) instead of the Amazon RDS option, you should skip the next section and proceed to the section on installing WordPress.
Option 2: Use Amazon RDS for MySQL
My assumption here is that you have decided to use Amazon RDS for MySQL instead of installing MySQL directly on your Amazon EC2 instance.
Do not complete this section if you already completed the previous section (Option 1: Install MySQL On Amazon EC2).
If you did complete the previous section, skip this section and proceed to the section on Installing WordPress.
Create An RDS DB Security Group
Log in to your AWS console.
From the list of services, select RDS. You will see a screen similar to this:
Select Security Groups from the left navigation. A screen similar to this will appear:
Note: If you’re doing this for the first time, you will only have the default security group listed.
Press the Create DB Security Group button.
Enter a meaningful name and description. For this demo, let’s call our security group wpsecgp.
Press Yes, Create. On the next screen you will see your newly created database security group listed. Select it. You will notice a message like this below:
This DB Security Group has no authorizations. You will not be able to connect to DB Instances associated with this security group until you add an authorization. Select a Connection Type below to add an authorization.
In the Connection Type dropdown, you are required to select a connection type to authorize a new ingress rule. You have two options:
- CIDR/IP
- EC2 Security Group
Select EC2 Security Group.
In the AWS Account option, “you may authorize EC2 Security Groups belonging to this account, or you may manually enter another AWS Account ID and name of an EC2 Security Group belonging to that account”. Select This Account.
Then select the EC2 Security Group Name. This security group was created when we originally launched our Amazon EC2 instance.
Your screen should now look like this:
Press Authorize.
Repeat the steps for creating a db security group. Name your security group wpsecgp2. But this time, select CIDR/IP and enter the Private IP of your Amazon EC2 instance.
Note: CIDR/IP must be in the format B.B.B.B/M where B is 0-255 and M is 0-32
So if your private IP is 99.226.146.201 enter 99.226.146.201/32
Repeat the steps for creating a db security group one more time.
Name your security group wpsecgp3.
Again, select CIDR/IP and enter the Elastic IP of your Amazon EC2 instance.
Use the same format for the Private IP.
You now have three non-default db security groups. We will use them later.
Launch An RDS DB Instance
Return to your Amazon RDS dashboard and press Launch a DB Instance.
On the Select Engine page, choose MySQL.
You will be asked if you plan to use this database for production purposes. For this demo, I will choose Yes.
For databases used in production or pre-production we recommend:
- Multi-AZ Deployment for high availability (99.95% monthly up time SLA)
- Provisioned IOPS Storage for fast, consistent performance
Billing is based upon the RDS pricing table.
An instance which uses these features is not eligible for the RDS Free Usage Tier.
You will now be taken to the DB details page.
On this page, I will leave the Instance Specifications section at their default values.
In the Settings section, you are required to enter the following details:
- DB Instance Identifier: Specify a name that is unique for all DB instances owned by your AWS account in the current region. DB instance identifier is case insensitive, but stored as all lower-case, as in “mydbinstance”.
- Master Username: Specify an alphanumeric string that defines the login ID for the master user. You use the master user login to start defining all users, objects, and permissions in the databases of your DB instance. Master Username must start with a letter, as in “awsuser”
- Master Password: Specify a string that defines the password for the master user. Master Password must be at least eight characters long, as in “mypassword”.
- Confirm Password: Retype the value you specified for Master Password.
Enter the values and press Next.
You will be taken to the Configure Advanced Settings page:
Some settings of interest on the Configure Advanced Settings page are:
- DB Security Group(s): “Select the security group or groups that have rules authorizing connections from all of the EC2 instances and devices that need to access the data stored in the DB instance. By default, security groups do not authorize any connections; you must specify rules for all instances and devices that will connect to the DB instance.”
Select the three DB Security Group we created earlier, wpsecgp, wpsecgp2 and wpsecgp3.
- Database Name: “Specify a string of up to 8 alpha-numeric characters that define the name given to a database that Amazon RDS creates when it creates the DB instance, as in ‘mydb’. If you do not specify a database name, Amazon RDS does not create a database when it creates the DB instance.”
For this demo, I will use wpdb.
- Backup Retention Period: “Select the number of days, between 1 and 35, that Amazon RDS should retain automatic backups of this DB instance. The backup retention period determines the period for which you can perform a point-in-time recovery. Select 0 to disable backups.”
Although I will leave this as default (1) for this demo, you probably want to increase this number on a real production system.
When you have entered your configuration options, press Launch DB Instance.
Your Amazon RDS DB instance will be created (takes a while though).
Now let us set up MySQL and phpMyAdmin to manage Amazon RDS.
Install MySQL For Amazon RDS
To install MySQL for Amazon RDS, first run the following command:
apt-get install mysql-server
During installation process you will be asked to enter and confirm a password for the MySQL “root” user.
NOTE: We don’t really need to install mysql-server because our database is located on Amazon RDS. However, since I plan to manage the Amazon RDS instance using phpMyAdmin, and to avoid unnecessary complexities, just install mysql-server. The extra database created during the install process of phpMyAdmin will probably remain redundant. If you have a good understanding of phpMyAdmin configuration, you might be able to skip installing mysql-server.
Since we definitely need to run PHP5 with MySQL (for WordPress), we will install the PHP module for MySQL using the following commands:
apt-get install php5-mysql apt-get install libapache2-mod-auth-mysql
Now let us install phpMyAdmin.
Install phpMyAdmin For Amazon RDS
To install phpMyAdmin use the following command:
apt-get install phpmyadmin
When asked to “…choose the web server that should be be automatically configured to run phpMyAdmin” select apache2
When asked if you want to “Configure database for phpMyAdmin with dbconfig-common” choose Yes
Follow the rest of the instructions on screen and remember the password that you enter in each field.
After the installation of phpMyAdmin is complete we need to configure our Apache to make phpMyAdmin accessible via browser.
Use the following command to do this:
ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
Locate this file on your server: /etc/phpMyAdmin/config.inc.php
You will see a section like this:
/* Configure according to dbconfig-common if enabled */ if (!empty($dbname)) { /* Authentication type */ $cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */ if (empty($dbserver)) $dbserver = 'localhost'; $cfg['Servers'][$i]['host'] = $dbserver; if (!empty($dbport) || $dbserver != 'localhost') { $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['port'] = $dbport; } //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your server has it */ $cfg['Servers'][$i]['extension'] = 'mysqli'; /* Optional: User for advanced features */ $cfg['Servers'][$i]['controluser'] = $dbuser; $cfg['Servers'][$i]['controlpass'] = $dbpass; /* Optional: Advanced phpMyAdmin features */ $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; $cfg['Servers'][$i]['tracking'] = 'pma_tracking'; $cfg['Servers'][$i]['userconfig'] = 'pma_userconfig'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; }
Immediately after that section (after the last }), add the following code, but of course with your own Amazon RDS instance URL (Endpoint):
$cfg['Servers'][$i]['auth_type'] = 'HTTP'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'mydbinstance.cihi4vte69oj.us-east-1.rds.amazonaws.com';
You will copy the host value from the Endpoint value of your Amazon RDS instance. See area highlighted in yellow below (don’t include the port number):
Now restart Apache to make the changes take effect:
/etc/init.d/apache2 restart
Now you can access phpmyadmin in your browser like this:
http://abc.com/phpmyadmin where abc.com is your domain name that has been mapped to your Amazon EC2 Elastic IP address.
You will have to select your Amazon RDS endpoint from the Server Choice list and log in with the Master Username and Master Password you choose when you launched your RDS instance.
Troubleshooting phpMyAdmin For Amazon RDS
If you hit an error like this when you attempt to log in…
#2005 – Unknown MySQL server host ‘mydbinstance.cihi4vte69oj.us-east-1.rds.amazonaws.com’ (2)
This is a known DNS resolution issue. See here for details.
Assuming you don’t hit any errors, you now have all essential elements on your virtual server for running WordPress and everything is working perfectly. So proceed to the section on installing WordPress.
Installing WordPress On Amazon EC2
From your home directory, download the latest copy of WordPress and extract it to /home/userx/aws/abc.com directory.
We created userx and assigned /home/userx/aws/abc.com as a virtual host directory in previous sections.
Do the download and extract by using these commands:
wget http://wordpress.org/latest.tar.gz tar -xzvf latest.tar.gz -C /home/userx/aws/abc.com
By default, all the files will be extracted into a “wordpress” directory. So your files are at /home/userx/aws/abc.com/wordpress/
To move the files to root of your virtual host directory and then remove the “wordpress” directory use:
cp -avr /home/userx/aws/abc.com/wordpress/* /home/userx/aws/abc.com rm -rf /home/userx/aws/abc.com/wordpress
Rename the file wp-config-sample.php to wp-config.php
mv wp-config-sample.php wp-config.php
Open wp-config.php in a text editor. I advise using FTP for this part instead of command line text editors. Locate this area:
// ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'database_name_here' ); /** MySQL database username */ define( 'DB_USER', 'username_here' ); /** MySQL database password */ define( 'DB_PASSWORD', 'password_here' ); /** MySQL hostname */ define( 'DB_HOST', 'localhost' );
Modify the database connection parameters in your config.php file accordingly.
Note: The values you enter here will depend on whether you are running MySQL server on Amazon EC2 or using Amazon RDS.
If you’re using Amazon RDS for example, MySQL hostname value would be something like: mydbinstance.cihi4vte69oj.us-east-1.rds.amazonaws.com:3306
If you’re using MySQL on Amazon EC2 as described in this article, MySQL hostname will remain as localhost
Find the section called Authentication Unique Keys and Salts within the wp-config.php file. Looks like this:
define('AUTH_KEY', 'KIb`] lgxzd-:r5:%4q.X<8|Xl|.MtcTx`|>H|Kc7k:yBKB:&bip4Zo|k@|<2eRF'); define('SECURE_AUTH_KEY', ' x:nwmIQDw1z+-!),>42Mo@_ sC.)3f2oWNot-82!,IU31mDQIYUOYbo|G$-_t{#'); define('LOGGED_IN_KEY', '%<}iy~j9)e8yp|7?bU+@q]cNcib:j1-t}nc&eeiXz9P/|U(>8ePOJ=H[6$4:~&vx'); define('NONCE_KEY', 'Hbz8NvQmmjM|-s@Y#CkNe*Bm@F1R<&DW/:0zoC~9{6pAw5skwJYn%:75YPT>#fAb'); define('AUTH_SALT', '><8Q,fd<|QG5(]m@(T/rik%-QE:LY*0 VpGDzPKawkZk^<r-uC6#f=$SPL$;|>%n'); define('SECURE_AUTH_SALT', 'vnoF|(;s#CVU]ziW@YAA9O5~0~DBQq_&J2E5L8.6_]qie8;~28~jeRLwU/x}gDE3'); define('LOGGED_IN_SALT', 'JXF>94g`RR8m^njv|;=G-(5i$-bUU/2Mxd:`Vk<Z*#1 r#XLnvMW:jbMQv7H01<j'); define('NONCE_SALT', 'UZx.uG3KXI)`(i~Ac%)D[]VrrJS0:>j.mDb/nAV*p=p1SGE|rhKvrv6>:l<Ae)qJ');
These KEY and SALT values provide a layer of encryption to the browser cookies that WordPress users store on their local machines. Basically, adding long, random values here makes your site more secure. Use this online generator to randomly generate a set of key values that you can copy and paste into your wp-config.php file.
Run the WordPress installation script by accessing the URL in a web browser. In our case, the url of the installation script would be located at http://abc.com/panel/install.php
WordPress should now be installed! Just follow any screen prompts like entering your site title etc.
Now that you have set up your WordPress website on Amazon EC2, there are tons of more configuration stuff you might need to do at one time or another. For example you might want to check out my tutorial on:
Performing WordPress Updates And Installations Via SSH
OR you might love my popular tutorial on:
Virtual Network Computing (VNC) For Ubuntu On Amazon EC2
If you have any questions, additions to this article, or if you noticed any error(s) here, please feel free to drop your comments below.
Leave a Reply