By entries and word count, the biggest collection of articles on my old website (grahamewatt.com) is a six-part series documenting how I went about rolling a free-ish website on AWS using a pretty basic hosting stack. It's been a fair amount of effort to restructure and port the articles into one coherent article, but its been fascinating to see how my confidence working with tech has improved. I still don't particularly think of myself as a wizard, but what one took me a couple of weekends these days would probably take me a few hours now.1

All six parts (five + epilogue) are included here back-to-back, with minimal editing. I fixed some typos and removed some navigational content (link menus, meta-narrative) that doesn't make sense when the whole thing is in a single post.

Best part is this still works! If you want to build a minimal website on AWS and do all the config yourself, there are some minor things that you'll have to sort out but the logic is still sound.


Part 1 – The Plan

I have a website! And not just any website. One with my name on it. One where I totally unnecessarily configured every square inch of it. One that is totally overkill for what it's actually being used for. But it uses entirely free2 infrastructure, thanks to the magic of AWS free tier infrastructure. Will it be free forever? No. But I currently save $9-10/month on hosting costs, and learned a bunch of cool new skills in the process.

In this series, I'm going to cover how to set up your own "free" website on AWS. We'll get a site set up exactly as this one is. grahamewatt.com runs using LEMP infrastructure (Linux, NGINX,3 MySQL, PHP) on EC2, s3, and RDS, using CloudFront for its CDN and Wordpress for its CMS.

Getting Started

To build a similar site, you will need the following:

  • AWS Account (sign up for free at aws.amazon.com)

  • A domain

    • I purchased mine from Google Domains, but AWS also resells domains (which will allow you to save yourself a little bit of time editing nameservers). If you want a vanity domain (.blog, .tv, .fm, etc.) you may have to check a few different registrars to figure out who sells those domains.

  • SSH client

    • I use PuTTY but anything will work.

  • FTP client

  • Patience

    • In my experience, it is a rare tutorial that works flawlessly end-to-end first go. And even when they do, it is far too easy to accidentally misread or skip a step, and then be very confused. Networking is also just...frustrating sometimes, so be patient and you will get there. I believe in you.

Once you've got all your tools, it's time to dive in.

System Overview

General infrastructure diagram

This is what we're building. It looks fairly messy (and the stack isn't exactly correct) but it's actually not too bad. Here's what's happening:

  • Route 53

    • DNS management. Tells the internet where to go when someone types in "grahamewatt.com" into their browser bar.

  • EC2

    • A computer. This one happens to be running Ubuntu, which is a Linux operating system. You can get them to run Windows too. AWS never turns them off and they have zillions of them to choose from, including the t2.micro instance I am using for this site. We're using it as a server, which will serve our website to the internet. Since it hosts our website, it is our web host.4

  • RDS

    • Relational Database Service. Runs the database that makes the Wordpress CMS work. We're using MySQL (the "M" in LEMP).

  • S3

    • Folders of files. S3 is basically the same5 as the file explorer on your computer, with folder hierarchies and sorting. We're passing off all the images and media to be stored in a separate system for two reasons: 1) the EC2 instance we're using doesn't exactly have a massive amount of storage, and 2) using S3 means we can use a CDN, resulting in super fast image load speeds and less work for the EC2 instance to do.

  • CloudFront

    • A content delivery network (CDN). CDN's are networks of servers that cache websites and images around the world, so that users in Tokyo only need to connect to a computer in Seoul to get your cat GIFs, instead of connecting to Chicago.

That's the macro-level stuff on AWS. All of it is either free-tier eligible or just free forever (Route 53). You can get by without S3 and CloudFront in this assembly, but they're not hard to get going. There are also a couple of pieces of software running on our EC2 instance:

  • NGINX

    • NGINX is one of a couple popular web server technologies available out there. Perhaps slightly less common for a basic website than Apache server, I just happen to be more familiar with it due to some work I did using the video streaming plugin NGINX-RTMP so it's my default server of choice.

  • Wordpress

    • Our content management system (CMS). Far and away the most popular choice of CMS for websites great and small. Wordpress makes it easy to create or modify custom themes, build new web pages, start a blog, the works.

  • Certbot (not pictured)

    • Free, auto-renewing SSL certificates. SSL is the "S" at the end of HTTPS,6 and makes that little padlock appear in your address bar on any site properly maintained. There is literally no reason in this day and age to not have an HTTPS connection when browsing the web.

  • TiddlyWiki (& NodeJS)

    • Not relevant for this series, but it's a cool piece of software that does well as a wiki or personal notes system. I included it in the diagram to show an example of how port forwarding works and also to give it a plug because I really like it. Check it out at tiddlywiki.com

There are also a bunch of default software packages that come preinstalled on Ubuntu. Again, all of these things are free and open source, so no need to bust out the credit card.

The Road Ahead

Part 2 of this series covers setting up an EC2 instance and connecting to it. Part 3 will cover installing NGINX, and configuring your DNS to serve your domain to your web host. Part 4 will cover setting up WordPress, and launching your website. Part 5 will cover the finishing flourishes: setting up the CDN and s3 offload.

As someone who does not have a formal background in computer science, I intend to keep the tutorial focused on the core contents and the logic behind each step. I always prefer to understand the "why" when I am doing things so that I have a solid grasp of the core concepts and can then leap off to explore the next thing in the future.


Part 2 – EC2 Instances

This tutorial is the second in my series on setting up a website using free infrastructure. In this section we'll cover booting up and connecting to your EC2 instance, configuring security groups, and some basic command line tools for folks who have never used the command line before.

EC2 overview

EC2 stands for Elastic Cloud Compute, and is a service that provides "computers" over the internet. EC2 instances and their equivalents at Google and Azure are the backbone of the cloud revolution. Before cloud services, using web servers and infrastructure usually meant buying physical servers, or buying time from dedicated hosts. Now, we can rent computer time for pennies, configure it however we want from the comfort of a home or office, and wire it up to all the other crazy features AWS has to offer.

EC2 instances are powerful tools, made more so by something AWS provides called an Elastic Load Balancer. As traffic grows, an ELB will split it between duplicate instances to keep one from being overwhelmed. AWS will even let you script initialization of new instances so the service will maintain them as necessary. Pretty cool.

EC2 instances are run out of tremendously complex server farms scattered across the globe, but for the sake of what we're doing it's helpful to think about our instance as a single computer in a building somewhere. The computer never turns off, and has only the software we decide we want7 on it.

Our EC2 configuration will be fairly straightforward for this series; we aren't going to be adding some of those more advanced features, which are a) overkill, and b) cost money, thereby defeating the purpose of a series on free websites. But know that most SaaS platforms on the web use some combination of EC2 and ELBs for the majority of their horsepower.

Setting up an EC2 instance

Launching an EC2 instance is very straightforward. After logging into AWS, check your region8 and navigate to the EC2 dashboard (you can search from the "Services" dropdown in the top menu bar). Select Instances from the left menu, and click the big blue Launch Instance button to start the EC2 launch wizard.

The first decision to make is which image to select. An image is essentially a set of software and configuration files which represents the computer it was taken from--a snapshot of a computer in time. You can use these snapshots to set up other machines to be exactly the same as the original.

