Configuring HTTPS with NGINX on AWS
local graph
Chapter 17 — Configuring HTTPS with NGINX on AWS
Section titled “Chapter 17 — Configuring HTTPS with NGINX on AWS”17 Configuring HTTPS with NGINX on AWS
Section titled “17 Configuring HTTPS with NGINX on AWS”When it comes to deploying our applications, a lot of tutorials and books go through simple deployments and smooth over the concept of encrypting traffic to and from the server using HTTPS. However, HTTPS is essential and usually the biggest hurdle that a developer must overcome to get their website or API out into the world. While this book’s title is Rust Web Programming, it is essential to dedicate a chapter to truly understanding how HTTPS works so that you can implement HTTPS locally and then on the Amazon Web Services (AWS) cloud. This chapter will cover the following topics:
- What is HTTPS?
- Implementing HTTPS locally with Docker Compose
- Attaching a URL to our deployed application on AWS
- Enforcing HTTPS on our application on AWS
By the end of this chapter, you will be able to build infrastructure in Terraform code that can encrypt traffic and lock down unwanted traffic to our Elastic Compute Cloud (EC2) instances so that they can only accept traffic from the load balancer, which will be explained later in the chapter. What is best is that most of this is automated, and as we are using Docker to deploy our applications, you will be able to transfer this skill to any web project that you want to deploy in the future. While this is not the best implementation, as there are entire books dedicated to cloud computing, you will be able to implement a solid, safe deployment that will continue to serve users even if an EC2 instance is out of service, as the load balancer can route to other instances. It will also be able to scale if traffic demand increases.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle. Configuring HTTPS with NGINX on AWS
What is HTTPS?
So far, our frontend and backend applications have been running through HTTP. However, this is not secure and has some drawbacks. To secure the traffic between our browser and our NGINX server, we are going to have to ensure that our application is using the HTTP/2 protocol. The HTTP/2 protocol has the following differences from the standard HTTP/1 protocol:
-
Binary protocol: HTTP uses a text-based protocol, whereas HTTP/2 uses a binary protocol. A binary protocol uses bytes to transmit data as opposed to human-readable characters, which are encoded using the American Standard Code for Information Interchange (ASCII). Using bytes reduces the number of possible errors and the size needed to transfer data. It will also enable us to encrypt our data stream, which is the basis of HTTPS.
-
Compressed headers: HTTP/2 compresses headers when sending requests. Compressing headers has similar benefits to the binary protocol, which results in a smaller size of data needed to transfer the same request. The HTTP/2 protocol uses the HPACK format.
-
Persistent connections: When using HTTP, our browser must make a request every time a resource is needed. For instance, we could get our NGINX server to serve an HTML file. This will result in one request to get the HTML file. Inside the HTML file, there could be a reference to a CSS file, and this would result in another request to the NGINX server. It is also not uncommon to have a reference to a JavaScript file in the HTML file. This would result in another request. Therefore, to load a standard web page, our browser requires up to three requests. This does not scale well when we are running a server with multiple users. With HTTP/2, we can have persistent connections. This means that we can make three requests for the HTML, CSS, and JavaScript files in one connection.
-
Multiplex streaming: Making requests using HTTP/1 means that we must send our requests sequentially. This means that we make one request, wait for this request to be resolved, and then send another request. With HTTP/2, we use multiplex streaming, which means that we can send multiple requests at the same time and resolve them when the responses are returned. Combining multiplex streaming with a persistent connection results in a faster loading time. Any reader who used the internet in the 1990s will remember having to wait a long time for a simple page to be loaded. Granted, the internet connection back then was not as fast, but it was also a result of making multiple HTTP sequential requests with different connections to load multiple pictures, HTML, and CSS.
Now that we have explored the difference between HTTP and HTTP/2, we can explore HTTPS, which is built on top of HTTP/2. Before we go forward, however, it must be stated that security is a field in itself. Learning about the high-level concepts around HTTPS is enough to make us understand the importance of what we are implementing and why we take certain steps. However, it does not make us security experts.
Before we explore the steps of HTTPS, we need to understand what a man-in-the-middle attack is, because this attack inspires the steps of HTTPS. A man-in-the-middle attack is exactly what it sounds like: a malicious eavesdropper that can intercept communication packets between the user and the server. This also means that the eavesdropper can obtain encryption if they are passed over a network. Simply googling man-in-the-middle attacks will result in loads of tutorials and software that can be downloaded to implement such attacks. There are more caveats to security that are beyond the scope of this book, but to conclude, if you are hosting a website that you expect users to connect to and log in to, there is no excuse not to use HTTPS.
When it comes to HTTPS, there is a range of steps that need to be completed. First, before any requests are made to the server, the owner of the server and the domain must get a certificate from a trusted central authority. There are not many trusted central authorities around. What these authorities do is get some identification of the person who owns the domain and some proof that the person applying for the certificate owns the domain. This might sound like a headache, but a lot of URL providers, such as AWS, have streamlined the process using information such as payment details to send to the central trusted authority in the backend when you are pointing and clicking to buy the domain. We must fill in some extra forms, but if you have a working AWS account, this will not be too taxing. These central authorities are limited because anyone with a computer can create a digital certificate. For instance, if we were intercepting traffic between a server and a user, we could generate our own digital certificates with a key and forward them to the user. Because of this, mainstream browsers only recognize certificates that have been issued by a small number of recognized authorities.
Figure 17.1 – Chrome blocking access due to an unrecognized certificate
[figure outside: Figure 17.1]
It is not advised to proceed. Once the owner of the domain and server has the certificate from the central authority, the user can make requests. Before any meaningful data to the application is exchanged, the server sends over the certificate with the public key to the user. The user then creates a session key and encrypts this session key with the public key of the certificate, which is then sent back to the server. The server can then decrypt the key using the private key that was not sent over the network. Therefore, even if the eavesdropper manages to intercept the messages and get the session key, it is encrypted, so they cannot use it. Both the server and client can check the validity of mutually encrypted messages. We can use the session key to send encrypted messages to and from the server and the user, as seen in the following diagram:
Figure 17.2 – Steps required when making an HTTPS connection
Do not worry—there are packages and tools that will help us manage the HTTPS process; we will not have to implement our own protocol. You will understand why we must carry out certain steps and how to troubleshoot problems when they arise. In the next section, we will implement a basic HTTPS protocol with NGINX locally.
Implementing HTTPS locally with Docker Compose
Section titled “Implementing HTTPS locally with Docker Compose”When it comes to implementing HTTPS, most of the work is going to be achieved through NGINX. Although we have worked a little with NGINX, the NGINX configuration is a powerful tool. You can implement conditional logic, pull variables and data from the request and act on them, redirect traffic, and much more. In this chapter, we are going to do enough to implement HTTPS, but it is advised that, if you have time, read up on the fundamentals of NGINX configurations; reading material is provided in the Further reading section. For our NGINX .conf file, we have the following layout:
#ingress/nginx.conf events {
[figure outside: Figure 17.2]
worker_connections 512; } http {
server { ... } server { ... }}Here, we can see that we have two server scopes in our http scope. This is because we need to enforce HTTPS. We must remember that our outside port is 80. However, if we want to carry out an HTTPS connection, we instead need to connect to port 443, which is the standard for HTTPS. Typing https:// into the browser will target port 443, and typing http:// into the browser will target port 80. If we allow port 80 to be open, loads of users will access our site in an unsecured way because some people will type http:// into the browser. Hackers would also spread the HTTP links around because they want as many people as possible not to use a secure network. However, if we block port 80, people who put http:// into the browser will just get blocked from accessing the website. It is unlikely that the average user is going to understand the differences in ports, look at what they typed in, and correct it. Instead, they are just going to think that the site is down. Therefore, we are going to have to listen to both ports 443 and 80. However, when a request is made to port 80, we are going to redirect the request to port 443 instead. Our first server scope can redirect with the following code:
#ingress/nginx.conf server {
listen 80; return 301 https://$host$request_uri;}Here, we can see that we listen to port 80, and then return the same request that was sent, but with the HTTPS protocol, which means that it will hit port 443. We can also see that we reference the request_uri variables. These variables are standard variables in NGINX that are automatically populated. We can define our own variables with the following line of code:
set $name ‘Maxwell’;
However, we want our NGINX instance to work on our server and localhost, so using the standard variables is the best choice here. Now that we have defined our rerouting rule, we can move on to the next server scope; we listen to port 443 with the following code:
#ingress/nginx.conf server {
listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/self.crt;ssl_certificate_key /etc/nginx/ssl/self.key; location / {
proxy_pass http://ingress:8001/;}Alongside the port definition, we also declare that we are using the ssl and http2 NGINX modules. This is not surprising as HTTPS is essentially SSL on top of HTTP/2. We then define where our server certificate is in the NGINX container. We will add these later in the docker-compose volume. We can also see that we pass our HTTPS request to the appropriate application via HTTP. If we try to change these proxies to the HTTPS protocol, we would get a bad gateway error. This is because the handshake between NGINX and our services would fail. It is not essential because we must remember that the ports that the frontend and backend applications expose are not available to anyone outside of localhost. On our local machine, we can access them, but this is because they are running on our local machine. If we were to deploy our application server, it would look like this:
Figure 17.3 - Traffic flow if deployed on a server
Our NGINX configuration is not optimal. There are settings that can be tweaked in terms of ciphers, caching, and managing timeouts. However, this is enough to get an HTTPS protocol working. If you get to the point that you need to optimize the caching and encryption methods of your NGINX configuration, it is suggested that you seek further education materials on DevOps and NGINX. Now that we have defined our NGINX configuration, we must define our certificates.
[figure outside: Figure 17.3]
Installing SSL
Section titled “Installing SSL”To define our own certificates, we must install the openssl package by following the steps using the following links:
- Linux: https://fedingo.com/how-to-install-openssl-in-ubuntu/
- Windows: https://linuxhint.com/install-openssl-windows/
- Mac: https://yasar-yy.medium.com/installing-openssl-library-on-macoscatalina-6777a2e238a6
This can be done with the following command:
openssl req -x509 -days 10 -nodes -newkey rsa:2048 \ -keyout ./ingress/self.key \ -out ./ingress/self.crtThis creates a key with x509, which is the International Telecommunication Union standard. We state that the certificate will expire in 10 days and that the key and certificate will have the name self. They can be called anything; however, for us, it makes sense to call the certificate self because it is a self-issued certificate. The command shown in the previous code snippet will push several prompts. It does not matter what you say to these prompts, as we will just be making localhost requests with them, meaning that they will never go anywhere outside of our local computer. We can now stash the key and certificate anywhere within the deployment directory if you can reference the key and certificate placed in the docker-compose.yml file. In our ingress build config file, our NGINX service now takes the following form:
version: "3.7"services: ingress: ... nginx: container_name: 'nginx' image: "nginx:latest" ports: - "80:80" - "443:443" links: - ingress volumes: - ./ingress/nginx.conf:/etc/nginx/nginx.conf - ./ingress/self.crt:/etc/nginx/ssl/self.crt - ./ingress/self.key:/etc/nginx/ssl/self.keyWhile where you get your key and certificate from may vary, it is important that you put the key and the certificate inside the etc/nginx/ssl/ directory inside the NGINX container.
We are now at the point where you can test our application to see if the local HTTPS is working. If you spin up your Docker Compose instance and then go to https://localhost in your browser, you should get a warning that it is not secure, and you will not be able to instantly connect to the frontend. This is reassuring because we are not a central authority, so our browser will not recognize our certificate. There is a multitude of browsers, and we would waste a lot of space in this book describing how to get past this for every browser. Considering browsers are free to download, we can get around the blocking of our application in Chrome by going to the flags URL, as seen here:
Chrome chrome://flags
Search flags Reset all
Experiments 127.0.6533.120
WARNING: EXPERIMENTAL FEATURES AHEAD! By enabling these features, you could lose browser data or compromise your security or privacy. Enabled features apply to all users of this browser. If you are an enterprise admin you should not be using these flags in production.
Interested in cool new Chrome features? Try our beta channel.
| Available | Unavailable |
|---|---|
| Allow invalid certificates for resources loaded from localhost. | |
| Allows requests to localhost over HTTPS even when an invalid certificate is presented. – Mac, Windows, Linux, ChromeOS, Android, Lacros | |
| #allow-insecure-localhost | |
| Enabled |
Figure 17.4 – Allowing our application certificate to pass in Chrome
Here, we can see that I have allowed invalid certificates from localhost. Now that our invalid certificate is enabled in our browser, we can access our application, as seen here:
[figure outside: Figure 17.4]
Not Secure https://localhost
Login
Password
Let’s Go
Figure 17.5 – Accessing our application through HTTPS
Here, we are using the HTTPS protocol; however, as we can see in the preceding screenshot, Chrome is complaining, stating that it is not secure. We can inspect the reason why by clicking on the Not Secure statement, giving the following view:
Not Secure https://localhost
localhost
Your connection to this site is not secure
You should not enter any sensitive information on this site (for example, passwords or credit cards) because it could be stolen by attackers. Learn more
Certificate is not valid
Cookies and site data
Site settings
[figure outside: Figure 17.5]
Here, we can see that our certificate is not valid. We expected the certificate not to be valid because we issued it, which makes it not officially recognized. However, our HTTPS connection is working, and we can see that the React app is served using HTTPS with the following screenshot of the network:
| Name | X | Headers | Preview | Response | Initiator | Timing |
|---|---|---|---|---|---|---|
| localhost | ▼ | General | ||||
| localhost | ▼ | Request URL: https://localhost/frontend/public/bundle.js | ||||
| bundle.css | ✔ | Request Method: GET | ||||
| bundle.js | ✔ | Status Code: 200 OK | ||||
| rust_interface_bg.wasm | ✔ | Remote Address: [::1]:443 |
This is interesting to see how HTTPS works; however, it is not useful with a self-signed certificate running on our localhost.
If we want to utilize HTTPS, we are going to have to apply it to our application on AWS. There are a couple of steps we need to carry out before we implement HTTPS on AWS. In the next section, we will assign a URL to our application.
Attaching a URL to our deployed application on AWS
Section titled “Attaching a URL to our deployed application on AWS”In the previous chapter, we managed to deploy our to-do application onto a server on AWS and access this application directly by putting the IP address of the server into our browser. When it comes to registering our URL, you will be exposed to multiple acronyms. To feel comfortable when navigating AWS routing, it makes sense to be familiar with URL acronyms by reading the following diagram, where TLD stands for Top-Level-Domain and SLD is Second-Level-Domain:
Figure 17.8 - Anatomy of a URL
[figure outside: Figure 17.8]
When we are associating a URL with our application, we are going to be configuring the Domain Name System (DNS). A DNS is a system that translates a user-friendly URL to an IP address. For a DNS system to work, we will need the following components:
-
Domain registrar: An organization, such as AWS, Google Cloud, Azure, GoDaddy, and so on, that will register a domain if it receives payment and the personal details of the person responsible for the domain. This organization will also handle reports of abuse if the URL is used in illegal activity.
-
DNS record: A registered URL can have multiple DNS records. A DNS record essentially defines a routing rule for the URL. For instance, a simple DNS record will forward the URL to an IP address of a server.
-
Zone file: A container for DNS records (in our case, the zone file will be managed by AWS). The DNS records and registrars are essential for our URL to work. Even though we can directly connect to IP addresses, there are a couple of middlemen if we want to connect to a URL, as laid out in the following diagram, where TLL stands for Time-To-Live, TLN DNS stands for Top-Level Name DNS, and SLD DNS stands for Second-Level Domain DNS:
Figure 17.9 – Steps required to connect a URL to an IP address
As we can see from the preceding diagram, if we want to connect to a server, we send the URL to the local DNS server. This server then makes three calls in sequential order from top to bottom. By the end of the three requests, the local DNS server will have the IP address related to the URL. We can see that the registrar is responsible for part of the mapping. This is where our DNS records are configured. If we remove our DNS records, then the URL is no longer available on the internet. We do not have to make the calls laid out in Figure 17.9 every time we enter a URL. Our browsers and the local DNS server will cache the URL to the IP address mapped to reduce the number of calls to the other three servers. There is a problem, however; when we have been building our production server, you might have realized that the IP address has changed every time we tear down and spin up a production server. There’s nothing wrong going on here; when we create an EC2 instance, we must take a server that is available. A cloud provider such as AWS cannot hold the server aside just for us unless we want to pay for it. In the next section, we will keep our IP consistent with Elastic IP addresses.
[figure outside: Figure 17.9]
Attaching an Elastic IP to our server
Section titled “Attaching an Elastic IP to our server”Elastic IP addresses are essentially fixed IP addresses that we keep. We can then attach these Elastic IP addresses to any one EC2 instance at one point in time as we see fit. This is very helpful when it comes to routing. We can set up the routing of a URL to an Elastic IP and then switch the allocation of the Elastic IP to the server that we need. This means that we can deploy a new application to another server, test it, and then switch our Elastic IP to the new deployment server without having to touch the routing for our URL. We will not be creating an Elastic IP every time we spin up a production server. Because of this, it is OK to point and click in the AWS console to create and attach the Elastic IP address. Before we do this, however, we need to deploy our production server with the previous NGINX config file that does not have HTTPS defined, and Docker Compose will not point to self-signed keys in the volume, as we are passing the HTTPS off to the load balancer we create in AWS.
Now that we have removed all references to our keys and port 443 routing in our Docker Compose system and NGINX conf files, reverting to the state of our system before implementing HTTPS locally, we are ready to deploy our build on our production server. Remember, we can do this using the deployment/run_build.sh script that we set up in the previous chapter. Once the server is built, we know that there is an EC2 instance live, but change the tag of the EC2 server in deployment.main.tf to to-do production server tag. We are now ready to allocate an Elastic IP address to our EC2 instance. To allocate Elastic IPs, we first need to navigate to the EC2 service by searching for EC2 in the search bar in the AWS dashboard at the top and clicking on the service, resulting in the following view:
Figure 17.10 – EC2 dashboard view
We can see that Elastic IPs can be accessed on the right of the Resources panel and on the left of the screen. Once we are in the Elastic IP address dashboard, we will have a list of Elastic IP addresses that you have. At the top right of the screen, there will be an orange button labeled Allocate Elastic IP address. If you click this button, you will get the following creation form:
[figure outside: Figure 17.10]
EC2 > Elastic IP addresses > Allocate Elastic IP address
Allocate Elastic IP address Info
Section titled “Allocate Elastic IP address Info”Elastic IP address settings Info
Section titled “Elastic IP address settings Info”Public IPv4 address pool Amazon’s pool of IPv4 addresses Public IPv4 address that you bring to your AWS account with BYOIP. (option disabled because no pools found) Learn more Customer-owned pool of IPv4 addresses created from your on-premises network for use with an Outpost. (option disabled because no customer owned pools found) Learn more
Network border group Info eu-west-2
Global static IP addresses AWS Global Accelerator can provide global static IP addresses that are announced worldwide using anycast from AWS edge locations. This can help improve the availability and latency for your user traffic by using the Amazon global network. Learn more Create accelerator
Tags - optional
Section titled “Tags - optional”A tag is a label that you assign to an AWS resource. Each tag consists of a key and an optional value. You can use tags to search and filter your resources or track your AWS costs.
No tags associated with the resource. Add new tag You can add up to 50 more tag
Cancel Allocate
Figure 17.11 – Allocating (creating) an Elastic IP address
[figure outside: Figure 17.11]
What we are doing here is grabbing an Elastic IP address from a pool of IP addresses for the area you are working on. There is a limit of five Elastic IP addresses per account. If you think this is not enough for you, you will need to get more creative with your networking infrastructure. You can also investigate creating sub-accounts for the main account. As with clean code, there are benefits to having clean accounts that only work on one project at a time. This will help you keep track of costs, and shutting down all infrastructure for a project will be clean, as you can be sure that everything for that project has been cleared by deleting the account.
Moving on to our allocation of the Elastic IP to our EC2 server, we can allocate it by highlighting the desired Elastic IP address in the Elastic IP dashboard and clicking on the Actions button at the top right of the dashboard, as seen here:
Figure 17.12 – Actions on our Elastic IP
[figure outside: Figure 17.12]
Under Actions, we must click on the Associate Elastic IP address option, giving us the following display:
EC2 > Elastic IP addresses > Associate Elastic IP address
Associate Elastic IP addressinfo Choose the instance or network interface to associate to this Elastic IP address (35.177.70.168)
Elastic IP address: 35.177.70.168
Resource type Choose the type of resource with which to associate the Elastic IP address. Instance Network interface
If you associate an Elastic IP address with an instance that already has an Elastic IP address associated, the previously associated Elastic IP address will be disassociated, but the address will still be allocated to your account. Learn more If no private IP address is specified, the Elastic IP address will be associated with the primary private IP address.
Instance Choose an instance i-0dd491961aac55183 (to-do build server) - running The private IP address with which to associate the Elastic IP address. Choose a private IP address
Reassociation Specify whether the Elastic IP address can be reassociated with a different resource if it already associated with a resource. Allow this Elastic IP address to be reassociated
Cancel Associate The Instance option will provide a drop-down menu of the EC2 instances that we have running. Luckily, we have the helpful to-do build server tag that we defined in Terraform. However, if we do not have a tag, we can still choose an instance from the drop-down menu. We can then click the Associate button. Once this is done, we can go to our Elastic IP address in our browser, and we should be able to access our to-do application, as seen here:
Figure 17.14 – Accessing our to-do application using a static IP
And here we have it—our application can be accessed with an Elastic IP! We can now spin up a new server if we want, test it, and redirect our Elastic IP to the new server if we are happy, providing seamless updates without our users knowing. However, getting users to type in the raw IP address is not desirable. In the next subsection, we will register a domain and connect it to our Elastic IP address.
Registering a domain name
Section titled “Registering a domain name”When it comes to registering a domain, it can all be handled in AWS with the Route 53 service. First, we navigate to Route 53, which is the service that handles routing and URL registration. On the left side of the Route 53 dashboard web page, we can click on the Registered domains section, as seen in the following screenshot:
[figure outside: Figure 17.14]
Route 53 Dashboard Hosted zones Health checks Profiles New IP-based routing CIDR collections Traffic flow Traffic policies Policy records Domains Registered domains Requests
Figure 17.15 – Registered domains view
If you click on the Register Domain button at the bottom of the screen, you will be led through a straightforward series of forms to register your domain. The forms ask you for the domain you want to register. It will then tell you whether the domain and other similar domains are available. Domains cost about $14 a year on average at the time of writing this book. Once you have selected your domain and clicked on the checkout, you will be taken through a series of personal information forms. These forms include a contact address and whether the domain is for personal use or for a company. It is recommended that you select the validation through DNS because this is automated. It is also recommended that you ensure that the WHOIS lookup is enabled for your privacy. Registering a domain means that people can do public lookups on your address against the domain. The WHOIS protection ensures that your details will not be visible and that they can contact you through a proxy managed by AWS. If you do anything illegal, however, authorities may be able to collaborate with AWS to access such details that are registered with the domain that is performing illegal activities, depending on the laws of where you live.
Once your domain is registered, you can go to the Hosted zones section in the main Route 53 dashboard. Here, we will see a list of hosted zones for each URL that you own. A hosted zone is essentially a collection of DNS records. If we click on a hosted zone for a URL, there will be two DNS records: NS and SOA (NS=name server; SOA=start of authority). These records should not be deleted, and if they are, somebody else who knows what they are could hijack your URL by implementing those records themselves. DNS records are essentially records on how to route traffic for a domain name. Each DNS record has the following attributes:
[figure outside: Figure 17.15]
- Domain/subdomain name: The name of the URL the record belongs to
- Record type: The type of record (A, AAAA, CNAME, or NS)
- Value: Target IP address
- Routing policy: How Route 53 responds to queries
- TTL: The amount of time the record is cached in the DNS resolvers in the client, so that we do not have to query the Route 53 servers too often, with the trade-off of reducing traffic to DNS servers versus time for updates to roll onto clients
The attributes just defined are self-explanatory, apart from the record type. There are advanced record types that we can build in Route 53. However, the following record types are needed for us to route our domain to our IP:
- A: The simplest record type. Type A merely routes traffic from the URL to an IPv4 IP address.
- AAAA: This routes traffic from the URL to an IPv6 address.
- CNAME: This maps a hostname to another hostname (target must be an A or AAAA record type).
- NS: The name server for the hosted zone (controls how the traffic is routed).
For us, we are going to create a DNS A record. We do this by accessing Hosted zones, which will look like the following:
Figure 17.16 – Hosted zones dashboard
By clicking on the URL that we have bought (in Figure 17.16, this is pubsub.me), we can create our DNS record by clicking on the Create record button in the following screenshot:
[figure outside: Figure 17.16]
Once we have clicked on this, we get the following layout:
Figure 17.18 – Creating a DNS record
[figure outside: Figure 17.18]
We can see that record type A is the default. We can also see that we can add a subdomain. This gives us some flexibility. For instance, if we wanted, the api.pubsub.me URL could point to a different IP address from pubsub.me. For now, we are going to just leave the subdomain empty. We are then going to put the Elastic IP address that we set up in the previous section in the Value section and click Create records. We are then going to create the exact same DNS record, but with the subdomain of www. Once this is done, we should have two A records. We can then check where our URL is mapping the traffic using the www.digwebinterface.com website. Here, we can enter URLs, and the website will tell us where the URLs are being mapped. We can see here that our URLs are both mapping to the correct Elastic IP:
Hostnames or IP addresses: pubsub.com www.pubsub.com
Type: Unspecified
Nameservers: Resolver: Default All Authoritative NIC Specify myself:
Options: Show command Colorize output Stats Request NS ID Trace Sort alphabetically Short No recursive Only first nameserver Compare output Save to file Show IP geolocation DNSSEC
Dig Fix Reset form
[email protected] (Default): pubsub.com. IN A 199.59.243.224
[email protected] (Default): www.pubsub.com. IN CNAME pubsub.com. IN A 199.59.243.224
Figure 17.19 - Checking a DNS record
With the mapping result confirmed, as seen in the preceding screenshot, we can visit our URL and expect to see the following:
[figure outside: Figure 17.19]
Figure 17.20 – Accessing our application through the registered URL
We can see that our URL is now working. However, the connection is not secure. In the next section, we will enforce an HTTPS protocol for our application and lock it down, as right now, even though we can access our application through the URL, there is nothing stopping us from accessing the IP of the server directly.
Enforcing HTTPS on our application on AWS
Section titled “Enforcing HTTPS on our application on AWS”Right now, our application kind of works, but it is a nightmare in terms of security. By the end of this section, we will not have the most secure application, as further reading of a networking and DevOps textbook is suggested to achieve gold-standard security. However, we will have configured security groups, locked down our EC2 instances so that they cannot be directly accessed by outsiders, and enforced encrypted traffic through a load balancer that will then direct traffic to our EC2 instances. The result of our efforts will be the following system:
Figure 17.21 – Not secure login form
[figure outside: Figure 17.20, Figure 17.21]
To achieve the system shown in Figure 17.21, we need to carry out the following steps:
- Get certificates approved for our URL and variations.
- Create multiple EC2 instances to distribute traffic and ensure that the service survives outages.
- Create a load balancer to handle incoming traffic.
- Create security groups.
- Update our Python build script to support multiple EC2 instances.
- Attach our URL to the load balancer using the Route 53 wizard.
In the previous section on attaching a URL to our application on AWS, we did a lot of pointing and clicking. As said in the previous chapter, pointing and clicking should be avoided if possible, as it is not repeatable, and we as humans forget what we did. Sadly, with URL approvals, pointing and clicking is the best option. In this section, only the first and sixth steps will require pointing and clicking. The rest will be achieved with Terraform. We are going to be making some big changes to our Terraform configuration, so it is advised that you run a terraform destroy command before altering it. Before we can do any of the coding, however, we are going to have to get our certificates for our URL.
Getting certificates for our URL
Section titled “Getting certificates for our URL”Because we brought our URL through Route 53, which is handled by AWS, and our servers are running in AWS, the certification and implementation of those certificates is a straightforward process. We need to navigate to Certificate Manager by typing certificate manager into the services search bar and clicking on it. Once there, we are displayed with a page that only has one orange button, labeled Request a certificate. Click on this, and we will be transported to the following page:
AWS Certificate Manager > Certificates > Request certificate
Request certificate
Section titled “Request certificate”Certificate type Info ACM certificates can be used to establish secure communications access across the internet or within an internal network. Choose the type of certificate for ACM to provide.
Request a public certificate Request a public SSL/TLS certificate from Amazon. By default, public certificates are trusted by browsers and operating systems.
Request a private certificate No private CAs available for issuance.
Requesting a private certificate requires the creation of a private certificate authority (CA). To create a private CA, visit AWS Private Certificate Authority
Cancel Next
[figure outside: Figure 17.21]
We are going to want our certificate to be public-facing; therefore, we are happy with the default selection, and we click Next. We are then presented with the following form:
AWS Certificate Manager > Certificates > Request certificate > Request public certificate
Request public certificate
Section titled “Request public certificate”Domain names
Section titled “Domain names”Provide one or more domain names for your certificate.
Fully qualified domain name Info
Section titled “Fully qualified domain name Info”pubsub.me
Add another name to this certificate
Section titled “Add another name to this certificate”You can add additional names to this certificate. For example, if you’re requesting a certificate for “www.example.com”, you might want to add the name “example.com” so that customers can reach your site by either name.
Validation method Info
Section titled “Validation method Info”Select a method for validating domain ownership.
- DNS validation - recommended Choose this option if you are authorized to modify the DNS configuration for the domains in your certificate request.
- Email validation Choose this option if you do not have permission or cannot obtain permission to modify the DNS configuration for the domains in your certificate request.
Key algorithm Info
Section titled “Key algorithm Info”Select an encryption algorithm. Some algorithms may not be supported by all AWS services.
- RSA 2048 RSA is the most widely used key type.
- ECDSA P 256 Equivalent in cryptographic strength to RSA 3072.
- ECDSA P 384 Equivalent in cryptographic strength to RSA 7680.
Tags Info
Section titled “Tags Info”No tags associated with the resource.
Add new tag
Section titled “Add new tag”You can add up to 50 tags.
Cancel Previous Request Here, we type in the URLs we want to associate with the certificate. In Figure 17.23, we have stated that we want a certificate for the URL pubsub.me. We will also want a wildcard certificate, so you must repeat this process for the *.pubsub.me URL. We can also see that DNS validation is already highlighted, and this is recommended as we have our servers on AWS, meaning we will have to take no more action to get the certificate issued. We can then click on the button labeled Request, and we will be redirected to a page with the list of certificates. I find that the new certificate request is not present nearly every time I do this. My guess is that there is a delay. Do not worry—merely refresh the page, and you will see the pending certificate request listed. Click on this listing, and you will be directed to a detailed view of this certificate request. In the middle of the screen on the right, you need to click the Create records in Route 53 button, as seen here:
Figure 17.24 – Creating records for DNS confirmation
Follow the prompts after clicking the button, and the CNAME record will be created. If you do not do this, then the pending status for the ticket will go on indefinitely because the cloud provider needs the route to issue the certificate, considering we selected DNS validation. The created records should look like the following screenshot:
Figure 17.25 – Creating the records options
[figure outside: Figure 17.23] [figure outside: Figure 17.24] [figure outside: Figure 17.25]
After a few minutes, the certificate should be issued. Once this is done, carry out the same steps for the prefix wildcard. After that, your certificate lists should look something like the following:
Figure 17.26 – Creating records for DNS confirmation
In the preceding screenshot, we can see that I have two certificates: one for if a user directly types in the URL with no prefix, and the wildcard that covers all prefixes. We are ready to use these certificates, but before we do this, we are going to have to carry out some other steps. Before we define rules around the traffic, we are going to have to build the infrastructure where the traffic is going. In the next subsection, we will prep our EC2 instances.
Prepping our EC2 instances
Section titled “Prepping our EC2 instances”We will be using a load balancer, and the traffic of that load balancer will be directed to our EC2 instance. Our load balancer can also distribute across multiple EC2 instances that are the same. This means that if one EC2 instance is down, we can still use the other EC2 instance. We can also scale our application. For our example, we will keep our EC2 instance count to one, as we still have our cache for the auth sessions housed on the EC2 instance. If we were to increase our EC2 instances without housing our cache on a separate EC2 instance, then we would get inconsistent reads from our user session cache. Setting up another EC2 instance, splitting up the docker-compose to house the Redis cache, and then passing the IP of that EC2 instance into the EC2 instances housing our to-do application would bloat this already lengthy chapter. However, we have covered all the concepts for it to be achieved, so we might as well prep the EC2 instance for that to be a possibility. We have to prep the EC2 instance for the load balancer with the following code:
resource "aws_instance" "production_server" { ami = "ami-05ea2888c91c97ca7" instance_type = "t2.medium" count = 1 key_name = "remotebuild" user_data = file("server_build.sh") security_groups = [[figure outside: Figure 17.26]
”${aws_security_group.webserver-security-group.name}”
]tags = {Name = "to-do prod ${count.index}"}}Here, we can see that we have added a count parameter and defined it as 1. If we increase the count, we will increase the number of EC2 instances built. We have also altered the tag. We can also see that we access the number of EC2 instances being created with index. The index starts at zero and increases by one every time a resource is made. Finally, we can also see that we have added a security_groups section. Right now, we have not made the security group that we are referencing, but we will in the section on security groups. We are referencing security groups to enforce rules of incoming traffic. It also must be noted that we are using security_groups because we are using the default VPC. If we are not using the default VPC, we must use security_group_ids. Now that we have the option for multiple instances, we must update the outputs at the bottom of the deployment/main.tf file with the following code:
output "ec2_global_ips" {value = ["${aws_instance.production_server.*.public_ip}"]}output “db_endpoint” {
value = "${aws_db_instance.main_db.*.endpoint}"}output “public_dns” {
value = ["${aws_instance.production_server.*.public_dns}"]}output “instance_id” {
value = ["${aws_instance.production_server.*.id}"]}Here, we can see that apart from the database endpoint, all the other outputs have been changed to lists. This is because they all reference the potential for multiple EC2 instances. Now that we have prepped our EC2 instances, we can route traffic to our instances with a load balancer.
Creating a load balancer for our traffic
Section titled “Creating a load balancer for our traffic”There is a range of different load balancers that we can pick from. We have already discussed NGINX, which is a popular load balancer. For this chapter, we are going to use the application load balancer to route the traffic to our EC2 instance and implement the HTTPS protocol. There are multiple features that load balancers can offer, and they protect against distributed denial-of-service (DDoS) attacks, whereby the attacker will try to overload the server with excessive requests. We will create our load balancer in the deployment/load_balancer.tf file. First, we collect the data that we need with the following code:
deployment/load_balancer.tf
Section titled “deployment/load_balancer.tf”data “aws_subnets” “subnets” {
filter { name = "vpc-id" values = [aws_default_vpc.default.id] }}data “aws_acm_certificate” “issued_certificate” {
domain = "pubsub.me" statuses = ["ISSUED"]}data “aws_acm_certificate” “raw_cert” {
domain = "*.pubsub.me" statuses = ["ISSUED"]}We can see that instead of a resource, we used the data declaration. This is where we make queries to AWS for specific types of data to be used in the rest of the Terraform script. We get the virtual private cloud (VPC) ID. In Terraform, we can define and build a VPC, but throughout this book, we have been using the default VPC. We can get the default VPC ID for our load balancer. We then get the data for the certificates that we have defined in the previous section with the preceding code. We now must define a target for our load balancer. This is done in the form of a target group where we can bunch a group of instances together for the load balancer to target with the following code:
deployment/load_balancer.tf
Section titled “deployment/load_balancer.tf”resource “aws_lb_target_group” “target-group” {
health_check { interval = 10 path = "/" protocol = "HTTP" timeout = 5 healthy_threshold = 5 unhealthy_threshold = 2 } name = "ToDoAppLbTg" port = 80 protocol = "HTTP" target_type = "instance" vpc_id = aws_default_vpc.default.id}Here, we can see that we define the parameters for a health check. These parameters are self-explanatory. The health check will alert a service targeting the health status of the target group. We would not want to route traffic to a target group that is down. We then define the protocol and port of the traffic, the type of resource in the target group, and the ID of the VPC. Now that our target group is defined, we can attach our EC2 instance to it with the following code:
resource "aws_lb_target_group_attachment" "ec2_attach" { count = length(aws_instance.production_server) target_group_arn = aws_lb_target_group.target-group.arn target_id = aws_instance.production_server[count.index].id}We can see that we get the IDs of the EC2 servers for the target ID. With this, our EC2 instances can be targeted by the load balancer. Now that we have a target, we can create our load balancer with the following code:
resource "aws_lb" "application-lb" { name = "ToDoApplicationLb" internal = false ip_address_type = "ipv4" load_balancer_type = "application" security_groups = [ "${aws_security_group.alb-security-group.id}" ] subnets = data.aws_subnets.subnets.ids tags = { name = "todo load balancer" }}We can see that the parameters in the load balancer definition are straightforward. However, you may have noticed the security group definition. We are referencing a security group even though we have not defined any security groups. If you do not know what a security group is, do not worry—we will cover and build all the security groups we need in the next section. Before we do that, however, we might as well define listening and routing rules for the load balancer. First, we can define the HTTP listener for port 80. If you remember the first section of this chapter, when getting HTTPS working on our localhost, what do you think we need to do for the HTTP traffic? You don’t have to know the specific Terraform code, but what is the general behavior that we want to facilitate? With this in mind, we can achieve that behavior with the following code:
deployment/load_balancer.tf
Section titled “deployment/load_balancer.tf”resource “aws_lb_listener” “http-listener” {
load_balancer_arn = aws_lb.application-lb.arn port = 80 protocol = "HTTP" default_action { type = "redirect" redirect { port = "443" protocol = "HTTPS" status_code = "HTTP_301" } }}That’s right! We receive HTTP traffic from port 80, and we then redirect it to port 443 with the HTTPS protocol. We can see that we have attached this listener using the Amazon Resource Name (ARN) of the load balancer that we created. We can now define our HTTPS listener with the following code:
deployment/load_balancer.tf
Section titled “deployment/load_balancer.tf”resource “aws_lb_listener” “https-listener” {
load_balancer_arn = aws_lb.application-lb.arn port = 443 protocol = "HTTPS" certificate_arn = data.aws_acm_certificate .issued_certificate.arn default_action { target_group_arn = aws_lb_target_group.target-group.arn type = "forward" }}Here, we can see that we accept HTTPS traffic and then forward HTTP traffic to our target group that we defined using the ARN of the target group. We can also see that we have attached one of the certificates to the listener. However, this does not cover all our URL combinations. Remember, we have another certificate that we want to attach. We can attach our second certificate with the following code:
deployment/load_balancer.tf
Section titled “deployment/load_balancer.tf”resource “aws_lb_listener_certificate” “extra_certificate” {
listener_arn = "${aws_lb_listener.https-listener.arn}" certificate_arn = "${data.aws_acm_certificate.raw_cert.arn}"}Configuring HTTPS with NGINX on AWS
This connection should be easy to understand. Here, we merely reference the ARN of the HTTPS listener and the ARN of the certificate that we want to attach. We have now defined everything we need for the resources of the load balancer. However, what of the traffic? We have defined the load balancer, EC2 instances, and the routing for HTTPS for the load balancer. But what is stopping someone from just directly connecting to the EC2 instance, bypassing the load balancer and HTTPS completely? This is where security groups come in. In the next section, we will lock down the traffic by creating security groups so that users cannot bypass our load balancer.
Creating security groups to lock down and secure traffic
Section titled “Creating security groups to lock down and secure traffic”Security groups are essentially firewalls. We can define the traffic to and from a resource that has a security group implemented. The rules of the traffic can be fine-grained. A single security group can have multiple rules defining the origin (even specific IP addresses if needed) and the protocol of the traffic. When it comes to our security groups, we are going to need two. One will accept HTTP and HTTPS traffic from all IPs anywhere in the world. This is going to be for our load balancer because we want our application to be available to everyone. The other security group will be implemented by our EC2 instances; this blocks all HTTP traffic apart from the first security group. We will also enable SSH inbound traffic because we need to SSH into the servers to deploy the applications, giving us the following traffic layout:
Figure 17.27 – Security groups for our deployment system
[figure outside: Figure 17.27]
This is where you must be careful with online tutorials. There is no shortage of YouTube videos and Medium articles that will get a load balancer up and running with some pointing and clicking. However, they leave the EC2 instances exposed and do not bother exploring security groups. Even with this section, we are going to leave the database exposed. I am doing this because it is a good question to be asked in the Questions section. However, I’m highlighting it here because you need to be warned that it is exposed. The way to lock down the database will be covered in the Answers section of this chapter. When it comes to our security groups, we can define them in the deployment/security_groups.tf file. We can start with the load balancer security group with the following code:
resource "aws_security_group" "alb-security-group" { name = "to-do-LB" description = "the security group for the application load balancer" ingress { ... } ingress { ... } egress { ... } tags = { name: "to-do-alb-sg" }}Here, we have two inbound rules under the ingress tag and one outbound rule under the egress tag. Our first inbound rule is to allow HTTP data from anywhere with the following code:
ingress { description = "http access" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"]}The cidr blocks of all zeros mean from anywhere. Our second inbound rule is HTTPS traffic from anywhere. How do you think this will be defined? It can be defined with the following code:
## deployment/security_groups.tfingress { description = "https access" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"]}Now for our outbound rule. We must allow all traffic and protocols out of the load balancer as they are coming from our resources. This can be achieved with the following code:
## deployment/security_groups.tfegress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"]}It must be noted that from_port and to_port are 0, meaning that we allow outgoing traffic from all ports. We also have set protocol to -1, meaning we are allowing all protocols as outgoing traffic. We have now defined the security group for the load balancer, so we can move on to defining our security group for the EC2 instances with the following code:
## deployment/security_groups.tfresource "aws_security_group" "webserver-security-group" { name = "to-do-App" description = "the security group for the web server"
ingress { ... } ingress { ... } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"]}{ tags = { name: "to-do-webserver-sg" }}The outbound rules are going to be the same as the load balancer because we want to return data to anywhere that is available to request it. When it comes to our HTTP inbound rules, we only want to accept traffic from the load balancer with the following code:
## deployment/security_groups.tfingress { description = "http access" from_port = 80 to_port = 80 protocol = "tcp" security_groups = [ "${aws_security_group.alb-security-group.id}" ]}Here, we can see that instead of defining the cidr blocks, we rely on the security group of the load balancer. Now that all the user traffic is defined, we only need to define the SSH traffic for deployment with the following code:
## deployment/security_groups.tfingress { description = "SSH access" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"]}Now for our outbound rule. We must allow all traffic and protocols out of the load balancer, as they are coming from our resources. This can be achieved with the following code:
## deployment/security_groups.tfegress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"]}It must be noted that from_port and to_port are 0, meaning that we allow outgoing traffic from all ports. We also have set protocol to -1, meaning we are allowing all protocols as outgoing traffic. We have now defined the security group for the load balancer. We can now move on to defining our security group for the EC2 instances with the following code:
## deployment/security_groups.tfresource "aws_security_group" "webserver-security-group" { name = "to-do-App" description = "the security group for the web server" ingress { ... } ingress { ... } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { name: "to-do-webserver-sg" }}The outbound rules are going to be the same as the load balancer because we want to return data to anywhere that is available to request it. When it comes to our HTTP inbound rules, we only want to accept traffic from the load balancer with the following code:
## deployment/security_groups.tfingress { description = "http access" from_port = 80 to_port = 80 protocol = "tcp" security_groups = ["${aws_security_group.alb-security-group.id}"]}Here, we can see that instead of defining the cidr blocks, we rely on the security group of the load balancer. Now that all the user traffic is defined, we only need to define the SSH traffic for deployment with the following code:
deployment/security_groups.tf
Section titled “deployment/security_groups.tf”ingress {
description = "SSH access" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"]}Here, we access SSH through port 22. This will enable us to SSH into our servers and deploy our applications. Nearly everything is done. We only need to attach our EC2 instances to our EC2 security group, which can be done with the following code:
deployment/security_groups.tf
Section titled “deployment/security_groups.tf”resource “aws_network_interface_sg_attachment”
"sg_attachment_webserver" { count = length(aws_instance.production_server) security_group_id = aws_security_group. webserver-security-group.id network_interface_id = aws_instance. production_server[count.index]. primary_network_interface_id }Our Terraform scripts are now complete and will be able to spin up multiple EC2 instances, a database, and a load balancer while locking down traffic. This is a good template for other projects if you want to get a basic web app with HTTPS and access to a database off the ground with restricted traffic.
Now that we have the option to support multiple EC2 instances, we are going to have to change our deployment script.
Updating our deployment script
Section titled “Updating our deployment script”As our output now returns a list of EC2 IP addresses, our deployment script must be able to handle multiple IP addresses, copy the Docker Compose files over to all the IP addresses, and run the application on all the EC2 instances. This is achieved with the following code:
deployment/run_deployment.sh
Section titled “deployment/run_deployment.sh” ... OUTPUT_FILE="output.json" IP_ADDRESS=$(jq --raw-output '.ec2_global_ips.value[0][0]' \ $OUTPUT_FILE) IP_ADDRESSES=("$IP_ADDRESS") echo "All IP Addresses: ${IP_ADDRESSES[@]}" ...for IP in "${IP_ADDRESSES[@]}"do echo “Processing IP: $IP” done
Here, we can see that we create a list of IP addresses and assign them to the IP_ADDRESSES variable. We then loop through our list of IP addresses, copying over the Docker Compose files and running the applications on these servers. In this loop for the deployment and running of the application, we substitute IP as this is the variable in the loop.
If our Terraform output gave us two IP addresses, we could construct our list with the following code:
IP_ADDRESS=OUTPUT_FILE) IP_ADDRESS_TWO=OUTPUT_FILE) IP_ADDRESSES=(“IP_ADDRESS_TWO”)
Now, all our code infrastructure is done! We can run this Bash script and deploy our build onto AWS. Everything is nearly done; all we must do is connect our URL to our load balancer in the next subsection.
Attaching our URL to the load balancer
Section titled “Attaching our URL to the load balancer”This is the home run. We are finally near the end. However, this is important if you want to use your Rust server. To connect our URL to the load balancer, we must navigate to the hosted zone for your URL. Once there, click on the Create record button. When in the Create record display, if you are not using the wizard, click on the Switch to wizard link at the top right of the Create record display to get the following wizard view:
Choose routing policy
Section titled “Choose routing policy”Info
The routing policy determines how Amazon Route 53 responds to queries.
Routing policy
Section titled “Routing policy”Switch to quick create
- Simple routing Use if you want all of your clients to receive the same response(s).
🔒53🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡🟡Here, we can see a range of fancy ways to route traffic. However, we are going to select Simple routing as we just need to pass traffic to the load balancer, which is doing the distribution of traffic between EC2 instances. Selecting Simple routing gives us the following form to fill in:
Figure 17.29 – Define simple record wizard view
[figure outside: Figure 17.29]
Here, we can see that I have selected Alias to Application and Classic Load Balancer to route traffic to. I have selected the location where the load balancer is. This has given me a dropdown where I can see my ToDoApplicationLb load balancer to select. When you click the Define simple record button, you are then navigated to a list of records that are to be created. We carry out the creation wizard process one more time to account for all prefixes with the wildcard, and then confirm our creation of records. With this, HTTPS now works with our application, as seen here:
Figure 17.30 – HTTPS working with our application on the internet
To check this, we can perform the following cURL command:
curl -X POST https://pubsub.me/api/v1/users/create \-H "Content-Type: application/json" \-d '{ "email": "[email protected]", "password": "password"}'With this, our chapter is complete. If you try to access one of our EC2 instances directly through an IP address, you will be blocked. Therefore, we cannot directly access our EC2 instances, but we can access them through HTTPS through our URL. If you give users any variation of your URL, even an HTTP link to the URL, your users will happily use your application with the HTTPS protocol.
[figure outside: Figure 17.30]
Summary
Section titled “Summary”For now, we have done all we need to do to deploy a robust and secure application on AWS with locked-down traffic and HTTPS enforced. We have covered a lot to get here, and the skill set that you have gained in this chapter can be applied to pretty much any other project you want to deploy on AWS if you can package it in Docker. You now understand the advantages of HTTPS and the steps needed to not only achieve the HTTPS protocol but also to map your URL to the IP address of a server or a load balancer. What’s more, we automated the attachment of certificates that we created using Certificate Manager to our load balancer in Terraform using the powerful data query resource that Terraform has to offer. Finally, this all came together when we managed to access our application using HTTPS and only HTTPS. Not only have we developed some practical skills that will become useful in many future projects, but we have also explored the nature of how HTTPS and DNS work, giving us a deeper understanding and appreciation of how the internet generally works when we type in a URL to the browser.
Questions
Section titled “Questions”- Once we remember that our system still has the database exposed to the rest of the world, how would we lock it down?
- Why should we use an Elastic IP in some cases?
- How could we automate the association of an existing Elastic IP to an EC2 instance?
- How do we utilize security groups to lock down traffic between a URL and EC2 instances?
- Let’s say that the traffic for our application greatly increased, and our two instances cannot handle the pressure. What could we do to enable our system to handle the increase?
- What is the basic premise of a DNS record?
- What is a URL-hosted zone?
Answers
Section titled “Answers”- We would create a security group for the database that only accepts traffic to and from the EC2 instance security group. If we were having to make a migration, we could SSH into an EC2 instance and use it as a proxy to connect to a database. You can also do this with database viewing software such as DataGrip. Sometimes, you can have an EC2 instance that is just there for a user to use as a proxy to access the database. This is known as a bastion server.
- When we destroy and create EC2 instances, the IP address of the EC2 instance will change. We can use an Elastic IP to ensure that the IP address remains consistent, which can be helpful for automation pipelines, as we can continue to point to that IP address. However, if we are using a load balancer, we do not need to use an Elastic IP address, as we will point our URL to the load balancer.
- We can automate the association of an Elastic IP to an EC2 instance using Terraform and its powerful data resource. This means we get the data of the existing Elastic IP with a data query, and then attach this IP to an EC2 instance that we are creating.
- Ensure that the security group for the EC2 instances in the target group that the load balancer is attached to can only accept HTTP traffic from the load balancer.
565
-
Considering that everything in our system is automated and piped into each other, all we must do is increase the count in our EC2 instance definition from 2 to 3 and add the third EC2 to the list in the deployment script. This will increase the number of EC2 instances handling the traffic from 2 to 3.
-
A DNS record is essentially a routing rule that tells us how to route traffic from the URL to a server IP, URL namespace, or AWS service.
-
A URL-hosted zone is a collection of DNS records for a URL.
Further reading
Section titled “Further reading”Fjordvald, M.B. and Nedelcu, C. (2018) Nginx HTTP Server: Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever before. 4th edn. Packt Publishing.
Sharma, R. (2015) NGINX High Performance. Packt Publishing.
Kholodkov, V. (2015) Nginx Essentials: Excel in Nginx quickly by learning to use its most essential features in real-life applications. Packt Publishing.
Dar, U. (2013) Nginx Module Extension. Packt Publishing.
Aivaliotis, D. (2016) Mastering NGINX. 2nd edn. Packt Publishing.
Fjordvald, M. (2013) Instant Nginx Starter. Packt Publishing.
DeJonghe, D. (2024) NGINX Cookbook: Advanced Recipes for High-Performance Load Balancing. 3rd edn. O’Reilly Media.
Get this book’s PDF copy, code bundle, and more
Section titled “Get this book’s PDF copy, code bundle, and more”Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
UNLOCK NOW
Note: Have your invoice handy. Purchases made directly from the Packt website don’t require an invoice.
[blank page]