Setting Up a Golang Web Server on EC2 with a Free SSL Cert and No Load Balancer

EC2 Instance Setup

Create a new EC2 instance. This example was done on amazon-linux but I think it would probably be better to use ubuntu next time.

If you do use ubuntu note that you’ll need to use apt instead of yum and will likely have to open ports 80 and 443 on the instance.

All instance types will need to have ports 443 and 80 opened via your linked security group.

Creating the backend domain

I have purchased a domain name from namecheap (~$1.50/yr). To get it this cheap it needs to be 6-10 numbers only with the xyz extension.

To manage dns via route53 we create a new hosted zone and then add the following nameservers on namecheap’s dns manager:

ns-596.awsdns-10.net.
ns-348.awsdns-43.com.
ns-1820.awsdns-35.co.uk.
ns-1429.awsdns-50.org.

We then create a subdomain called mysite1.1234567892.xyz and point it to the EC2 instance’s public IP in route53 19.100.124.17 (as an A record). This will be used for the certificate as well.

Nginx

Installation, note that if using the ubuntu you will need to use apt instead of yum.

sudo yum update
sudo yum install nginx

Verify that its running with systemctl status nginx

Create the configuration:

  • Create a new directory called sites-enabled: sudo mkdir /etc/nginx/sites-enabled
  • Edit the http block using sudo nano /etc/nginx/nginx.conf and add this line: include /etc/nginx/sites-enabled/*;
  • Create the configuration file: sudo nano /etc/nginx/sites-enabled/1234567892

Add the following values to the config file:

server {
  listen 80;
  server_name mysite1.1234567892.xyz;
  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  Host       $http_host;
    proxy_pass        http://127.0.0.1:4800;
  }
}

server {
  listen 80;
  server_name mysite2.1234567892.xyz;
  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  Host       $http_host;
    proxy_pass        http://127.0.0.1:4500;
  }
}

Restart nginx with sudo systemctl restart nginx. Check status again with: systemctl status nginx. To test, go to http://19.100.124.17/ and be sure that it showing as http, not https. Accessing the full http url http://mysite1.1234567892.xyz/ will give a bad gateway error until the application is deployed.

Setup Golang

Here are the steps to install GoLang on an Amazon Linux EC2 instance:

  1. First, connect to your EC2 instance using SSH.
  2. Once connected, update the package lists for upgrades and new package installations: sudo yum update -y
  3. Download the GoLang package. You can find the URL of the latest version on the official website: wget https://golang.org/dl/go1.22.3.linux-amd64.tar.gz
  4. Extract it: sudo tar -C /usr/local -xzf go1.22.3.linux-amd64.tar.gz
  5. Set the Go environment variables. Add these lines to the /etc/profile file (or to the specific user’s profile, like ~/.bash_profile or ~/.bashrc):
    export PATH=$PATH:/usr/local/go/bin
    export GOPATH=$HOME/go
    export PATH=$PATH:$GOPATH/bin
  6. Source the profile: source /etc/profile
  7. Check it installed correctly: go version

Add and then run the following go script on your EC2 instance:

package main

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
)

func getRoot(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("/ request\n")
	io.WriteString(w, "Website #1!\n")
}
func getPing(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("got /ping request\n")
	io.WriteString(w, "pong HTTP!\n")
}

func main() {
	http.HandleFunc("/", getRoot)
	http.HandleFunc("/ping", getPing)

	err := http.ListenAndServe(":4800", nil)
	if errors.Is(err, http.ErrServerClosed) {
		fmt.Printf("server closed\n")
	} else if err != nil {
		fmt.Printf("error starting server: %s\n", err)
		os.Exit(1)
	}
}

You should then be able to see your application by visit your domain, for example http://mysite1.1234567892.xyz/. We haven’t setup ssl yet so make sure you’ve got http for the protocol.

Setting up SSL

Firstly, we need to setup letsencryt/certbot:

  1. sudo dnf install python3 augeas-libs
  2. sudo python3 -m venv /opt/certbot
  3. sudo /opt/certbot/bin/pip install --upgrade pip
  4. sudo /opt/certbot/bin/pip install certbot certbot-nginx
  5. sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot

Create a certificate: sudo certbot -n -d mysite1.1234567892.xyz --nginx --agree-tos --email your-email+mysite1@gmail.com

This will also add entries to /etc/nginx/sites-enabled/1234567892. You can also setup auto-renew : https://eff-certbot.readthedocs.io/en/latest/using.html#setting-up-automated-renewal

Your sites should now be accessible via https, for example: https://mysite1.1234567892.xyz/

Thanks to the following links for the info:
https://eff-certbot.readthedocs.io/en/latest/using.html#setting-up-automated-renewal
https://gist.github.com/rschuetzler/793f478fa656cca57181261a266ec127
https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-reverse-proxy-on-ubuntu-22-04

AWS Installing AWS Inspector Agent on Windows EC2 Instance

Hi everyone,

Just a quick post on installing the AWS Inspector Agent on a Windows EC2 instance.

Open PowerShell and run the following command:

(new-object System.Net.WebClient).DownloadFile('https://inspector-agent.amazonaws.com/windows/installer/latest/AWSAgentInstall.exe','C:UsersAdministratorDesktopAWSAgentInstall.exe')

On your desktop, right click on AWSAgentInstall.exe and select run as administrator. Follow the prompts.

Go to run, and execute services.msc. You should now see the Amazon SSM Agent:

If you go to your amazon console > amazon inspector > assessment targets > Click on your relevant target > Preview Target:

Your agent status should now be healthy.

Thanks to these links for the info:
https://superuser.com/a/330754/124014
https://docs.aws.amazon.com/inspector/latest/userguide/inspector_installing-uninstalling-agents.html#install-windows

AWS EC2 Elastic Beanstalk Going to Sleep – .Net/Windows/MSSQL Server Express

Hi everyone,

I’ve been having a bit of an issue with my AWS app going to sleep and taking a long time to handle initial requests.

I’m using .NET with Elastic Beanstalk on a T2 Micro Instance and MSSQL Server Express on RDS. My FrontEnd is a static ReactJS app that sits in S3 behind CloudFront. There’s also a load balancer across the backend.

My frontend was always instant but my initial Api calls were timing out. This ruled out S3 and CloudFront, leaving the following:

  • Load balancer
  • RDS/MSSQL
  • EC2/IIS

After a bit of Googling I came across something that looked fairly promising – MSSQL Server Express has a property called AutoClose set to ‘ON’ by default. AWS appears to correct this as mine was off however it’s worth checking:

-- If set to zero then auto close is off
SELECT DATABASEPROPERTY('mydatabasename','IsAutoShrink')

-- Check all instances at once
SELECT name,is_auto_close_on FROM sys.databases

-- Turn off if on
ALTER DATABASE myDB SET AUTO_CLOSE OFF

In my case the actual problem turned out to be IIS idle timeout. By default IIS automatically times out an application after 20 minutes. In order to disable this create the following ebextension:

commands:
    setIdleTimeoutToZero:
        cwd: "C:\windows\system32\inetsrv"
        command: "appcmd set apppool /apppool.name:DefaultAppPool /.processModel.idleTimeout:0.00:00:00"

If you haven’t done this before, all you need to do is create a folder called .ebextensions under your project directory. Then create a new file called iis-idle-timeout.config and add the yaml to it. If you need more information on iis timing out check out this great blog post: https://notebookheavy.com/2017/06/21/set-iis-idle-timeout-elastic-beanstalk/

Thanks to these sources for the solutions:
Disable auto_close: https://stackoverflow.com/a/1750400/522859
IIS Timeout: https://notebookheavy.com/2017/06/21/set-iis-idle-timeout-elastic-beanstalk/
EBExtension Info: http://notebookheavy.com/2017/05/01/auto-install-newrelic-agent-elastic-beanstalk/