There are a number of free-tier eligible machines available; we want the one called Ubuntu Server 18.04 LTS.9 On the Instance Type page, select the t2.micro, the only instance available for free, and press the Review and Launch button. Review your image and instance type, and press the Launch button to get started.

AWS will prompt you to select a key pair. We're going to create a new key pair; name your pair and press the Download button to save the private key.

DO NOT LOSE YOUR PRIVATE KEY! Our private key file is essentially our password; we need it to log into our instance. Save it in a safe place; if you do lose it you'll lose access to your website infrastructure and will need to build everything over again.

Your instance will spend a few minutes booting up and configuring itself. You can watch it from the EC2 dashboard. When it's ready, you'll be able to get its IP address, which will allow you to see it from anywhere on the internet.

Connecting to your EC2 instance

The next step is to connect to your new instance. I've always used PuTTY to do so, but with the recent Windows update that installs OpenSSH by default you can also connect via the command line. We'll cover both in this section.

If you've already been through Part 1 and have downloaded the PuTTY client, go ahead and boot it up via the start menu.

The PuTTY client

There are a LOT of options and features in PuTTY, but we don't need the vast majority of them. All we need to do is provide a username, our EC2's IP address, and our private key, and we're good to go.

The username and IP address are easy. If you used the Ubuntu AMI, AWS defaults the username to "ubuntu". You can find the IP address in the EC2 instance dashboard, under the IPv4 Public IP heading. Both of these go into the Host Name field using the following format:

username@IPaddress

Which will look something like:

ubuntu@4.52.32.101

Lastly, we need to add our private key. We do that by going to the Auth tab in the Category menu (under Connection/SSH). The default settings can be left the same, but when we press the Browse button to add our key and navigate to the folder we stored it in, we find we can't actually use it. What gives?

It turns out AWS provides keys using the .pem format, but PuTTY only accepts the .ppk format. Luckily, PuTTY provides a tool as part of the installation process called PuTTYGen that will translate for us. Open it up, press the Load button to find & convert your key, and then Save Private Key to save the new version. PuTTYGen will complain about a passphrase, which you can add or not as you prefer, and then save it.

Back in PuTTY, add the new .ppk key and head back to the Session tab. You can save your login credentials by filling out the Saved Sessions field and pressing the Save button, which will keep you from having to fill everything out every single time. Once saved, Open the session to begin connecting...

...except nothing happens. We can't connect, and eventually the session will time out.

It turns out that AWS is providing an additional layer of security we need to edit. So log back into AWS, open up the EC2 service, and select Security Groups from the side menu.

AWS Security Groups

AWS security groups behave the same way as a firewall does: they allow you to manage the flow of traffic to services protected by them based on where the traffic is going to/coming from, and what port10 the traffic is trying to enter through. By default, inbound ports start off closed, which keeps all traffic out. We need to open a door.

Select the security group attached to your EC2 instance and select the Inbound tab. Press the edit button to open up the edit wizard.

First, we need to make a hole for our SSH traffic to enter through. Delete the default rules and create a new rule of type SSH. The wizard will automatically fill out the port & protocol fields (22, TCP), leaving you to fill out your IP address. You can fill it out manually, but it's much easier to select the "My IP" option from the source dropdown and let the wizard do it for you.

We have now opened a hole in the firewall we can connect through. Save the new rules and try to connect again. This time, it should work:

Et voila!

Let's go ahead and add a few more rules while we're in here. We're going to need to allow web traffic from anywhere once we get our website running, so we need to add an HTTP and HTTPS rule11 that allows all traffic. If you're someone who works from a few locations, you'll also need to add additional SSH rules to include the IP addresses of your other networks. I wouldn't recommend allowing SSH connections from anywhere as you leave your EC2 instance accessible to SSH attempts from anywhere in the world. If you're the kind of person who lives on Starbucks & hotel wi-fi,12 look into getting a VPN service and allowing SSH from the VPN's IP address instead.

Connecting via the command line

NOTE: Even if you're not interested in using the CLI to connect to your instance and prefer to stick with PuTTY, if you are a complete newbie to shell commands it's worth reading this section as we'll cover a few basic shell commands you'll need moving forward.

An alternate method for connecting to your instance uses the Command Line Interface (CLI) and OpenSSH, an open-source SSH tool that comes default with Linux, Mac, and even Windows 10 machines. If your computer doesn't have OpenSSH, it's worth getting--the utility also comes with secure copy (scp) and secure FTP (sFTP), which are both quite handy to have in a pinch.

To use OpenSSH, open up your preferred CLI interface. The default program on Macs is called Terminal; Windows have both Command Prompt and Powershell; I use PowerShell as it has a lot more support and a few nice features that make things a little more manageable when using it. You'll be greeted with a line of text that looks something like this:

The line where your cursor is blinking shows the folder you're currently in. C:\Users\Grahame can be navigated to via the File Explorer and we can see all the folders within the Grahame folder. We can also use the command line to see what files are in the Grahame folder. Type the following into the command line and press enter:

$ ls

You should see a list of all the files and folders in your current folder. Excellent! You can change folders using the cd command. For example, to change into the Videos folder, I type13

$ cd Videos

and here we are. My cursor is now blinking next to C:\Users\Grahame\Videos and I can now run commands in the Videos folder.

You can jump directly to a specific folder by following cd with the path name of the folder you want to access. We need to find our private key, so use cd to travel through your folders until you reach the folder with your key. Once you reach the right folder, use ls again to confirm the key is there, and then check that OpenSSH is installed and running properly by using the ssh command:

$ ssh

If OpenSSH is properly installed, you'll be presented with a list of command flags: -b, -c, -D, etc. The command flags allow us to modify a command and pass it additional parameters and information. To use OpenSSH with a key file, we need to pass it the -i flag with the name of our private key (including the .pem). We'll use the same host@IPADDRESS path for our connection, and we'll let OpenSSH handle the rest as the defaults are good enough for us. So our command is:

$ ssh ubuntu@IPADDRESS -i private_key.pem

If it works, you'll connect to your EC2 instance (you may have to accept a warning about your certificate identity), and we'll be good to go.

I'm in! Now what?

We now have a running EC2 instance we can securely connect to. We can run shell commands within the instance the same way we can on our local machine. And we can control the AWS security groups to change the flow of traffic to and from our instance.


Part 3 – NGINX

Welcome back. We'll be installing NGINX (pronounced "engine-X") to use as a web server and setting up our DNS to use our domain name.

In the previous section, we set up an EC2 instance to run our website. Using the physical hardware analogy14 from earlier in the series, we have bought a computer, connected it to our firewall, and poked holes in the firewall so we can connect to it from the internet. Now, we need to install some software to actually make the website work.

NGINX Overview

What is NGINX? Well according to the folks who wrote the thing:

NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server.

Errr...cool? What does that actually mean? Let's break it down as best we can:

HTTP Server

