Deploy Golang App to AWS using Docker-Machine

adkarigar
2 min readSep 12, 2020

--

lets spinoff….

Requirements

DockerToolBox ( docker-compose, docker-machine )
AWS account ( free-tier works )

Aws Credentials
get the key pair from the aws or create one in aws Resources

$ vim ~/.aws/credentials[default]
aws_access_key_id = **************Z3NVPP
aws_secret_access_key = ************T3Fyu7

Spin off docker-machine with aws driver

— make sure to create subnet in aws console first —

$ docker-machine create --driver amazonec2 \
--amazonec2-open-port 8080 \
--amazonec2-region ap-south-1 \
--amazonec2-subnet-id subnet-***** \
amazon-aws-test
# verify$ docker-machine ls

folder structure project

golang_aws
|_ docker-compose.yml
|_ Dockerfile
|_ main.go

docker-compose.yml

version: '3'
services:
goapp:
container_name: golang_webapp
hostname: golang_webapp
restart: on-failure
build:
context: .
environment:
GET_HOSTS_FROM: dns
ports:
- "8080:8080"

Dockerfile

FROM golang:1.15-alpine3.12 AS build
WORKDIR /src/
COPY main.go /src/
RUN CGO_ENABLED=0 go build -o /bin/demo
FROM scratch
COPY --from=build /bin/demo /bin/demo
ENTRYPOINT [ "/bin/demo" ]

main.go

package mainimport "log"
import "net/http"
func main() {
http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request){
_,err := w.Write([]byte("hello"))
if err!=nil {
log.Println("Error",err)
}
})
log.Println("up&Running....")
log.Fatal(http.ListenAndServe(":8080",nil))
}

Set Docker Env

$ docker-machine env amazon-aws-test
$ eval $("C:\Program Files\Docker Toolbox\docker-machine.exe" env aws-test1)

Build & Run

$ cd golang_aws
$ docker-compose up -d --build

verify — get the public ip from AWS or docker-machine ls

$ docker-machine ls
get the public_IP from URL column
$ curl -k http://<public_IP>:8080
hello

lets get to aws console

  1. EC2 instance is running up.
  2. lets look at the security group for our docker-machine.
security-group

Refactor

if any changes done to the code locally, build the docker-compose again.

thats’ all folks, take it easy………………

--

--