ruk·si

☁️ AWS
Basic ECS Setup

Updated at 2015-10-01 02:05

You need Docker to build the image for deployment.

# install https://www.docker.com/toolbox
# remember to choose your terminal app (iTerm Always) during installation
# run Docker Quickstart Terminal in your Applications
# wait for the VM to start up, this can take a while
# copy the IP e.g. 192.168.99.100

# open /etc/hosts and add Docker Virtual Machine IP there:
192.168.99.100      dockerhost

Start a new Go project.

mkdir gromash
cd gromash
touch main.go
touch Dockefile

Create Dockerfile.

FROM golang
ADD . /go/src/gromash
RUN go install gromash
ENTRYPOINT /go/bin/gromash
EXPOSE 8080

Create main.go.

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", indexHandler)
    addr := ":8080"
    fmt.Printf("Starting server at %s\n", time.Now())
    err := http.ListenAndServe(addr, nil)
    if err != nil {
        panic(err)
    }
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Time is %s", time.Now())
}

Test that the Go app works.

go run main.go
# localhost:8080, works? ok, stop it

Build the Docker image and test that it still works.

docker build -t ruksi/gromash .
docker run -d --publish 6060:8080 --name gromash-ps ruksi/gromash
# dockerhost:6060, works? cool.
docker exec -t -i gromash-ps /bin/bash # to get inside the container
docker rm -f gromash-ps

Upload Docker image to Docker Hub.

# create Docker Hub account (repository for Docker images)
docker login
docker info
docker push ruksi/gromash
# soon you will see your new image in Docker Hub
# setup ECS container instance cluster here...
Login to AWS
    IAM:
        Dashboard:
            Create Account Alias...
                https://company.signin.aws.amazon.com/console
        Create Group
            Name: Administrators
            Policies: AdministratorAccess
        Create User
            Name: yourname
            Group: Add to Administrators
            Manage Passwords -> Create Password
        Logout
Login again at https://company.signin.aws.amazon.com/console
    EC2:
        Key Pairs
            Create Key Pair
                Note: keypairs are region specific, choose deployment region.
                Name: id_yourname_company_uswest1
                Move keypair to ~/.ssh
                `chmod 400 id_yourname_company_uswest1.pem`
    VPC Dashboard:
        Start VPC Wizard
            Choose VPC with a Single Public Subnet
            VPC name: Container_VPC
            Create VPC
        Security Groups:
            Create Security Group
                Name tag: Container_SG_uswest1
                Description: SG for ECS
            Inbound Rules:
                HTTP    TCP     80      0.0.0.0/0
                HTTPS   TCP     443     0.0.0.0/0
                SSH     TCP     22      */32 # * = http://checkip.amazonaws.com

Go to ECS console and start custom task wizard.

Create Custom Task:
    Add Container Definition:
        Container Name:     gromash
        Image:              ruksi/gromash
        Memory:             500
        CPU Units:          10
        Essential:          Yes
        Port Mappings:      80 (Host) <-> 8080 (Container), TCP
    Add Volume:
        Name:               gromash-volume
        Source Path:        (empty)
    Next Step
Schedule Tasks:
    Create a Service
        Desired number of Tasks:    1
        Service Name:               gromash-service
        Elastic Load Balancing:     no
    Next Step
Configure Cluster:
    Number of Instances:    1
    Instance Type:          t2.micro
    Key Pair Name:          id_yourname_company_uswest1
    Security Ingress CIDR:  */32    # * = http://checkip.amazonaws.com
    IAM Role Information:
        Create IAM Roles
            ecsInstanceRole
    Review
Launch

Wait for the cluster to start up, takes a couple of minutes...
aws --version

# if not installed
curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws

aws --version
aws configure
WS Access Key ID [None]: ***
AWS Secret Access Key [None]: ***
Default region name [None]: us-west-1
Default output format [None]:

Create gromash-task-def.json.

{
    "family": "gromash-family",
    "volumes": [
        {
            "name": "gromash-volume",
            "host": {}
        }
    ],
    "containerDefinitions": [
        {
            "environment": [],
            "name": "gromash-app",
            "image": "ruksi/gromash",
            "cpu": 10,
            "memory": 500,
            "portMappings": [
                {
                    "containerPort": 8080,
                    "hostPort": 80
                }
            ],
            "mountPoints": [
                {
                    "sourceVolume": "gromash-volume",
                    "containerPath": "/go/src/gromash"
                }
            ],
            "command": [
                "go build"
            ],
            "entryPoint": [
                "/go/bin/gromash"
            ],
            "essential": true
        }
    ]
}
aws ecs register-task-definition --cli-input-json file://gromash-task-def.json

Create service based on the task definition.

ECS:
    default:
        Services:
            Create
                Task Definition:            gromash-family:1
                Cluster:                    default
                Service Name:               gromash-1
                Number of Tasks:            1
                Elastic Load Balancing:     no

Go to EC2 console, copy the instance DNS: http://xxxxxxxxxxxx.us-west-1.compute.amazonaws.com/ Navigate to that with your browser. Now you have a Go server cluster with a single server, congratulations!

Notes:

  • You cannot add more tasks to this service because there isn't enough ports, CPU or memory.
  • If you want to remove the resources created in this note:
    • go to CloudFormation console and press Delete Stack
    • go to the ECS, clusters, gromash-1, reduce number of tasks to 0
    • delete the ECS service gromash-1
    • delete the ECS cluster default
    • go to VPC, delete the Container_VPC