At its most basic, a server is a piece of software that you ask for things and it delivers them to you.15 Just as you ask a server in a restaurant for items off the menu and receive a dinner, same thing happens with a server. You send the server a request, e.g. "Give me the web page at grahamewatt.com" and it delivers the code necessary for your browser to render that web page. Also like in a restaurant, you may not actually like what you get served, but you're getting what you asked for no matter how good the meal is or nice the web page is. If you want something different, you need to ask for something else. We need a web server so that when people ask for the web pages located on our domain, we can serve them something tasty.

HTTP just happens to be the protocol used to ask for things across the internet; HTTP will also cover HTTPS, which NGINX supports. You can read more about it in Part 2

Reverse Proxy

A proxy in networking is the same as in real life—it's a computer acting on behalf of another computer. Most people use proxies without realizing it whenever they're on a wi-fi network—all of your page requests go via your router which actually sends them out into the wider world on your behalf, receives the response and then delivers it to you. Your router is a forward proxy and is behaving as your agent to the web. The critical advantage of a proxy in your home network is that it can manage the traffic of everyone on the network. You get the blog you wanted to read and your anime-loving roommate gets episode #1,259,352 of Naruto, and neither of you have to worry about accidentally receiving each other's material.

A reverse proxy is a backwards forward proxy.16 Instead of making requests on behalf of a user, a reverse proxy receives requests on behalf of a group of servers, correctly sorts the traffic, and returns the response back to the user. What this means is that you can have multiple servers hosting your website, but your user never has to worry about which one is actually filling the request—they always get the cat photo they were looking for.

We're not going to have multiple web servers, so we don't have to worry about complex proxy networks. We'll just use NGINX to convert incoming traffic to HTTPS and leave it at that.

IMAP/POP3 proxy server

Email. We're not setting that up, so we can ignore this.

Installing NGINX

Before installing NGINX, we need to get our bearings. SSH into your EC2 Instance (Part 2) if you're not already logged in. In addition to all the text giving you details about Ubuntu and your instance's status, you'll see the entry field has changed to something like this:

ubuntu@ip-172-31-84-81: $

This is how Linux does things, but it's essentially the same idea as your Windows or Mac CLI. You're in a folder in the computer's file structure, and can navigate using the cd command. Linux also helpfully tells us our username (ubuntu) and internal host (ip-172-31-84-81, less useful). The ubuntu user is one of several default users and the one AWS makes you log in with by default.17

The first thing we want to do is switch to the root user, which will give us full access to all parts of the system and let us run the commands we need to. Type:

$ sudo su root
  • sudo: "Super user do." Until we have root access, we are limited to doing things on our instance based on the permissions our current user has. sudo allows us to run commands as though we had full admin privileges, which is exactly what we need to change to the root user.

  • su: "Switch user." We follow it with the name of the user we wish to change to, hence su root.

Now we have root access, let's make sure we have all the latest updates. Type:

$ apt-get update

apt-get is a package manager and installation utility which comes default with Ubuntu installs. It's quite powerful, allowing us to install, update, upgrade, configure, and uninstall any software registered with the manager.18 We'll use it next to install NGINX:

$ apt-get install nginx

You'll be asked to confirm, and then NGINX will be installed. It won't be running by default, so start the service:

// EITHER
$ service nginx start

//OR
$ /etc/init.d/nginx start

And we're up! We can check to see if it's working properly. Enter the public IP address of your EC2 instance into your web browser. If NGINX is running properly and you correctly configured your security groups, you'll be greeted with the following web page:

We now have a running web server! The default page is being loaded from /var/www/html/index.nginx-debian.html. We can use nano, a file editor program, to edit it. /var/www is the default location for websites in NGINX. Change to the /var/www/html directory using cdor type the full address when using the nano command:

$ nano /var/www/html/index.nginx-debian.html
If you press the tab key after typing the first few letters of a file or folder, ubuntu will auto-complete the file name. Much faster than typing "index.nginx-debian.html"

We can edit the HTML of the home page using the nano editor. Change one of the text lines, and close the editor (ctrl+x). Make sure you save it as index.nginx-debian.html. Reload your website to see your changes.

Managing the DNS

Let's take a quick minute to set up our web domain so we don't need to use our IP address to find our website. Exact instructions will vary depending on where you purchased your domain and how the registrar/DNS host is set up; however they will all allow you to accomplish the same thing by adding DNS Records.

The Domain Name Service (DNS) is, to use a classic analogy, the phone book of the internet. Just as folks used to use the Yellow Pages19 to look up phone numbers, internet users use DNS to look up the IP address of a website by searching for its name and then dialing the IP20 associated with the web domain. Right now, we have an entry in the phone book, but it's just our name—there's no phone number IP address associated with it.

To point our domain to an IP address, we need to add an A Record. If you're using AWS' Route 53, this can be done by pressing the "Create Record Set" button. Set the name to @ (or leave it blank, if allowed) and the value to your IP address, and save the record.21 It's also good practice to add a record to handle the www. subdomain. Either add another A record pointing to your IP address with name as www, or add a CNAME Record pointing www to your root domain (mywebsite.com).

Save the changes and give them a few minutes to propagate. Then test your domain changes by opening up a new browser window and going to your website. If it works, we'll be back at the NGINX server page and we can move on to getting NGINX all set up.

Configuring NGINX

We've installed NGINX but we still need to get it configured for the website we want to build. First, we want to create a folder for our new website so we can keep everything together. cd into /var/www if you haven't already, and create a new folder using the "make directory" command:

$ mkdir mywebsite.com

We're naming the website after our domain name for clarity's sake; you can name it whatever you want. cd into your new folder and create a new test home page using nano:

$ nano index.html

Nano will create a temporary file called index.html which we can now edit. Write a quick test page and save it using the editor. You can also copy-paste the one below; to paste from the clipboard use ctrl+shift+v.

<html>
  <head>
    <title>Welcome to mywebsite.com!</title>
  </head>
  <body>
    <center><h1>mywebsite.com is working!</h1></center>
  </body>
</html>

Save it as index.html and close nano. The next step is to tell NGINX about our new website.

The Config File

cd to /etc/nginx/sites-available, and check out the default configuration file using nano default.

The default configuration file

Make friends with the config file. This is where pretty much all of our efforts involving NGINX will center around. We won't edit the default config file—it's good to have as a reference. So close nano and let's duplicate the default file using the copy command:

# replace mywebsite.com with your domain
$ cp default mywebsite.com

Open up our new config file and delete out the commented lines (start with a #) above and below the main server{...} block. You should end up with something like this:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
}
Leave the section about PHP alone if it's included in your default config file. We'll need it later and we don't want to type it all out.

