Running a “Copy Cat” Server in AWS

“Stop copying me!!” is a phrase that I hear a lot from the back of the car when my 3 kids are back there. The age old tried and tested way to really annoy somebody is to repeatedly repeat back everything they say. Children learn how effective this is from an early age. It’s especially powerful when the child that is being copied is already having a tantrum about something else!

In continuing on with the theme from my recent blog posts about getting things up and running on the cloud, lets get a CopyCatServer up on AWS in a few simple steps.

WARNING: This is a simple tutorial to show the ease of getting a simple Java process to run on AWS and to connect to it. Security controls such as Network Access Control Lists, Security Groups etc. are left very open. On a proper production or even test system, access should be properly controlled and limited using IAM users/groups, Subnets, NACLs, Route Tables, Security Groups etc.

First of all we need an AWS account. An account can be created at https://aws.amazon.com and it offers percentage usage of some services for free for about a year (be careful and check though before using any services!).
When signing up, you will have to go through a few steps of getting a confirmation code sent to your phone etc. but the process doesn’t take too long. When last I did this for a personal account, it took only a few minutes.

Once you have your AWS account set up and are signed into the AWS Console, you will see something like this:

EC2 may not be in “recently visited services”. If not, we can search for it and click into it and you should see something like this:

Click on “Launch instance” and you’ll see something like this.

This is a list of Amazon Machine Images (AMI). An AMI is analogous to a Docker image and is a specification for a virtual machine – i.e. the EC2 instance (Elastic Compute instance) – from which instances can be created and started. The AMIs that are eligable for free tier are marked as such. Lets select the second one down (which is marked as free tier) – Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type – ami-0fa94ecf2fef3420b. After selecting this you should see a screen to choose and “Instance Type”.

An instance type is a specification of the computing resources that will be associated with the EC2 instance that we spin up e.g. RAM, CPUs EBS (Elastic Block Storage – similar to hard disk) etc. Lets choose the one that is selected in the above image that is eligable for the fee tier. Click “Next: Configure Instance Details” and you should see a screen similar to this:

This screen allows us to configure more details such as which VPC (Virtual Private Cloud), Subnet etc. that the EC2 instance will be associated with. We’ll just go with defaults here. A very high level overview is that a VPC is a virtual private network that you own within AWS. A subnet is a section of the network inside this VPC. A VPC is associated with a region e.g. eu-west-1 for Ireland. Inside a region, there are availability zones and inside an availability zone there is a data-centre with the physical hardware on which services (e.g. like our EC2 instance) are running. So our EC2 instance will be running in a data-centre which will be in a subnet which will be in an availability zone (subnets can’t span availability zones) which will be in a region. Ideally, we would spin up multiple replicas of the same EC2 instance in different availability zones and have our applications replicated across them for availability and fault tolerance. However, as this is just a quick demo, we will spin up one EC2 instance. This is done by clicking “Review and Launch” which brings us to a screen similar to this:

Clicking launch brings us to:

This allows us to create a key pair and download a .pem file which we can use later to ssh into the EC2 instance.

We can give the key pair a name and download the pem file. Then click “Launch Instances” and you should see a screen similar to this:

At the bottom of the page, we can click “View Instances”. After a short while (minute or two), if we click this we should see the EC2 instance running:

If we click on “Connect”, we get instructions on how to use the .pem file we downloaded earlier to ssh to the EC2 instance.

I have pasted these instructions below for convenience:

To access your instance:
Open an SSH client. (find out how to connect using PuTTY)
Locate your private key file (tom-demo.pem). The wizard automatically detects the key you used to launch the instance.
Your key must not be publicly viewable for SSH to work. Use this command if needed:
chmod 400 tom-demo.pem
Connect to your instance using its Public DNS:
ec2-99-79-70-139.ca-central-1.compute.amazonaws.com
Example:
ssh -i “tom-demo.pem” ec2-user@ec2-99-79-70-139.ca-central-1.compute.amazonaws.com
Please note that in most cases the username above will be correct, however please ensure that you read your AMI usage instructions to ensure that the AMI owner has not changed the default AMI username.

