Deploying Our Application on AWS
local graph
Chapter 16 — Deploying Our Application on AWS
Section titled “Chapter 16 — Deploying Our Application on AWS”16 Deploying Our Application on AWS
Section titled “16 Deploying Our Application on AWS”While we have had a lot of fun running our system locally, nobody else can access it. In this chapter, we cover how to deploy our application onto a server on AWS. We will automate the building of the server and provisioning of the database by using Terraform. My love for Rust is part of the reason why I keep updating the editions of this book. Another motivator is that while there are plenty of online tutorials, a book that brings you through the entire journey of building the application to deploying it gives you the ability to see the entire process. I also believe that taking time to learn how to provision infrastructure exactly how you want gives you a starting point for further learning and adds to your toolkit of problem-solving. For instance, when I was working on a financial loss modeling engine that was used by Nasdaq, we had to run models that had hundreds of terabytes of data to run large financial models. I built a system that used Terraform to spin up a large server that runs the model. As soon as the model was finished, the script evoked Terraform again to destroy the server. Being able to provision cloud infrastructure is another tool that can factor into your solutions when solving problems. This chapter will cover the following:
- Setting up our build environment with AWS
- Building a server build pipeline
- Packaging our system with Docker
- Distributing our system with Docker
- Deploying our system with Docker
By the end of this chapter, you will be able to configure NGINX to route traffic to different servers and serve frontend web apps. You will also be able to package your servers in distroless Docker images, making these images tiny and secure, as there is no terminal in a distroless image. You will also be able to automate the building and configuration of infrastructure such as servers and databases. Deploying Our Application on AWS
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.
Setting up our build environment
Section titled “Setting up our build environment”While we can run the server locally, our aim is to deploy our application on a server. To run our application on a server, we are going to have to build our application in a Docker image. To ensure that our Docker image build runs smoothly, we are going to use an online computing unit on AWS. Before we run our build process, we need to carry out the following steps:
- Setting up an AWS Secure Shell (SSH) key for Elastic Compute Cloud (EC2).
- Setting up the AWS client for our local computer.
- Writing a Terraform script that builds our build server.
- Writing a Python script that manages the build.
- Writing a Bash script that orchestrates the build on the server.
Once we have completed the steps, we will be able to run an automated pipeline that creates a build EC2 server on AWS and then builds our Rust application. First, let us get started by creating an SSH key for our server.
Setting up an AWS SSH key for an Amazon EC2 instance
Section titled “Setting up an AWS SSH key for an Amazon EC2 instance”If we want to run commands on a server, we are going to have to connect to the server using the SSH protocol over the Hypertext Transfer Protocol (HTTP). However, we cannot have anyone accessing our server as it will not be secure. To stop anyone from connecting to our server and running any commands they want, we will only allow users to connect to our server if they have an SSH key. To create our key, we need to log in to the AWS console and navigate to our EC2 dashboard, which can be accessed via the search box, as seen in the following screenshot:
Figure 16.1 - Navigating to the EC2 dashboard with the search box
Once we have navigated to the EC2 dashboard, we can navigate to Key Pairs under the Network & Security section of the panel on the left side of the view, as seen in the following screenshot:
▼ Network & Security
Security Groups
Elastic IPs
Placement Groups
Key Pairs
Network Interfaces
Figure 16.2 - Navigating to Key Pairs
UIs can change
It must be noted that AWS might not look like the screenshots in this chapter, as AWS keeps changing the UI. However, the fundamental concepts will be the same.
Once we have navigated to the Key Pairs section, there will be a list of key pairs that you already own. If you have built EC2 instances before, you might already see some listed. If you have never built an EC2 instance before, then you will not have anything listed. At the top right of the screen, you can create a key by clicking on the Create key pair button shown in the following screenshot:
Figure 16.3 - Button to allow the creation of a key pair
[figure outside: Figure 16.1] [figure outside: Figure 16.2] [figure outside: Figure 16.3]
Once we have clicked on this button, we will see the following form:
EC2 > Key pairs > Create key pair
Create key pair Info
Key pair A key pair, consisting of a private key and a public key, is a set of security credentials that you use to prove your identity when connecting to an instance.
Name remotebuild The name can include up to 255 ASCII characters. It can’t include leading or trailing spaces.
| Key pair type | Info |
|---|---|
| RSA | |
| ED25519 |
Private key file format .pem For use with OpenSSH .ppk For use with PuTTY
Tags - optional No tags associated with the resource.
Add new tag You can add up to 50 more tags.
Cancel Create key pair
Figure 16.4 – The Create key pair form
In the preceding screenshot, we can see that we have named our key remotebuild; we also state that our key has the .pem format and is of the RSA type. Once we click on the Create key pair button, we will download the key. We now must store our key. This can be done by storing it in our home directory in the .ssh directory. Inside the .ssh directory, we can create a keys directory with the following command:
mkdir "$HOME"/.ssh/keys/[figure outside: Figure 16.4]
The “$HOME” environment variable is always available in the Bash shell, and it denotes the home directory for the user. This means that other users who log in to the computer under a different username cannot access the SSH keys we downloaded if we store them in the directory that we have just created. We can now navigate to where our key has been downloaded and copy it to our keys directory with the following command:
cp ./remotebuild.pem "$HOME"/.ssh/keys/remotebuild.pemWe then must change the permissions for the key so that only the owner of the file can read the file with the 600 code for us to use the key for SSH purposes with the following command:
chmod 600 "$HOME"/.ssh/keys/remotebuild.pemWe now have an SSH key stored in our .ssh/keys directory, where we can access this key with the correct permissions in order to access the servers that we create. Now that we have this, we need programmatic access to our AWS services by setting up our AWS client.
Setting up our AWS account
Section titled “Setting up our AWS account”We will be using Terraform to automate our server build. To do this, Terraform will make calls to the AWS infrastructure. This means that we must have the AWS client installed on our local machine. Before we configure our client, we need to get some programmatic user keys. If we do not obtain programmatic access, our code will not be authorized to build infrastructure on our AWS account. The first step of obtaining the user keys is navigating to the IAM section via the search box, as seen in the following screenshot:
Figure 16.5 - Navigating to the IAM section
[figure outside: Figure 16.5]
Once we have navigated to the IAM section, we will get the following layout:
Figure 16.6 – View of the IAM section
We can see in the preceding screenshot that my user has multi-factor authentication (MFA), and I keep my access key rotated. If you are new to AWS, this checklist might not be satisfactory, and it is suggested that you follow the security recommendations that AWS gives you. We now must access the Users option on the left-hand side of the view and create a new user by clicking the Create user button at the top right of the screen, as seen in the following screenshot:
Figure 16.7 – Creating users
[figure outside: Figure 16.6] [figure outside: Figure 16.7]
We can then create a user. It does not matter what name we call the user, as seen in the following figure:
Figure 16.8 – First stage of creating a user
[figure outside: Figure 16.8]
We can see that we will have to create the programmatic access later. To create our user, we now move on to setting permissions for the user by clicking the Next button. Our permissions configuration will look like the following:
Figure 16.9 – Defining user permissions
We can see that we have given the user AdministratorAccess permissions, which will enable us to create and destroy servers and databases. We can not create the user, which will appear on the dashboard once the user has been created. We can now create an access key for our user by clicking Create access key on the user profile, as seen in the following screenshot:
Figure 16.10 – Defining user permissions
[figure outside: Figure 16.10, Figure 16.9]
We can then select the Command Line Interface (CLI) key, as seen in the following screenshot:
Figure 16.11 – Selecting the type of access key
We can see in the screenshot that AWS recommends CloudShell for our deployment approach, which, while technically secure, does have vulnerabilities. For instance, we are creating a long-lived access key. If that key were leaked to a hacker, they could perform actions on our system until we detected the leak and acted on it.
[figure outside: Figure 16.11]
DevOps is an entire field in itself, and security professionals spend their entire career ensuring that systems are safe. While this book will cover enough to launch a safe web application, it does not claim to be the best practices. Please seek further books and courses on security and DevOps if you want to progress your role in the deployment of applications.
Once the access key is created, you will be exposed to an access key and a secret access key. It is important to note these down in a secure location, such as a password manager, because you will never be able to see your secret access key again on the AWS site, and we will need it when configuring our AWS client on our local computer.
Now that we have the user keys handy, we can configure our AWS client with the following command:
aws configureThe AWS client will then prompt you to enter the user keys as and when they are required. Once this is done, your AWS client is configured, and we can use AWS features programmatically on our local computer. Now, we are ready to start creating servers using Terraform in the next section.
Setting up our Terraform build
Section titled “Setting up our Terraform build”When it comes to building infrastructure on AWS, we can simply point and click in the EC2 dashboard. However, this is not desirable. If you are anything like me, when I point to and click a series of configuration settings, I forget what I have done unless I document it, and let’s be honest, documenting what you’ve clicked is not something you are going to look forward to. Even if you are a better person than me and you do document it, when you change the configuration, there is a chance that you will not go back to update the documentation of that change. Pointing and clicking is also time-consuming. If we wanted to create some infrastructure and then destroy it a week later, and then recreate it a month after that, we would be reluctant to touch it if we had to point and click, and our server bills would be higher. This is where infrastructure as code (IaC) comes in. We will have to do some pointing and clicking, as we did in the previous sections. We cannot do any programmatic access without pointing and clicking to set up programmatic access.
For our IaC, we are going to have a separate build directory in the root of our system. In the build directory, we can define our infrastructure for the build server in the build/main.tf file. It must be noted that the .tf extension is the standard extension for Terraform files. First, we define which version of Terraform is being used with the following code:
builds/main.tf
Section titled “builds/main.tf”terraform { required_version = ">= 1.9.4" required_providers { aws = { source = "hashicorp/aws" version = ">= 5.62.0" }}Now that we have defined the Terraform version, we can declare that we are using the AWS module. The Terraform registry has modules for a range of platforms, including Google Cloud and Microsoft Azure. Anyone can build modules and abstract infrastructure to be downloaded in the Terraform registry. Our AWS module usage declaration takes the following form:
provider "aws" { region = "eu-west-2"}You might want to pick a different region if another region suits you. A list of the available regions on AWS for EC2 can be found via the following link: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html.
I’m merely using “eu-west-2” for demonstration purposes. We can now build our EC2 instance with the following code:
resource "aws_instance" "build_server" { ami = "ami-05ea2888c91c97ca7" instance_type = "t2.medium" key_name = "remotebuild" user_data = file("server_build.sh") tags = { Name = "to-do build server" }}The resource statement in the Terraform script declares that we are defining a resource to be built, and aws_instance states that we are using the EC2 instance template in the AWS module. A list of the available AWS Terraform modules and their documentation can be found via the following link: https://registry.terraform.io/providers/hashicorp/aws/latest/docs.
We are calling it build_server. We can refer to build_server anywhere else in the Terraform script, and Terraform will work out the order in which resources need to be built to make sure all references are accounted for. We can see that we have referenced the remotebuild key that we defined in the previous section. We can create multiple EC2 instances that can be accessed by one key if we want. We also declare the name so that when we look at our EC2 instances, we know what the server is for. We must also note that user_data is the Bash script that will be run on the new EC2 server once it has been built. The ami section is a reference to the type of operating system and version being used. Do not directly copy my Amazon Machine Image (AMI) ID in the example unless you are using the same region, as AMI IDs can vary depending on the region. If you want to find out the AMI ID, go to your EC2 dashboard and click on Launch an instance, which will result in the following window:
EC2 > Instances > Launch an instance
Section titled “EC2 > Instances > Launch an instance”Launch an instance Info
Section titled “Launch an instance Info”Amazon EC2 allows you to create virtual machines, or instances, that run on the AWS Cloud. Quickly get started by following the simple steps below.
Name and tags Info
Section titled “Name and tags Info”Name e.g. My Web Server Add additional tags
Application and OS Images (Amazon Machine Image) Info
Section titled “Application and OS Images (Amazon Machine Image) Info”An AMI is a template that contains the software configuration (operating system, application server, and applications) required to launch your instance. Search or Browse for AMIs if you don’t see what you are looking for below
Search our full catalog including 1000s of application and OS images
Quick Start
Section titled “Quick Start”Amazon Linux aws macOS Mac Ubuntu ubuntu Windows Microsoft Red Hat Red Hat SUSE Linux SUSE Browse more AMIs Including AMIs from AWS, Marketplace and the Community
Amazon Machine Image (AMI)
Section titled “Amazon Machine Image (AMI)”Amazon Linux 2023 AMI ami-05ea2888c91c97ca7 (64-bit (x86), uefi-preferred) / ami-02b0ba219a3ee9d7f (64-bit (Arm), uefi) Free tier eligible Virtualization: hvm ENA enabled: true Root device type: ebs
Figure 16.12 – Launching an instance
Here, we can see that we are picking Amazon Linux. You must select this; otherwise, your build scripts will not work. If we zoom in, we can see that the AMI ID is visible, as seen here:
[figure outside: Figure 16.12]
Amazon Machine Image (AMI)
Section titled “Amazon Machine Image (AMI)”Amazon Linux 2023 AMI
Section titled “Amazon Linux 2023 AMI”ami-05ea2888c91c97ca7 (64-bit (x86), uefi-preferred) / ami-02b0ba219a3ee9d7f (64-bit (Arm), uefi)
Virtualization: hvm ENA enabled: true Root device type: ebs
Figure 16.13 – Accessing AMI ID for the server
This will be the AMI ID for the Amazon Linux operating system in the region that you want to launch. You can also see that nothing is stopping you from using other operating systems in other Terraform projects. If you have built EC2 instances in the past, you will know that the IP address is random unless we attach an Elastic IP to the EC2 instance. We will have to produce an output of the IP address of our EC2 instance so that we can connect to it. Our output is defined with the following code:
## builds/main.tfoutput "ec2_global_ips" { value = ["${aws_instance.build_server.*.public_ip}"]}Here, we can see that we reference our build server using aws_instance.build_server. At this point, our Terraform build is nearly done. We must remember that we need to build the build_server.sh script that is going to be run on the EC2 instance once the EC2 instance has been built. In our /build/server_build.sh file, we can install the basic requirements needed for our server with the following code:
#!/bin/bash## builds/server_build.tfsudo yum update -ysudo yum install git -ysudo yum install cmake -ysudo yum install tree -ysudo yum install vim -ysudo yum install tmux -ysudo yum install nodejs -ysudo yum install -y openssl-develsudo yum install make automake gcc gcc-c++ kernel-devel -y[figure outside: Figure 16.13]
With the preceding packages, we will be able to navigate around the server looking at file trees with tree; we will also be able to perform git operations, open files, and edit them using vim, and have multiple panels open through one terminal if we need to with tmux. The other packages enable us to compile our Rust code. We must also note that we have appended each install with a -y tag. This is to tell the computer to bypass input prompts and put in default answers. This means that we can run this script in the background without any problems. We now must install the PostgreSQL drivers with the following code in the same server_build script:
sudo amazon-linux-extras install postgresql10 vim epel -ysudo yum install -y postgresql-server postgresql-devel -yWe nearly have everything that we need. In the next section, we will be using Docker to build and package our applications. This can be done with the following code in the same server_build script:
sudo amazon-linux-extras install dockersudo service docker startsudo usermod -a -G docker ec2-userHere, we can see that we install Docker, start the Docker service, and then register our user with the Docker service so that we do not have to use sudo with every Docker command. As we have installed Docker, we might as well install docker-compose for completeness. This can be done at the end of our script with the following code in the same server_build script:
sudo curl -L "https://github.com/docker/compose/releases \/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)"-o /usr/local/bin/docker-compose \sudo chmod +x /usr/local/bin/docker-composeThe curl command downloads docker-compose. We then make the docker-compose executable with the chmod command. The build script is almost finished. However, running all the commands that we have defined in the build script will take a while. There is a chance that we can SSH into our server before the build script has finished. Therefore, we should write a FINISHED string to a file to inform other processes that the server has all the packages that have been installed. We can write our flag with the following code:
echo "FINISHED" > home/ec2-user/output.txtWe have now built out the infrastructure that is going to build our applications for deployment. In the next section, we are going to build a script to orchestrate the building of our application on the server.
Building a server build pipeline
Section titled “Building a server build pipeline”Now that we can build our server programmatically, we can include it in our build pipeline. Our build pipeline can be defined by a simple Bash script that is housed next to our Terraform file. Because the Bash script is in the same directory as the Terraform file, we start off by ensuring that the working directory is in the same directory with the following code:
#!/usr/bin/env bash## builds/run_build.sh
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATHWe then build the server using Terraform with the following code in the same run_build script:
## builds/run_build.shterraform initterraform apply -auto-approveterraform output -json > ./output.json
IP_ADDRESS=$(jq --raw-output '.ec2_global_ips.value[0][0]' \output.json)echo $IP_ADDRESSecho "waiting for server to be built"sleep 5echo "attempting to enter server"The two Terraform commands that we carry out in the preceding snippet are init and apply. init sets up the Terraform state to record what is going on and downloads the modules that we need, which, in this case, are from AWS. The apply command runs the Terraform build, which will build our EC2 server. Once our EC2 instance is built, we can get the output of Terraform and write it to a JSON file, and then load the data from that JSON file, assigning the IP address of the created server to the IP_ADDRESS variable. We can also see that we sleep our script for 5 seconds to ensure that the server has started the creation process, and the IP can be routed to.
We are now ready to upload our files to the server that has recently been built. We must ensure that we do not upload node_modules by deleting them with the following code:
## builds/run_build.shrm -rf ../ingress/frontend/node_modulesWe then upload our nanoservices with the following code:
## builds/run_build.shscp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \-r ../nanoservices
ec2-user@$IP_ADDRESS:/home/ec2-user/nanoservices
We can see that we point to the SSH key to access the server. We can also see that we set StrictHostKeyChecking=no. This ensures that we are not prompted to ask whether we are okay connecting to this host because it will not be known to our computer. We then upload the ingress, glue, docker-compose.yml, and .env files with the following code:
scp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \-r ../ingress \ec2-user@$IP_ADDRESS:/home/ec2-user/ingressscp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \../docker-compose.yml \ec2-user@$IP_ADDRESS:/home/ec2-user/
scp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \../.env \ec2-user@$IP_ADDRESS:/home/ec2-user/Finally, we SSH into our created server, and perform a loop until the output.txt file is present, telling us that the build script has run and everything we need is installed onto the server with the following code:
ssh -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no -t \ec2-user@$IP_ADDRESS << EOF until [ -f ./output.txt ] do echo "waiting for file" sleep 3 done echo "File found" sudo curl https://sh.rustup.rs -sSf | bash -s -- -ysource ~/.cargo/envexport $(cat .env | xargs)cd ingresscd frontendnpm installnpm run buildcd ..cargo build --releaseEOF terraform destroy -auto-approve
We can also see that we built the frontend and backend Rust server. We can then run this Bash script to build the server, copy the files over to the server, and build our application.
Warning!
Terraform can sometimes be temperamental; if it fails, you may need to run it again. Sometimes I’ve had to perform a Terraform run up to three times before it fully works. Every action is stored by Terraform, so do not worry; running the Bash script again will not result in duplicate servers.
It usually makes sense to show the printouts in this book; however, the printout here is long and would probably take up multiple pages. Also, the printouts are obvious. Terraform openly states what is being built, the copying and building are also verbose, and the destruction of the server with Terraform is also printed out. It will be very clear what is going on when you run this build pipeline.
You might also notice that there is a range of Terraform files that have been created. These files keep track of the state of our resources that have been built on the AWS platform. If you delete these state files, you have no way of knowing what is built, and duplicates will be spun up. It will also prevent Terraform from cleaning up. The place where I used to work used Terraform to build massive data models for calculating the risk of financial loss over geographical locations. The data being processed can go over the range of terabytes per chunk. We use Terraform to spin up a range of powerful computers, run data through it (which can take days), and then shut it down when it is finished. Multiple people need to monitor this process, so our Terraform state is housed in a Simple Storage Service (S3) bucket so that anyone on the project can shut it down if needed. An example of this configuration takes the following form in the state.tf file:
terraform { backend "s3" { bucket = "some_bucket" key = "some/ptaht/terraform.tfstate" region = "eu-west-1" }}It must be noted that your account needs to have access to the bucket defined. Now that our build pipeline is fully working, we can move on to wrapping our software in Docker so that we can package the software in Docker and deploy it.
Packaging our system with Docker
Section titled “Packaging our system with Docker”Throughout the book, we have been running our servers directly. However, packaging our servers with Docker enables us to distribute our servers to Docker orchestration systems such as docker-compose, or Kubernetes. We can also version control our server releases and isolate dependencies. For instance, if a server requires a particular library that is incompatible with another server, Docker enables us to run both servers on the same machine as the dependencies are isolated in the image and running container. For our system, we want to have the option of deploying our system as either a single monolith or a cluster of servers talking to each other, known as microservices. To achieve this flexibility, we must carry out the following steps:
- Building the base Docker image for all servers
- Defining the build config for our monolith
- Defining the build config for our microservices
Once we have carried out these steps, we will have a system that can be deployed onto a server as either a monolith or collection of microservices.
Building the base Docker image for all servers
Section titled “Building the base Docker image for all servers”For our system, we are going to build one Docker image for all our servers. We also want our images to be tiny, so we will be doing a two-stage build, resulting in a distroless build. This means the bare minimum is kept running the Rust binary. This approach is also more secure. The distroless image is so barebones that if a hacker manages to gain access to the container running our server binary, there is no terminal, so the hacker cannot perform any terminal commands. Because we are stripping down our image to the bare minimum, we must offer two Docker builds. One for AArch chips (ARM-based CPUs such as Apple Silicon; often labeled arm64/aarch64), and another for x86 chips (Intel/AMD 64-bit; often labeled amd64), because we will be copying over specific libraries. These Docker files are housed in the root of our system with the following names:
- Dockerfile.aarch
- Dockerfile.x86
We will start with the aarch Dockerfile. We start off by stating that we are using the Rust base image, and then we install the requisites needed for encryption and interacting with a Postgres database with the following code:
## Dockerfile.aarchFROM rust as build
RUN apt-get update && apt-get install -y libpq-devRUN apt-get install libssl-dev -yWe are also going to be building the frontend and embedding the built frontend into our ingress binary. Therefore, we must install nodejs and wasm-pack with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”RUN curl -fsSL
https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs
Install wasm-pack
Section titled “Install wasm-pack”RUN cargo install wasm-pack
Now, with everything installed, we copy all our code into the working directory, which we call app, with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”WORKDIR /app COPY . .
We can now build our frontend and our Rust servers with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”RUN cd ingress/frontend &&
npm install &&
npm run wasm &&
npm run build
RUN cargo build —release -p ingress
RUN cargo build —release -p actix_server
—features=auth-http —no-default-features
RUN cargo build —release -p auth_actix_server
With our servers built, we want to reduce the size of our binaries as much as possible. We do this by stripping our binaries of all the debug symbols. This means that debugging our crashes will be harder. Do not worry, we have extensively tested our code, and we are shooting off logs to a database. We strip our binaries with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”RUN strip /app/target/release/ingress RUN strip /app/target/release/actix_server RUN strip /app/target/release/auth_actix_server
We are now ready to define the second step of our two-step build by declaring the distroless image with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”FROM gcr.io/distroless/cc-debian12 Now, we could just copy over our service binaries. However, our binaries would not work if we did that. This is because the server binaries rely on some dynamically linked libraries to function. We can see what dynamic libraries are needed for a binary by typing in the ldd command and then a path to a binary. It will list all the dynamic libraries that the binary is linked to. I manually did this to the ingress binary, and as a result, we must copy over the following libraries from the previous step with the following code:
Dockerfile.aarch
Section titled “Dockerfile.aarch”COPY —chown=1001:1001 —from=build
/lib/ld-linux-aarch64.so.1
/lib/ld-linux-aarch64.so.1
COPY —chown=1001:1001 —from=build
/lib/aarch64-linux-gnu/libssl.so.3
/lib/aarch64-linux-gnu/libssl.so.3
COPY —chown=1001:1001 —from=build
/lib/aarch64-linux-gnu/libcrypto.so.3
/lib/aarch64-linux-gnu/libcrypto.so.3
COPY —chown=1001:1001 —from=build
/lib/aarch64-linux-gnu/libgcc_s.so.1
/lib/aarch64-linux-gnu/libgcc_s.so.1
COPY —chown=1001:1001 —from=build
/lib/aarch64-linux-gnu/libm.so.6
/lib/aarch64-linux-gnu/libm.so.6
COPY —chown=1001:1001 —from=build
/lib/aarch64-linux-gnu/libc.so.6
/lib/aarch64-linux-gnu/libc.so.6
These are all needed and supply the following functionality:
- ld-linux-aarch64.so.1: This is the dynamic linker/loader for 64-bit ARM architecture (AArch64). It’s responsible for loading shared libraries needed by a program and preparing the program to run by linking the libraries into the process’s memory space.
- libssl.so.3: Part of the OpenSSL toolkit, libcrypto provides general-purpose cryptographic routines such as encryption, decryption, hashing, and more.
- libgcc_s.so.1: Part of the GNU Compiler Collection (GCC) runtime libraries, this provides low-level support for exception handling and other essential functionalities for programs compiled with GCC.
- libm.so.6: This is the math library, providing basic mathematical functions such as sin(), cos(), sqrt(), and so on. It is a standard part of the C library.
- libc.so.6: This is the GNU C Library (glibc), which provides the core functionalities of the C standard library, including system calls, memory management, and basic input/output operations. We could statically compile our Rust servers. This is where all the dependencies are compiled into the binary. While this sounds good, we must remember that we already have three binaries in our image, and we could add more. If we duplicate these libraries and compile them into every library, the size of our image would grow a lot. Instead, we just have one libc library and have multiple binaries point to it. However, this approach is also not a magic bullet. When dynamically linking, you miss out on compiler optimizations of how that library interacts with the rest of your code.
If you really want to see size reduction in action, I have had plenty of fun compiling Rust with no standard library and pointing to libc. This means you must do all your memory allocation with unsafe code pointing to libc functions, but your binaries end up being tiny.
Now that we have copied over our libraries, we can copy over our Rust server binaries with the following code:
## Dockerfile.aarchCOPY --from=build \/app/target/release/ingress \/usr/local/bin/ingressCOPY --from=build \/app/target/release/actix_server \/usr/local/bin/actix_serverCOPY --from=build \/app/target/release/auth_actix_server \/usr/local/bin/auth_actix_serverFinally, we expose all the ports that relate to the different servers, and then run our ingress server with the following code:
## Dockerfile.aarchEXPOSE 8001EXPOSE 8081EXPOSE 8080
CMD ["ingress"]Here is the really cool part. We can overwrite the CMD in docker-compose. This means that our image can either run as a single small server as part of a microservices system, or the entire system as a monolith, by just changing the command that we pass through to the container that is created from this image.
For our Dockerfile.x86 file, everything is the same apart from the libraries are slightly different. We copy over the following libraries:
## Dockerfile.x86COPY --chown=1001:1001 --from=build \/lib64/ld-linux-x86-64.so.2 \/lib64/ld-linux-x86-64.so.2
COPY —chown=1001:1001 —from=build
/lib/x86_64-linux-gnu/libssl.so.3
/lib/x86_64-linux-gnu/libssl.so.3
COPY —chown=1001:1001 —from=build
/lib/x86_64-linux-gnu/libcrypto.so.3
/lib/x86_64-linux-gnu/libcrypto.so.3
COPY —chown=1001:1001 —from=build
/lib/x86_64-linux-gnu/libgcc_s.so.1
/lib/x86_64-linux-gnu/libgcc_s.so.1
COPY —chown=1001:1001 —from=build
/lib/x86_64-linux-gnu/libm.so.6
/lib/x86_64-linux-gnu/libm.so.6
COPY —chown=1001:1001 —from=build
/lib/x86_64-linux-gnu/libc.so.6
/lib/x86_64-linux-gnu/libc.so.6
Our images are ready to be built. However, there is one slight adjustment to our servers. We must ensure that all our servers are listening to the address 0.0.0.0:
Before we run any builds, we must add a .dockerignore file in the root of our system to prevent us from needlessly copying over excessive files such as node_modules. This .dockerignore file has the following content:
ingress/frontend/node_modules/ builds/ target/
Now, depending on the chip architecture of your computer, you build the Docker image for your servers by running one of the following commands in the root of your system:
# for aarch chipsdocker build . -f Dockerfile.aarch -t compute-unit
# for x86 chipsdocker build . -f Dockerfile.x86 -t compute-unitHere, you will get a long printout of the build, and when the build is done, you will have a stored Docker image called compute-unit. This single image is going to be used for all our servers. We now have everything we need to build our monolith.
Defining the build config for our monolith
For our current system, all our databases are defined in the docker-compose file in the root of the system. We can stitch other docker-compose files together to build a working network. So, for instance, we can pass our main root docker-compose file into the docker-compose command and include another docker-compose file if this one works with the root docker-compose file. To see how this works in action, we will build the system defined in Figure 16.14:
Figure 16.14 - Our monolith system overview
We can see in Figure 16.14 that we are using NGINX as a router. NGINX is highly optimized for routing traffic, serving static assets, and load balancing. So, when a request comes into the network, it comes in via NGINX and then gets routed to the right server. We can also use NGINX to encrypt traffic between the client and our system. We will be doing this in the next chapter. With NGINX, we also get to decouple the routing logic from the servers that we build. We will see the power of this when we build our microservices system.
[figure outside: Figure 16.14]
For our monolith build, we must add the following files:
- ingress/build-config.yml
- ingress/nginx.conf
For our build-config.yml file, we have the following:
## ingress/build-config.ymlversion: "3.7"
services:
ingress: image: compute-unit environment: - 'TO_DO_DB_URL=postgres://username:password@postgres/to_do' - 'AUTH_DB_URL=postgres://username:password@postgres/to_do' - 'AUTH_API_URL=http://127.0.0.1:8081' - 'TO_DO_API_URL=http://127.0.0.1:8080' - 'JWT_SECRET=secret' - 'CACHE_API_URL=redis://cache:6379' - 'ELASTICSEARCH_URL=http://elasticsearch:9200/logs/_doc' ports: - "8001:8001"
depends_on: postgres: condition: service_started nginx: container_name: 'nginx' image: "nginx:latest" ports: - "80:80" links: - ingress volumes: - ./ingress/nginx.conf:/etc/nginx/nginx.confThere are a couple of things that we must note here. For the URLs that we define, we can see that we have swapped from localhost to the name of the service definition in docker-compose. This is Docker Compose routing. If you make a network request inside the network, and the URL is the name of a service, Docker Compose will route the request to that service. We can also see that our ingress server depends on the Postgres database. This is because we run our migrations when we start the ingress server. Therefore, our ingress server will only start once the Postgres database has started. Finally, we have our NGINX service. The NGINX service listens to port 80, which is the outside port. When you make a request to the server from a browser, the port that is publicly available outside of the server is port 80. Port 80 is the default, so when we make a request in our browser to this system, we will not have to define the port anymore. Just typing in localhost into the browser will result in us making a request to the NGINX router. Because everything goes through the NGINX router, we could even get rid of our ports definition on the ingress server, making the ingress server completely inaccessible outside of the network, meaning that we must go through the NGINX router. However, it is not essential; as we already covered, external requests from other computers can only access port 80.
We can also see that we point to our own NGINX configuration. The route to all files in our build configs are relative to the root of our system, and we must run our commands to run the system from the root of our system. Our conf file takes the following form:
## ingress/nginx.confevents { worker_connections 512;}http { server { listen 80; location / { proxy_pass http://ingress:8001/; } }}This is a very simple config. Basically, our NGINX service listens to port 80 and routes all traffic to our ingress server. We can run the monolith system with the following command:
docker compose -f docker-compose.yml -f ingress/build-config.yml upHere, we are stitching together our main databases and our build config for our monolith server. Once everything is running, we can test our monolith system with the following Bash script, run anywhere, just to test the network:
#!/usr/bin/env bash
curl -X POST http://0.0.0.0/api/v1/users/create \-H "Content-Type: application/json" \-d '{ "email": "[email protected]", "password": "password"}'curl -u [email protected]:password -X GET
http://0.0.0.0/api/v1/auth/login
We can see that there is no port anymore. We are hitting the NGINX service and being routed to the ingress server. If we type localhost in our browser, we will get our rendered React application.
So, our monolith system is working. We can now build our microservices system.
Defining the build config for our microservices
Section titled “Defining the build config for our microservices”For our microservices system, we have the network flow defined in Figure 16.15:
Figure 16.15 – Our microservices system overview
We have slightly more complex NGINX routing, and we are no longer running our ingress binary; therefore, we get our NGINX to serve our React app directly instead of routing frontend requests to another service. NGINX is optimized for this, so we could even see an improvement in the performance of serving React assets.
[figure outside: Figure 16.15]
To build and run our microservices system, we must add the following files:
- nanoservices/to_do/build-config.yml
- nanoservices/auth/build-config.yml
- ingress/frontend/build-config.yml
- ingress/frontend/Dockerfile
- ingress/frontend/nginx.conf
- ingress/frontend/.dockerignore
For our to_do build config, we have the following:
## nanoservices/to_do/build-config.ymlversion: "3.7"
services:
to_do: image: compute-unit environment: - 'TO_DO_DB_URL=postgres://username:password@postgres/to_do' - 'AUTH_DB_URL=postgres://username:password@postgres/to_do' - 'AUTH_API_URL=http://auth:8081' - 'TO_DO_API_URL=http://to_do:8080' - 'JWT_SECRET=secret' - 'CACHE_API_URL=redis://cache:6379' - 'ELASTICSEARCH_URL=http://elasticsearch:9200/logs/_doc' ports: - "8080:8080" command: ["actix_server"]
depends_on: postgres: condition: service_startedHere, we can see that we pass in the binary name of the to_do server that we want to run in order to run it. We also wait for the Postgres database to start. Looking at the config, I’m sure you can do the auth build config yourself, which takes the following form:
## nanoservices/auth/build-config.ymlversion: "3.7"
services:
auth:image: compute-unit environment:
- ‘TO_DO_DB_URL=postgres://username:password@postgres/to_do’
- ‘AUTH_DB_URL=postgres://username:password@postgres/to_do’
- ‘AUTH_API_URL=http://auth:8081’
- ‘TO_DO_API_URL=http://to_do:8080’
- ‘JWT_SECRET=secret’
- ‘CACHE_API_URL=redis://cache:6379’
- ‘ELASTICSEARCH_URL=http://elasticsearch:9200/logs/_doc’ ports:
- “8081:8081” command: [“auth_actix_server”]
depends_on: postgres: condition: service_started
And for our frontend build config, we have the following:
version: "3.7"services:
nginx: build: ./ingress/frontend/ ports: - "80:80" links: - auth - to_doHere, we can see that we point to the Dockerfile for the frontend, so we should build it. First, we ensure that we have Rust, Node, and wasm-pack for our build with the following code:
# ingress/frontend/DockerfileFROM rust:latest AS buildRUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -RUN apt-get install -y nodejsRUN cargo install wasm-packWe then copy over the frontend code and build it with the following code:
## ingress/frontend/DockerfileWORKDIR /appCOPY . .RUN npm installRUN npm run wasmRUN npm run buildNow that our frontend is built, we want to get rid of the Node modules and target from the Rust build for the WASM module, so we copy the public folder over to the NXINX image with the NGINX conf file using the following code:
## ingress/frontend/DockerfileFROM nginx:alpineCOPY --from=build /app/public /usr/share/nginx/htmlCOPY nginx.conf /etc/nginx/nginx.confFinally, we expose our port and run our NGINX server with the following code:
## ingress/frontend/DockerfileEXPOSE 80CMD ["nginx", "-g", "daemon off;"]Our Docker Compose system is ready to run. The only thing we have is our NGINX configuration, which defines the following routes:
## ingress/frontend/nginx.confhttp { server { listen 80; location /api/v1/auth/ { proxy_pass http://auth:8081/api/v1/auth/; } location /api/v1/users/ { proxy_pass http://auth:8081/api/v1/users/; } location /api/v1/ { proxy_pass http://to_do:8080/api/v1/; } location / { root /usr/share/nginx/html; include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; }Here, we can see that the logic is the same as how we coded our ingress server. We forwarded backend endpoints to the backend servers, and then anything else is forwarded to the folder containing our React app. We also include the MIME types; otherwise, the browser will not render the assets returned, and if the request is not requesting a specific file, the index HTML file is served.
We can run our microservices cluster with the following command:
docker compose \ -f docker-compose.yml \ -f nanoservices/auth/build-config.yml \ -f nanoservices/to_do/build-config.yml \ -f ingress/frontend/build-config.yml \ upOur system works! However, while uploading all this code to a server and performing builds will technically work, it is not the most efficient. In the next section, we will upload our Docker images to a repository so they can be pulled from anywhere that has access without having to pull the code.
Distributing our system with Docker
Section titled “Distributing our system with Docker”If we want maximum flexibility on how we deploy our systems, we will want to put our Docker images in a registry. Registries are like GitHub, but for Docker images. You can make them private or public. You can deploy multiple versions and tag your images, kind of like Git branches. Orchestration systems such as Docker Compose or Kubernetes can pull these images into their system and run them. Skilled DevOps engineers can connect an entire pipeline from Git to their Kubernetes clusters. For instance, when a pull request gets merged into main, GitHub Actions gets triggered and builds a Docker image, which is then pushed to Docker Hub. The Kubernetes system has hooks listening to changes and will then pull the latest update automatically. You can also add filters on these hooks based on tags. This is beyond the scope of this book; however, to give a solid example, when Caroline and I built our Rust Kubernetes cluster, we had a development cluster and a live cluster. When new code was pushed to the development branch on GitHub, GitHub actions built new Docker images with development tags. Only the development cluster pulled the update. We did a new release by merging the development branch with main, triggering a build of Docker images that had the live tag. The production cluster then pulled these images automatically.
Before we can push our images to Docker Hub, we will have to create a Docker Hub repo. Registering our image on Docker Hub is straightforward. After logging in, we click on the Create repository button in the top-right corner, as shown in the following screenshot: dockerhub Explore Repositories Organizations Search Docker Hub
maxwellflitton Search by repository name All Content Create repository
Figure 16.16 – Creating a new repository on Docker Hub
Once we have clicked on this, we define the repository with the following configuration:
Repositories / Create
Create repository
Namespace maxwellflitton Repository Name* compute-unit
Short description
A short description to identify your repository. If the repository is public, this description is used to index your content on Docker Hub and in search engines, and is visible to users in search results.
Visibility
Public Appears in Docker Hub search results Private Only visible to you
Cancel Create
Figure 16.17 – Defining a new Docker repository
Now that we have our repositories defined, we can update our run_build Bash script with logging into Docker, building the Docker images, and pushing these built Docker images to Docker Hub with the following updated code:
USERNAME=$1PASSWORD=$2ssh -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no -t \ec2-user@$IP_ADDRESS << EOF until [ -f ./output.txt ] do echo "waiting for file" sleep 3 done[figure outside: Figure 16.16] [figure outside: Figure 16.17]
echo "File found"sudo yum install docker -ysudo usermod -a -G docker ec2-usersudo systemctl start docker.servicesudo docker login -u $USERNAME -p $PASSWORDsudo docker build . -f Dockerfile.x86 -t compute-unitsudo docker tag compute-unit $USERNAME/compute-unit:latestsudo docker push $USERNAME/compute-unit:latestcd ingress/frontend && sudo docker build . -t front-unitsudo docker tag front-unit $USERNAME/front-unit:latestsudo docker push $USERNAME/front-unit:latestcd ../../nanoservices/user-session-cache/cache-modulesudo docker build . -t redis-cachesudo docker tag redis-cache $USERNAME/redis-cache:latestsudo docker push $USERNAME/redis-cache:latestHere, we can see that we pass the username and password for Docker into the script, and we use these to log in to Docker and push the images that we have built. We also note that we have created a redis-cache repository and we are also building and pushing the redis-cache image. However, before we run this build script, there is a chance that the EC2 instance could run out of memory. To ensure that this does not happen, we can attach more memory to the EC2 build instance with the following code:
resource "aws_instance" "build_server" { ami = "ami-05ea2888c91c97ca7" instance_type = "t2.medium" key_name = "remotebuild" user_data = file("server_build.sh") tags = { Name = "to-do build server" } # root disk root_block_device { volume_size = "150" volume_type = "gp2" delete_on_termination = true }}Once we have run our build script again, we can see in our Docker Hub dashboard that the image has been shown, as in Figure 16.18:
Tags
DOCKER SCOUT INACTIVE
Activate
This repository contains 1 tag(s).
| Tag | OS | Type | Vulnerabilities | Pulled | Pushed |
|---|---|---|---|---|---|
| latest | Image | Security unknown | 10 minutes ago | 11 minutes ago |
See all
Figure 16.18 – View of pushed Docker repository
Our images are ready, and we can now move on to pulling these images for our deployed server.
Deploying our system with Docker
Section titled “Deploying our system with Docker”When it comes to deploying our system, we must create a server and a database, upload the docker-compose file to the new server, and pass the parameters of the created database into the Docker Com-pose when starting our system. To achieve this, we must carry out the following steps:
- Write a Terraform script for our server and database.
- Write a Docker Compose system for our server.
- Write a deployment script for our system.
Before we write anything, however, we must have the following file structure in the root of our system:
└─ deployment ├── docker-compose.yml ├── main.tf ├── nginx.conf ├── run_deployment.sh └─ server_build.sh
The server_build.sh script should be copied from the deployment directory, as it is just setting up the server. To be honest, this file structure could be in its own repository, as we are not pointing to any builds. Instead, we will be pulling images from Docker Hub.
To get this deployment going, we can start by writing the Terraform script.
[figure outside: Figure 16.18]
Writing a Terraform script for our server and database
Section titled “Writing a Terraform script for our server and database”For our Terraform script, we start with the following boilerplate code:
## deployment/main.tfterraform { required_version = ">= 1.9.4" required_providers { aws = { source = "hashicorp/aws" version = ">= 5.62.0" } } } provider "aws" { region = "eu-west-2" }We then allow the option to pass in some variables for the database username and password with the following code:
## deployment/main.tfvariable "db_password" { description = "The password for the database" default = "password"}variable "db_username" { description = "The username for the database" default = "username"}We can see that these variables have a default and a description. These variables could go into another Terraform file if we wanted to, as Terraform will scan the directory and subdirectories for Terraform files and stitch them together. However, our system is still basic, so we do not need to traverse variables into other files.
We then move on to our server, which takes the following form:
## deployment/main.tfresource "aws_instance" "production_server" { ami = "ami-05ea2888c91c97ca7" instance_type = "t2.medium" key_name = "remotebuild" user_data = file("server_build.sh") tags = {Name = "to-do production server"}Now, we could run our Postgres database on the production server as a Docker image. However, this is fickle. If the server goes down, we could lose all our data. Also, managed database services come with extra perks. For instance, cloud providers offer backups and snapshots of managed database services. Managed databases are more expensive than a small EC2 instance, but if you are managing data that needs to be maintained, then managed database services become essential. We can create our managed Postgres database with the following code:
resource "aws_db_instance" "main_db" { instance_class = "db.t3.micro" allocated_storage = 5 engine = "postgres" username = var.db_username password = var.db_password db_name = "to_do" publicly_accessible = true skip_final_snapshot = true parameter_group_name = aws_db_parameter_group.custom_pg.name tags = { Name = "to-do production database" }}Here, we can see that we have passed our variables into the definition of the database. We also pass in a parameter group that we have not defined yet. Parameter groups can be used to configure the parameters of things such as a database. For instance, if we were to SSH into a Postgres database, we would see several binaries talking to each other and config files. We could manually edit these config files ourselves and force a restart of the server, but Terraform allows us to configure parameters in these files with the following code:
resource "aws_db_parameter_group" "custom_pg" { name = "custom-pg" family = "postgres16" description = "allows unencrypted connections" parameter { name = "rds.force_ssl" value = "0" }}Here, we are switching off the enforced encryption. This is because our SQLX connections are not encrypted. If we do not update this parameter, the database connections from our to_do server will be blocked.
Once the database and server are built, we define the outputs with the following code:
## deployment/main.tfoutput "ec2_global_ips" { value = [aws_instance.production_server.public_ip]}output "db_endpoint" { value = "${aws_db_instance.main_db.*.endpoint}"}Our Terraform script is now complete, and we can now move on to building our Docker Compose system.
Writing a Docker Compose system for our server
Section titled “Writing a Docker Compose system for our server”For our docker-compose file, we have the following definitions for our server and NGINX:
## deployment/docker-compose.ymlversion: "3.7"services: ingress: image: maxwellflitton/compute-unit environment: - 'TO_DO_DB_URL=${DATABASE_URL}' - 'AUTH_DB_URL=${DATABASE_URL}' - 'JWT_SECRET=secret' - 'CACHE_API_URL=redis://cache:6379' - 'ELASTICSEARCH_URL=http://elasticsearch:9200/logs/_doc' ports: - "8001:8001" nginx: container_name: 'nginx' image: "nginx:latest" ports: - "80:80" links: - ingress volumes: - ./nginx.conf:/etc/nginx/nginx.confHere, we can see that we pass in our password and username parameters for the database. We can also see that we reference the nginx.conf file that we will upload to the server. If we were going to deploy our microservices system, we would have to pull the NGINX image with our frontend.
For Elasticsearch and the cache, we have the same code that we have been building throughout the chapter, which is the following:
## deployment/docker-compose.ymlcache: container_name: 'to-do-redis' image: 'maxwellflitton/redis-cache' restart: always ports: - '6379:6379'elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.13.4 container_name: elasticsearchenvironment: - discovery.type=single-node - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m"ulimits: memlock: soft: -1 hard: -1 ports: - "9200:9200"Finally, for our NGINX conf file, we have the following configuration:
## deployment/nginx.conf## deployment/nginx.confevents { worker_connections 512;}http { server { listen 80; location / { proxy_pass http://ingress:8001/; } }}Here, we can see that we are merely passing the traffic to our monolith server. Now that everything is defined for our system, we just need to build our deployment script.
Writing a deployment script for our system
Section titled “Writing a deployment script for our system”For our deployment system, there are a few changes, but essentially, the approach is like our build script. First, we have some boilerplate code to ensure that the deployment process is running in the same directory as the script and that we have all the arguments that we need for the deploy script with the following code:
#!/usr/bin/env bash## deployment/run_deployment.sh
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATH
USERNAME=$1PASSWORD=$2DB_USERNAME=$3DB_PASSWORD=$4We then apply the Terraform build pass in our variables with the following code:
## deployment/run_deployment.shterraform init
terraform apply \-var="db_username=$DB_USERNAME" \-var="db_password=$DB_PASSWORD" \-auto-approve
terraform output -json > ./output.jsonWe then get the IP address of the server and the address of our database with the following code:
## deployment/run_deployment.shOUTPUT_FILE="output.json"
IP_ADDRESS=$(jq --raw-output '.ec2_global_ips.value[0]' \$OUTPUT_FILE)echo $IP_ADDRESSDB_ENDPOINT=$(jq -r '.db_endpoint.value[0]' $OUTPUT_FILE)With the database endpoint, we define our Postgres URL with the following code:
DB_PORT=5432DB_NAME="to_do"POSTGRES_URL="postgresql://${DB_USERNAME}:${DB_PASSWORD}" \"@${DB_ENDPOINT}/${DB_NAME}"echo "PostgreSQL URL: $POSTGRES_URL"We now have all the infrastructure built and the information we need. With this information, we upload the Compose file and NGINX conf file with the following code:
scp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \./docker-compose.yml \ec2-user@$IP_ADDRESS:/home/ec2-user/scp -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no \./nginx.conf \ec2-user@$IP_ADDRESS:/home/ec2-user/Finally, we SSH into our server, install Docker, log in to Docker Hub, and run our system with our database URL passed into the Docker Compose system with the following code:
ssh -i "~/.ssh/keys/remotebuild.pem" \-o StrictHostKeyChecking=no -t \ec2-user@$IP_ADDRESS << EOF until [ -f ./output.txt ] do echo "waiting for file" sleep 3 done echo "File found" sudo yum install docker -y sudo usermod -a -G docker ec2-user sudo systemctl start docker.service sudo docker login -u $USERNAME -p $PASSWORD export DATABASE_URL=$POSTGRES_URL sudo DATABASE_URL=$POSTGRES_URL docker-compose up -dEOFIf we run our script, our system will be deployed, and we can access our application on our server IP address, as seen in Figure 16.19:
Figure 16.19 – View of our application on our AWS server
While our server works, we can see in Figure 16.19 that our connection is not secure. Our server is also not secure against all types of traffic. In the next chapter, we will lock down our server and enable HTTPS encryption for our traffic.
Summary
Section titled “Summary”In this chapter, we built the infrastructure and scripting to fully automate the build and deployment of our servers to Docker Hub. We then built out our database and server for deployment. We also built tiny distroless images and could support multiple different servers that can be run just via the type of command passed into the image when creating a container. These skill sets are not just restricted to deploying a web server. At a fundamental level, you understand the linking of libraries and how to package Rust software to run efficiently. I have used my Docker knowledge to run Rust code that directly interacts with GPUs, as Docker enables us to run our Rust code with libraries and drivers installed for a specific purpose without having to alter the machine in general. With volumes, there is nothing stopping you from building a tiny binary that listens to Unix sockets via a volume to run in the background of your computer.
[figure outside: Figure 16.19]
As for our web app, it is very unsecure. In the next chapter, we will improve our Terraform scripts to lock down traffic to the server and database, to ensure that the traffic can only go through an ingress and not directly hit the server or database. We will also cover encryption with NGINX to facilitate HTTPS traffic between the client and NGINX.
Questions
Section titled “Questions”-
At a high level, what are the steps of building and distributing our servers via Docker?
-
At a high level, how do we deploy our app so it can be accessed by other people?
-
Why is our current deployment not secure?
-
Distroless results in tiny images because it is stripped down to the bare minimum. If we were to just compile a Rust binary and copy it over to the distroless build without doing anything else, it would not be able to run the Rust server. Why is this, and how can we solve it?
-
How do you get the IP address of the created server to perform operations on the server?
Answers
Section titled “Answers”-
We create an EC2 server using Terraform, and then copy all our code onto that server. We then build our images, log in to Docker Hub, and push the built images with a tag to Docker Hub so anyone with access to that Docker Hub repo can pull from it.
-
We create an EC2 server and a Postgres-managed database with the username and password for the database passed in. We then copy over a stripped-down version of Docker Compose that does not reference any builds, but the Docker Hub image repo instead. We log in to Docker Hub, pull the images, pass the database parameters into the image, and then run Docker Compose in the background. Once Docker Compose is running, we can access the app by visiting the IP address of the server in our browser.
-
Our current deployment does not have HTTPS, meaning that the traffic between the client and server is not encrypted. Our server and database also have no traffic restrictions, meaning that anyone from anywhere can make direct network requests to our server and database. This needs to be locked down, and we will cover this in the next chapter.
-
The Rust server will not be able to run because the dynamic libraries for things such as encryption, accessing ports, and accessing a runtime on the CPU are missing. We can solve this problem by performing the 1dd command against the binary and copying over the libraries that the binary needs to run.
-
You define the outputs, such as the IP address of the server. We can then run the terraform output command and write that to a JSON file. We can then use jq to read the values from the JSON output file and use these variables, such as the IP address, in other operations. Deploying Our Application on AWS
Learn more on Discord
Section titled “Learn more on Discord”To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow this QR code: https://packt.link/EaKXL