Whenever NGINX receives a request from a user, it checks the configuration files associated with the request and uses the instructions within the config file to serve the page. NGINX can run several virtual servers at once, each with instructions defined in a server {...} block. Within each server block are the configuration instructions for that server. To make our site work, we need to have the following commands defined:

  • listen: Tells NGINX what port to listen on. 80 is the default for HTTP, which matches our security group rules. The default_server parameter is an optional rule that tells NGINX what to serve if it can't figure out how to deal with conflicting information.

  • server_name: The domain (or IP address) of our site. Any requests coming through the listening port that match the domain of the server_name will continue to be processed within this block. You can have several server_name entries in case you want multiple domains or subdomains to behave the same way; e.g. server_name mydomain.com www.mydomain.com; will cause requests that omit the "www" to behave the same way22 as those that remember to add it.

  • root: The root folder of our website. We created our website folder earlier at /var/www/mywebsite.com.

  • index: The home page of the website. We created ours earlier at index.html. You can also add index.php in anticipation of installing Wordpress, which uses PHP to deliver web pages.

  • location: location tells NGINX what to do for specific requests within our website. Thankfully, we don't have to define location rules for every web page we have. Instead, we can use location / {...} to define a generic behavior for all traffic that ends up at our root folder.

  • try_files: The try_files command tells a request that makes it into the location block to go to the designated locations. We can leave the defaults as is; our current command checks the request path and if it doesn't exist delivers a 404: Page Not Founderror to the client.

It's also a good idea to log site access and errors using the access_log and error_log commands:

server {
    ...
    access_log /var/www/mywebsite.com/logs/access.log;
    error_log /var/www/mywebsite.com/logs/error.log;
    ...
}

NGINX will automatically create a folder in your site folder and update log files as activity occurs on your site.

Fully configured, our config file should look more or less like the following:

server {
    server_name mywebsite.com;
    listen 80 default_server;
    root /var/www/mywebsite.com;
    index index.html index.htm index.php;

    location / {
          # First attempt to serve request as file, then
          # as directory, then fall back to displaying a 404.
          try_files $uri $uri/ =404;
     }

    access_log /var/www/mywebsite.com/logs/access.log;
    error_log /var/www/mywebsite.com/logs/error.log;

}

Save it and restart NGINX ( service nginx restart ). If a restart fails, you have typos or errors in your config file. If it succeeds, we're good to go. All we need to do now is tell NGINX about our website. NGINX only knows about server rules in the /etc/nginx/sites-enabled folder, so let's create a symbolic link23 from sites-enabled to our configuration file:

$ ln -s /etc/nginx/sites-available/mywebsite.com /etc/nginx/sites-enabled/mywebsite.com
Why didn't we create the configuration file in sites-enabled instead of linking sites-enabled to sites-available? Mostly convention; when NGINX is managing multiple sites and applications it helps to be able to disable them without deleting their configuration. If you link from sites-enabled, you can turn off a site or app by simply deleting the link instead of removing the whole site.

Restart NGINX and head to your domain. If you did everything properly, you'll be greeted by your new website:

Ta da!

We've a long way to go still, but this is certainly a milestone to celebrate! We have now set up the L and the E of our LEMP stack. In Part 4, we'll switch gears and focus on setting up a MySQL database (M) so we can install Wordpress (P). We'll also set up our SSL certificates and edit NGINX so that all traffic is redirected to HTTPS.


Part 4 – Databases

This article was previously titled "Part 4: MySQL, Amazon RDS, and PHP." We set up a second instance for a database to power our site, which is likely overkill. I recommend you read the Epilogue before proceeding—most readers will find it more prudent to follow the instructions laid out over there.

AWS can be used for so many things. A person could spend a lifetime playing with all the different tools they make available to you in the cloud. But you ain't got time for that, so read on for part four of my series on setting up a website using only free infrastructure. We'll be getting a database set up to power the Wordpress CMS with, the final piece of groundwork necessary to launch our site.

Last time, we installed NGINX, configured the DNS to use our domain name, and got a primer in how NGINX manages websites and serves pages to visitors. We also got familiar with the command line, and computing without help from the windows and folders we're so familiar with. Doing so takes care of the 'L' and 'E' in 'LEMP', which means the 'M' is up next: MySQL on Amazon RDS.

Why do we need a database? (CMS Overview)

We discovered last time that we can directly edit and update web pages within NGINX, and serve them to our visitors, no database necessary. While editing things in nano/vim isn't exactly a quick process, it's not at all unreasonable to think we could manually code our web pages locally, and use an FTP client like FileZilla or even good old secure copy to get them up to our web server. We could even install things like NodeJS or PHP to give our site cool modern functionality and never go anywhere near a database.

So what gives? Why set up a database?

The answer, in a nutshell, is WordPress. WordPress is a content management system, or CMS, and is by far the most popular one on the internet. True to their name, content management systems manage content: files, photos, web pages, videos, music, etc. Designing, launching, and maintaining a website is a LOT easier when using a good CMS, to the point where there are literally thousands of tutorials on how to build a WordPress site24 out there. WordPress has the added advantage of being highly customizable thanks to a wide universe of 3rd-party plugins, most of which are free.

Since WordPress will be managing our content, it needs somewhere to store it. Individual files (pictures, movies) can be stored on the server25 in the file structure, but posts and pages are a little trickier. WordPress uses PHP, and serves web pages based on matching rules in template files with the relevant information for that post or page. The template files get stored on the server, but the information goes in the database so it can be queried and delivered as fast as humanly possible.

This is not a primer26 on database administration, or even how databases work. And to be honest, it's completely irrelevant to what we're trying to do here. AWS's Relational Database Service (RDS) lets you set up all the config without writing a single line of SQL, and WordPress will configure the database for us. We just need to get everything wired up.

Setting Up AWS RDS

Setting up a free RDS instance is actually one of the easiest things we're doing in this series. Navigate to the RDS service and press the big Create Database button on the dashboard to get started.

Choose Standard Create, MySQL, and Free Tier in the first three sections. The default version of MySQL is fine for our purposes (at the time of this writing it was 5.7.22). We will need to configure the database credentials in the settings menu, and double check our connectivity settings to make sure our EC2 instance can see our database.

Fill out the settings with a database name, and a username for the database administrator. I used wpdatabase and dbadmin for mine, but it can be anything you can remember. Fill and confirm a secure password; MAKE SURE YOU WRITE IT DOWN. You'll only need to type it in once, so it's fine if it's hypercomplicated.

Under config, review the default settings. If this is your first time with AWS, you should only have the default VPC available. If you've set up other VPCs27 in past projects, make sure you're launching your database in the same VPC as your EC2 instance. Also make sure that it has the same security groups assigned as your EC2 instance.

A virtual private cloud (VPC), is best thought of as a room in a house. Everyone in the room can see and speak with one another, but they cannot see and speak with folks in other rooms without opening windows and doors. In this analogy, our various instances will be able to see and speak with one another since they are part of the same VPC, but if we launched another EC2 instance in a different VPC, we would not be able to connect the instances without some extra networking work. The analogy breaks down somewhat when you start hosting VPCs within VPCs, but hopefully the main concept is clear. You gotta share a cloud with someone to talk to it.

I also give my database access to the same security groups as my EC2 instance so I don't have issues later because I forgot to poke holes in my security group. I think this is technically not best practice, but in reality if an attacker got this far we're completely pwned anyway, so it doesn't matter too much.

The goal. Make sure to also add your EC2 instance security group along with the default one.

You can set some additional configuration preferences as suit you. I turned on error log and general log, left auto backup and auto minor version upgrade enabled, and turned on deletion protection.