After ssh’ing into the EC2 instance, we will see something like this in our terminal:

https://aws.amazon.com/amazon-linux-ami/2018.03-release-notes/
4 package(s) needed for security, out of 10 available
Run “sudo yum update” to apply all updates.
[ec2-user@ip-172-31-15-122 ~]$

Run

sudo yum update

Running the CopyCatServer on EC2

To compile and run some java code on our EC2 instance, we need JDK 11. We can use Amazon Coretto JDK which we can download onto the instance (while ssh’d in) as follows:

wget https://corretto.aws/downloads/latest/amazon-corretto-11-x64-linux-jdk.rpm

Once the download is complete, run the following to install the JDK:
sudo yum install amazon-corretto-11-x64-linux-jdk.rpm

After installation, we can confirm that we have the JDK installed by running:
java -version

This should show something like:
openjdk version "11.0.6" 2020-01-14 LTS OpenJDK Runtime Environment Corretto-11.0.6.10.1 (build 11.0.6+10-LTS) OpenJDK 64-Bit Server VM Corretto-11.0.6.10.1 (build 11.0.6+10-LTS, mixed mode)

Now we need some code to run. We can open the VIM text editor and create a java file by running
vim CopyCatServer.java

If you are not used to VIM, go into insert mode by pressing “i”.

Then we need to add the following to the file:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class CopyCatServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket sc = new ServerSocket(8080);) {
            while (true) {
                try (Socket socket = sc.accept();
                        InputStream is = socket.getInputStream();
                        OutputStream os = socket.getOutputStream()) {

                    is.transferTo(os);
                } catch (Exception e) {
                    throw e;
                }
            }
        } catch (Exception e) {
            throw e;
        }
    }
}

If using iterm2 (https://www.iterm2.com/), this can be simply copied and pasted in. Once it’s entered, leave insert mode by pressing esc and save the file and close vim by typing :wq

Now we can compile our code running:
javac CopyCatServer.java

And we can get our CopyCatServer running by running:
java CopyCatServer

Once it is running, open another terminal tab/window from your local machine and let’s telnet to our java server.
If you don’t have telnet installed, it can be installed on mac with homebrew.
brew install telnet

telnet can also be installed as easily on linux and windows systems. A quick internet search will reveal multiple quick tutorials on how to get it set up.

With telnet, we can now telnet to our CopyCatServer which is running on our EC2 instance using the public IP address (this will vary for your instance but it is shown earlier where to get this) by running:

telnet 99.79.70.139 8080

Unfortunately, you will find that this will just hang and timeout eventually.
Trying 99.79.70.139...

Allowing Access to the CopyCatServer

The reason that telnet just hangs is because, no traffic is allowed to access port 8080 on our EC2 instance. There is a security group that gets associated with it that allows traffic for ssh but not for port 8080 which is the port that our CopyCatServer is running on.
We can fix this by going back the the EC2 management screen we had before and scrolling down to the details to Security Group:

Click on “launch-wizard-1”. This brings us the the security group associated with our EC2 instance. We can look at the inbound rules from here:

Click Edit to add a new rule and we can add a rule to allow traffic to port 8080 as follows:

Click save and you will see that the rule is added:

No we can go back to the terminal and telnet from our local machine again:

➜ ~ telnet 99.79.70.139 8080

Trying 99.79.70.139...

Connected to ec2-99-79-70-139.ca-central-1.compute.amazonaws.com. Escape character is '^]'.

This time we will see that telnet connects. Now anything we type into the telnet session will be simply copied back to us from our CopyCatServer just like an annoying person that copies everything we say!

hello
hello
how are you
how are you

Before we finish, be sure to shut down your EC2 instance. We can go back to the EC2 dashboard:

Then go into “Running instanes”:

Then the instance can be stopped as follows:

One Reply to “Running a “Copy Cat” Server in AWS”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s