Also buried in the additional configuration preferences is the Initial database name field. You must set this! We can in theory do this later, but it's easier to do it now

Once you're all set, launch the database instance to finish up.

AWS will begin spinning up your shiny new database instance. Once the instance is running, it will automagically create an empty database we can connect to. It doesn't take AWS too long to set up, so while it does that, let's poke some more holes in our security group so that AWS isn't blocking the database and Wordpress from talking to each other.

Go back to the EC2 instance dashboard, and edit the security group assigned to your instance. We need to add an inbound rule for port 3306 (the MySQL port):

  • Type: MySQL/Aurora

  • Port: 3306

  • Source: The security group.

It's a little weird, but essentially your database sends traffic out into the VPC, and it is filtered by the security group before it reaches the EC2 instance. So we need to allow the traffic back in; hence our new rule.

Installing MySQL

We're going to run WordPress in our EC2 instance, so SSH back into your web server. Since we set up our database to run MySQL, we'll need to install the appropriate software on our web server so we can issue the database commands. It's one line:

$ sudo apt install mysql-server

MySQL installed! On to the next thing!

Well, not really. The installation is up and active, but there are some security issues we should spend a moment fixing. Run the included security script:

$ sudo mysql_secure_installation

Respond yes (y) to everything until presented with the password policy validation menu:

There are three levels of password validation policy:

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:

If you entered a strong password earlier, you should be able to enter 2. Otherwise, select whatever tier is appropriate. The script will ask you to set the password; go ahead and retype your database password. Continue spamming y until the script completes.

Installing PHP & Configuring NGINX

One of the upsides of NGINX is the fact it comes completely stripped out, keeping it lightweight and free of bloat. In this case, it's also a minor downside--NGINX cannot understand PHP programs since it lacks a PHP processor. However, it's a simple enough install to get the necessary package, php-fpm. While we're at it, let's go ahead and add the PHP MySQL extension, php-mysql. We'll need it later.

$ sudo apt install php-fpm php-mysql

And everything is installed! However, we still need to tell NGINX that it now has the ability to process PHP. So we're headed back to our handy-dandy config file:

$ sudo nano /etc/nginx/sites-available/mywebsite.com

We need to make the following changes:

  • Uncomment the PHP sections, specifically the location ~ \.php$ and location ~ /\.ht sections

  • Delete listen [::]:80 default_server;

  • Change the server_name to mywebsite.com

  • Change the version of fastcgi_pass from .../php7.0-fpm.sock to 7.2

  • Add index.php to the list of indices

Our new configuration should look like this:

server {
        listen 80 default_server;
        root /var/www/mywebsite.com;

        index index.html index.htm index.nginx-debian.html;

        server_name mywebsite.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        location ~ /\.ht {
                deny all;
        }

        access_log /var/www/mywebsite.com/logs/access.log;
        error_log /var/www/mywebsite.com/logs/error.log;
}

Test for typos with sudo nginx -t, save, and reload nginx with sudo service nginx reload.

We can test that PHP was successfully installed by creating a quick info page. Create a new file in your /var/www/mywebsite.com folder called test.php and put the following in it:

<?php
phpinfo();

Save the file and then navigate in your browser to mywebsite.com/test.php. If all is well, you should be greeted with the following info page:

That's it! The LEMP has been launched! An open source miracle has occurred!

Well, sort of. But our infrastructure is now fully configured and ready for us to set up WordPress. In Part 5 we'll investigate just how to set up WordPress so it can use our networked RDS instance and our EC2 LEMP server, take care of security issues & install SSL certificates, and set up a private CDN using AWS s3 and CloudFront.


Part 5 – Wordpress

You've made it this far. I've made it this far. We've made it this far together.

Welcome to the final installment of Building a Free Website. We have a database, we have a server, and we've connected them all up. Now the time has come to install WordPress and launch our free site for the world to see. We'll also take care of some security things and set up our very own CDN.

*epic music plays*

As the series has progressed, we've gotten a bit more technical and I've tried to hold your hand a bit less. We'll be kicking that up a notch here as well.

Now, without further ado, let's get to it.

Installing WordPress

WordPress.org (not to be confused with WordPress.com, which is a whole other thing28) is the home of the WordPress open-source content management system. We'll want to grab the installer from their site and put it into our web server. Once we have it up and running, we're going to configure NGINX to route HTTP requests to WordPress, which will do some magic under the hood and return a fully formed webpage, complete with dynamic theme to the visitor.

If we were downloading it onto our computer, we'd need to visit the website, download the installer, and run it. However, we have a Linux server, and package managers to make the whole thing easier for us.

SSH into your EC2 instance and cd to your website folder at /var/www/mywebsite.com. Once there, we'll need to download and install WordPress, and we can do so through the magic of wget (use sudo if you aren't the root user):

$ wget https://wordpress.org/latest.tar.gz
$ tar -xzvf latest.tar.gz

wget goes to the WordPress site and downloads the latest stable build of WordPress for us. We use tar to unzip the compressed archive file... and that's it. WordPress is installed!

That was easy

  • If your EC2 instance doesn't have wget, you can install it with the following command: apt install wget.

  • You need to be a user with root access to download and install WordPress (and wget). Either prepend sudo to the previous commands or sudo su root before starting.

WordPress will have self-created a directory, which will be the home of our website. However, we need to move it up to the root of our website directory, as per the installation directions, otherwise it won't work. We want to copy all of the contents of the wordpress directory into /var/www/mydomain.com. We can get rid of the downloads afterwards.

$ cp -a wordpress/. .
$ rm -R wordpress
$ rm latest.tar.gz

WordPress has been installed... but we need to configure it to work with our AWS setup. Specifically, we need to tell it how to talk to our RDS instance. We do that by creating and editing the wp-config file, which provides all the various parameters and configuration options WordPress needs to keep track of. Our install comes with a sample config file, so copy it into a new active file:

$ cp wp-config-sample.php wp-config.php

Open our new wp-config.php with nano or vi and scroll down to the MySQL settings section. You'll see four define() blocks, each with two parameters. We need to update the second parameter of each block with our database information from Part 4:

/** The name of the database for WordPress */
define( 'DB_NAME', 'wpdatabase' );

/** MySQL database username */
define( 'DB_USER', 'dbadmin' );

/** MySQL database password */
define( 'DB_PASSWORD', 'your_password' );

/** MySQL hostname */
define( 'DB_HOST', 'wpdatabase.cabthgz5oiyo.us-east-1.rds.amazonaws.com' );
DB_NAME is the name of your database, not your database instance. When I set them up I used the same name for both, but if you used different ones make sure to use the correct name. DB_HOST is the full URL of your database instance.

Next, we need to secure our connections by filling out the Authentication Unique Keys and Salts section. WordPress uses these for pretty much anything privileged involved in running the website (i.e., all site administration). To do so, simply copy salts from WordPress' salt generator and paste them in place of the existing ones already in the file (if you're using nano: Ctrl + Shift + K to delete the placeholder lines; Right Click to paste the new ones).

// Not real keys. Obviously

define('AUTH_KEY',         '5KQCDaR3`Z`fn*N#,>c>orRvr2T.=R6%=Vuo=6+.2T,1f9rW+O(RekX3+gx:31t>');
define('SECURE_AUTH_KEY',  '#7<86DjJ$aQr,-8[L+Ty%iwL~Xc/>po]R,S3ef/2Z;OnGSnu:Mm1lHPe*[o|UP.+');
define('LOGGED_IN_KEY',    'FE&-XI=v1l<)v*K!(=6azJBDHT^o^d<NjLys-D=4&+ [ .^=ebN/md-[4>HCt.wU');

Save the file and restart NGINX. If everything is configured properly, you should now be able to go to your domain and you'll be greeted by the WordPress launcher page. Follow the steps and you'll have a WordPress site ready for configuration and launch!

From here, you can get started building your website. You can draft pages, download and install themes, write blog posts—the world is your oyster. However, stay with us—we're not quite done dotting our I's and crossing our T's just yet.

HTTPS Always: SSL Certificates

When doing anything on the internet, privacy and security should always be in the back of your mind. Our site management and servers are pretty well protected by our use of SSH and complex passwords (built on one of the most robust and secure cloud platforms out there), so we don't need to worry about unauthorized users breaking in and defacing our website or stealing our AWS credentials. However, our website is public in the most literal way possible: whenever someone visits our site and asks for a page (a GET request), we send the relevant HTML completely unencrypted.

This is not the end of the world—after all, our website is public, so if someone was spying on our user,29 they could figure out what the user was looking at by simply visiting the same page as they did. What is more problematic is the fact that sometimes users want to input information into a website. Information like passwords. Like, say, on an admin login screen...

Oh snap!

Yep. You sent your password unencrypted to your webserver when you logged into the admin portal at your mydomain.com/login page. The good news is you did not get your password stolen.30 But this is a gap, and we need to plug it.

Enter the Secure Socket Layer (SSL). Similar to the public key/private key method of authentication in use when we access our EC2 instance via PuTTY, setting up our website with a SSL certificate will allow our website and any visitors to conduct their browsing session via an encrypted channel (HTTPS), instead of sending things in plain text over the internet (HTTP).

Source: Savvy Security

SSL certificates are issued by a number of registrars, who are responsible for confirming the domain belongs to the requester and maintaining those lists and records. In the old days, companies would charge for this service (and most still do, especially for more advanced SSL certifications). But in this modern day and age, we have Let's Encrypt.31

Installing an SSL Certificate

Let's Encrypt provides a free automated SSL management tool called Certbot which does everything we want (and then some). Certbot will install our certificate, update our nginx.conf file to redirect all HTTP requests to HTTPS, and set a timer to re-run the protocol every 90 days to keep the certificates fresh and active.

To get started, grab the Certbot repository and add it to your EC2 instance. Accept any TOS or other conditions, and install using apt:

$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt install python-certbot-nginx

Certbot is now ready to go. Provided you've been following along, it should automatically be able to find your website, located at /etc/nginx/sites-available/mydomain.com, and use the info in the conf file to issue the certificates. If you did anything weird/different, go to your site's conf file and check that you have both a www and root entry in the server_name line.

// Your conf file should have this line somewhere
// If it doesn't, add it/fix it, save, and restart nginx

// ...
server_name mydomain.com www.mydomain.com

Certbot will also need port 443 open on our firewall. Port 443 is the default HTTPS port, and should already be open (as of this writing, the EC2 image used by AWS came with 443 already configured). You can check with the command sudo ufw status.32 In the To column, you should have entries for Nginx Full & Nginx Full (v6). If you only have entries for Nginx HTTP, you need to delete and replace them:

$ sudo ufw allow 'Nginx Full'
$ sudo ufw delete allow 'Nginx HTTP'

We are now finally ready to let Certbot work its magic. Run the NGINX plugin for your domains to get a certificate:

$ sudo certbot --nginx -d mydomain.com -d www.mydomain.com

Certbot will prompt you for some things (email address, TOS confirmation), and then will ask you if you want to redirect HTTP traffic to HTTPS.

The answer is yes. Yes, you want to redirect traffic. Otherwise why did you bother reading this section?

Certbot will run, and will probably reload NGINX. Then it will be done, and will give you the output info, along with some links to donate33 to Let's Encrypt and the EFF. Certbot will have also automatically set up the 90-day renewal process by creating a cron job in our server, which will run the script we just ran every 90 days. You can test the script by doing a dry run:

$ sudo certbot renew --dry-run

And that's it! Reload your site and you should see the little padlock in the browser bar that indicates success. You can also run security tests (Google SSL Server Test for a whole host of tests) to see how your site stacks up.

The mark of a job well done

CloudFront CDN

By any measure, setting up a content delivery network (CDN) is completely optional. If you don't intend on using your site for much more than a contact form and an "About" page, I wouldn't blame you for skipping this section. But if you intend to do things that will build a media library over time (e.g., write a blog w/ lots of images, distribute your e-book), then I highly recommend setting up a CDN. And, thanks to the magic of free tier, we can do it right here on AWS for FREE!

Amusingly, this is actually the most involved process in this article. None of the steps are particularly hard, but there are several of them. We need to:

  1. 1.

    Set up an S3 bucket to store our media

  2. 2.

    Set up a CloudFront Distribution

  3. 3.

    Create a subdomain for our CDN

  4. 4.

    Install and configure Offload Media Lite, syncing our website with our CDN

The AWS Part

The first three steps will take place in AWS, so go ahead and log into the console. Navigate to the S3 service and press the orange Create Bucket button. We have a few options covering name and access. Since the items in this bucket are for public consumption, we want to turn off the Block all public access setting.

As for name? It's going to be the same as our subdomain. This is not optional—it's a quirk of how Cloudfront works and if the bucket is not properly named, we cannot issue it an SSL certificate nor can we properly point Cloudfront to serve files from the bucket. I recommend something simple (e.g., cdn.mydomain.com). You can ignore advanced settings, and press Create Bucket to finish up. The bucket should appear in your bucket list as "Public," meaning that items within the bucket can be viewed anywhere on the web—though the bucket console itself cannot. You can test by uploading an item to the bucket via the console, selecting it, and pasting the Object URL into an incognito browser window. You should be able to see the file you uploaded without needing to log in.

Next, head over to Cloudfront34 and press the Create Distribution button in the main dashboard. Choose a Web delivery method to find yourself presented with a whole bunch of settings to address. Thankfully, the defaults will mostly work for us.

Put your S3 bucket in Origin Domain Name and fill out an Origin ID that will help you keep track of it. Next, scroll down to Viewer Protocol Policy and change it to "Redirect HTTP to HTTPS."35 Finally, scroll down to the Distribution Settings menu and add our subdomain to Alternate Domain Names.

What we're going for

Our distribution will not launch without an SSL certificate to secure it. AWS will happily do this for us. Click the Request a Certificate with ACM button to launch the AWS Certificate Manager (ACM) in a new tab. The wizard is pretty straightforward; simply add our new cdn.mydomain.com domain, and click through to "Step 5: Validation" (we can leave the defaults alone). ACM will show our newly certified domain as "Pending." It will periodically check our DNS until it finds the CNAME record it provided. You can manually copy it over, or you can let AWS do the heavy lifting for you—expand the field and press the Add to Route 53 button to automatically copy the record into the DNS. Doing so will also trigger another test by the ACM, so everything should all sync up in a matter of minutes.

Couldn't we have done this for our other SSL certificates? Sure, but it never hurts to learn two different ways of doing things. In addition, our method of using Certbot within our web server is applicable to cloud hosts and other hosts outside of AWS, and keeps our DNS records a little bit tidier.

Once the SSL certificate moves from "Pending" to "Issued," go back to our CloudFront tab. Select Custom SSL Certificate and add our new certificate to the field.36 Check everything over once more, and create the distribution. It'll take a few minutes to spin up, but we can move on while it does.

With the bucket and distribution set up, we need to make changes to our DNS so that when our images are linked into our site pages from cdn.mydomain.com, the traffic is properly directed to Cloudfront and the image. Grab the Domain Name from our distribution ([ID].cloudfront.net) and create a CNAME record for cdn.mydomain.com with [ID].cloudfront.net as the value.

The WordPress Part

We are in the home stretch. All the infrastructure has been set up. Our website now looks just like our diagram. All we have left to do is connect our website to S3, and for that we'll use Offload Media Lite.

As with any WordPress plugin, we can download and install them directly to our website from within the WordPress CMS. Log into your website and open the Plugins page from the left menu to see your current plugins. WordPress automatically comes with a few defaults; you can explore, add, or remove them at your leisure.

To get the Offload Media Lite plugin, press Add Plugin to visit the plugins catalog, and use the search function to find the plugin. Installation is easy as clicking Install Now—WordPress will automatically download and install the plugin for you. Once it's done, press Activate and refresh the page. If you check the Settings dropdown in the left menu, Offload Media Lite will have magically appeared, ready for configuration.

Bam!

Open 'er up, and fill out the fields in the Media Library tab as follows:

  • Provider: Amazon S3

  • Bucket: The name of your S3 bucket (cdn.mydomain.com)

  • Path: wp-content/uploads/

  • Custom Domain: cdn.mydomain.com

And turn all the switches to the "On" position. This will tell Offload Media Lite to move all files and images over to s3 whenever you upload them, organize them the same way WordPress would, and then remove them from your EC2 instance, saving space on our little hard drive.

Settings here at grahamewatt.com

"But wait! When I chose Amazon S3 for my storage provider, it said something about access keys?"

Oh. Yeah, I suppose it would.

After you save your configuration and try and test the plugin, it will fail.37 You'd think it should just work, since the server is within the VPC, but we need to create a "user" for Offload Media Lite to use to access the s3 bucket. We're done with configuration here in WordPress, but we need to make one final pit stop in AWS, in the Identity and Access Management (IAM) service.

The Other AWS Part (IAM)

Create a new user (Users --> Create User) and give it Programmatic Access. Call it something you can easily identify (e.g. "offload-lite"), and move to the "Permissions" step.

If you'd like a challenge, this is a good opportunity. We need to give the user the ability to PUT new items in our cdn.mydomain.com bucket, GET items from the bucket, DELETE objects within the bucket, and see a LIST of some or all of the items in our bucket. You can either create another security group, or just attach those rules directly.

If you can't solve it, or you'd rather just copy-paste the answer, take the following code and paste it into the JSON editor (Attach existing policies directly --> Create policy --> JSON):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:CreateBucket",
                "s3:DeleteObject",
                "s3:Put*",
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::cdn.mydomain.com",
                "arn:aws:s3:::cdn.mydomain.com/*"
            ]
        }
    ]
}

Click through the rest of the steps, and make sure to save the Access Key and Secret Key assigned to the user. If you lose them, we have to reset them, so keep them in a safe place (with your private ssh keys is a good option).

The keys go in your wp-config file. SSH into your EC2 instance, and navigate to the file. Add the following lines above the /* That's all, stop editing! Happy blogging. */ comment:

define('AS3CF_AWS_ACCESS_KEY_ID', '[ACCESS_KEY_ID]');
define('AS3CF_AWS_SECRET_ACCESS_KEY', '[SECRET_ACCESS_KEY]');

Save and close. To check it's working, refresh the Offload Media Lite settings menu. All errors should have disappeared. You can test it by uploading a file or image to your website through the Media Library in your WordPress CMS, and then looking for it in your S3 bucket. If there is a file or folders magically there that weren't before, you're all set!

Final Thoughts

Congratulations on building your free website! While it's a little more technically involved than most of the "start-your-own-website" posts out there, this website setup will be free38 for all of the next twelve months. Hopefully you've also learned a fair amount about how websites are put together and what goes on behind the scenes.

As someone who finds joy in building and creating, this was a wonderful project and has continued to pay dividends down the line. I didn't cover any of the things involved in designing or managing a website, and there are plenty of other things to explore involving setting up email, contact forms, comments, etc. There are free options out there for all of these things and more, and while they take a little more messing around with, I'm sure many of you will find the experience of tackling that challenge rewarding. You might even learn something in the process.


Epilogue

It feels like just a few weeks ago that I launched a free website, and shared the process with the world. But then I woke up to a bill from AWS, an unhappy reminder that time keeps on slipping, slipping, slipping...39

Earworm deployed (Image: Amazon.com)

Unfortunately, "Free Tier" is a bit of a misnomer, or at least a "subject to terms and conditions" kind of thing. Free web hosting was never gonna last forever, and so now it comes time to settle our accounts. If you've not got a free40 website up and running, check out the whole series first:

Otherwise, let's do what we need to do now that money is once again part of the equation.41 We're back with the (second) final part of How to Build a Free Website.

The Bill

I'll be the first to admit, I was not expecting the price tag on my first full month out of Free Tier services:

Ooof...

$26 bucks? For a website I can set up at Bluehost or Hostgator for $10? And I don't have to spend time updating things?

Well, this is a ripoff.

Still in shock, I was about four clicks away from exporting the site, nuking the AWS account, and moving everything over to one of the zillions of web hosts out there. I'd bought the domain from Google; they have a deal with Bluehost to automate setup AND you get a super easy email setup as well.

But then I stopped, and took a deep breath. I was missing something here.

Web hosting businesses all run off the same model (plus or minus): get a lot of cheap, stable servers (either by building their own farm or by paying for space on AWS, Azure, etc.), and rent them out. While they do get some advantages through volume discounts, complex shared configurations, and so on, the core of their model is entirely based around how much it costs to run a computer per hour. Even as an individual user, the idea that I was somehow spending 2-3x the money for the same computer time made ZERO sense—optimizations for a technology that's only changed so much in the last two decades could only be so good. Plus, cloud businesses have minuscule margins on basic computing systems because the competition is so fierce. Commoditized markets with zero delivery costs should mean commoditized pricing, even at the smallest scales.

So I looked at the line items, and found the culprits:

RDS, why must you hurt me so?

I'm getting slammed by RDS (database) costs. My EC2 costs are higher than I'd like, as they're break even with web hosting services for the same product and zero of the services. But there's no point in addressing the EC2 item if we can't do something about RDS.

To RDS, or not to RDS?

An RDS instance under the hood is actually just a specialized EC2 instance a customer pays a bit more for to get certain features that are nice to have when you know you'll be running a database. Both my EC2 instance and my RDS instance use t2.micro boxes, but I paid an extra $0.006/hour for my RDS instance, plus an additional $2.30 for some additional storage costs (presumably for backups and database snapshots).

The extra features are great if you're running a SaaS app in the cloud, storing business data, or doing other things where you need to keep your database on a different machine, ensure you've got that extra layer of protection, and so forth. If you're trying to run a simple WordPress website with two dozen pages and maybe 100 visitors a month, using RDS for your database is overkill in the extreme.

There's a second point here that the additional costs of RDS also masks. AWS does pricing on "compute hours," which is calculated as:

# of instances × # hours running42

What this means is that if you run two instances, you pay double what you would pay for a single instance. Obvious in hindsight, but surprisingly easy to overlook if you're not paying attention.

Clearly then, the move is to ditch RDS altogether, in favor of bringing everything into one single EC2 instance. I don't expect43 my traffic or content to balloon over the next twelve months, so I see no reason to increase the size or power of my existing EC2 instance. I'm simply going to export my database out of RDS, install MySQL in my EC2 instance, and reimport my database. After wiring WordPress up to the new, local database, I'll delete my RDS instance and save myself some cash.

Relocating Databases

Wouldn't it be great if we could somehow just copy-paste a database from one place to another? Ctrl+C, Ctrl+V, and move on with our life?

Actually, we can, or at least come close. All databases have an "export" function, which will give us a file we can then import into our new database. It's a few simple commands and then we're all set. If you've been following the series44 thus far, you'll have everything you need to get started.

First we need to get into our RDS instance. You can set up an SSH tunnel straight to the box (remember, an RDS instance is just an EC2 instance with some bells and whistles), but if you set it up properly you'll first have to reconfigure the security groups and then create a new tunnel from scratch. It would be great if we could get into another computer that's part of the security group, then go from there to the RDS instance.

Exporting our current database

Turns out, we've got something like that! SSH into your EC2 instance (which we know is in the group since it talks to the database). If you don't have it written down, you'll need to get all your database connection info from your wp-config.php file. You'll also need to install MySQL on your EC2 instance if it's not already there. It's a straightforward process; just run the following three commands:

$ sudo apt update
$ sudo apt install mysql-server
$ sudo mysql_secure_installation

You'll be prompted with a whole bunch of security questions. Create a password for the root user, and accept the defaults for everything else. Once you're done, check the status of the MySQL service with the command service mysql status.

Once MySQL is installed, we can connect to our remote RDS instance with a single command:

$ mysql -u wordpress -h wpdatabase.cabthgz5oiyo.us-east-1.rds.amazonaws.com -P 3306 -D wpdatabase

It should look pretty familiar, but let's break it down anyway:

  • mysql: the program we want to run

  • -h: the "host" parameter. This is the location of the computer running our database.

  • -D: the "database" parameter. We want to connect to a database on our host with the name wpdatabase

  • -u: the "user" parameter. We want to have the user permissions of the user wordpress

  • -P: the "port" parameter. By default, MySQL listens for connections on port 3306.

Give it a whirl and make sure you can connect (you'll be prompted for the database password). Once you know it's working, quit using the MySQL command \q (pressing Ctrl+C should also work). You'll end up back in your EC2 instance.

To actually export our database, we'll use a utility included with our MySQL installation called mysqldump, which uses the same syntax as MySQL does:

$ mysqldump -u wordpress -h wpdatabase.cabthgz5oiyo.us-east-1.rds.amazonaws.com -P 3306 -D wpdatabase > db-export.sql

The only changes here are the program name (now mysqldump) and a trailing command, denoted by the > character. The names and syntax might feel a little intuitive, particularly if you think of the > not as a "greater than" symbol but as an arrow pointing right. We are telling mysqldump to output the results of the command to a file called db-export.sql. You can name your file whatever you like, but make sure it has the .sql file extension for clarity and to avoid issues further down the line.

Run the command. It'll take a few seconds or even a minute or two; any longer and either something is wrong or your site is way too popular for this tutorial. Once complete, we can ls in our current folder to check the export file is where we want it to be.

Rebuilding our database

First, we need to set up our local MySQL install to receive our new database. We need to recreate the wordpress user, and take care of some general admin stuff. For a more detailed explanation of how to do this, check out Step Three of this excellent Digital Ocean article. For the quick and dirty version, simply run the following commands:

// start MySQL
$ sudo mysql

// update the root user to use a password (optional)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '[PASSWORD_FROM_INSTALL]';
mysql> FLUSH PRIVILEGES;

// create wordpress user
mysql> CREATE USER 'wordpress'@'localhost' IDENTIFIED BY 'PASSWORD';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'wordpress'@'localhost' WITH GRANT OPTION;

You'll notice that the commands once connected to MySQL take a different form. MySQL uses the SQL query language to perform all its operations, and has a small admin/operational database running in the background to make the program work. We use SQL to change the tables so that the app behaves as we want it to.

As it turns out, databases are also created using SQL commands. So to create a new database, we use the following SQL command:

mysql> CREATE DATABASE wpdatabase;

And thanks to mysqldump, we have a file full of SQL commands that will rebuild our database for us! We just need to tell MySQL to run it. Exit MySQL, confirm you're in the folder with our db-export file, and run the import with:

$ mysql -u wordpress -p wpdatabase < db-export.sql

Boom. Done.

All that remains is cleanup. Edit your wp-config.php file with the new database info, changing the 'DB_HOST' line to use 'localhost' instead of the RDS URL. Save, and go check out your website. It should be still up and running; in fact it should look exactly the same45 as it did before. When you're comfortable, stop your AWS RDS instance, and then delete it altogether (apparently AWS will automatically restart any database left off for seven days).

Final Thoughts

The other big pricing number was the cost of the EC2 instance itself. AWS has one option to allow you to reduce your costs there as well: pay up front. You can purchase a Reserved Instance credit for your EC2 instance, which lowers the cost by about 1/3. They've got a few different options, including pay upfront in full, pay partial upfront, 1-year, and 3-year terms. Not all options are available in all areas; I went with the 1-year/full upfront option as I intend to keep this site running for a long time still. By giving up scaling flexibility, which isn't really something I need, I can get rates less than what I would get at Bluehost or Hostgator.

The net final monthly bill? If you average out my EC2 costs on a month-to-month basis, I am now paying $6.58/month for my website. I save a whopping $36/year over using a hosting company, and I get the fun of messing around with AWS.

I do lose out on the support and maintenance however, so if you feel like you need or want those services it is worth migrating out of AWS entirely once your term is up. If you do choose to migrate out entirely, the process is much the same; you can also use one of the myriad of WordPress plugins to export46 the site and reimport it at your new location.

Whatever you decide, I hope you've enjoyed the process of building a website from scratch, and I look forward to hearing about your further adventures in website design!