2023-10-16 · 2

Golang Dockerfile & ECR Upload

cloudgolangecr

This post is over 2 years old. The content may be outdated.

go mod init example.com/api
go get github.com/gin-gonic/gin
go get github.com/go-sql-driver/mysql

After installing Golang, run the commands above to initialize the module and download gin. ECR is a place to push images, similar to how GitHub hosts code — here we will upload a Golang Docker image and eventually deploy the service to ECS.

// main.go
package main

import (
     "fmt"
     "database/sql"
     "log"

     "github.com/gin-gonic/gin"
     _ "github.com/go-sql-driver/mysql"
)

func main() {
	dsn := "[id]:[password]@tcp([db_endpoint]:[db_port])/"
  db, err := sql.Open("mysql", dsn)
  if err != nil {
      fmt.Println(err)
      return
  }

  if db != nil {
    fmt.Println("db connect to rds...")
  }
  defer db.Close()

  var databases []string

  // Query to get all databases
  rows, err := db.Query("SHOW DATABASES")
  if err != nil {
    log.Fatal(err)
  }
  defer rows.Close()

  for rows.Next() {
    var dbName string
    if err := rows.Scan(&dbName); err != nil {
      log.Fatal(err)
    }
    databases = append(databases, dbName)
  }

  fmt.Println("Databases:", databases)

  if err := rows.Err(); err != nil {
    log.Fatal(err)
  }

  r := gin.Default()

  r.GET("/", func(c *gin.Context) {
    c.JSON(200, gin.H{
      "message": "gin is running",
      "databases" databases
    })
  })

  r.Run(":3000")
}

The code above is an example. If you have a database available, tweak it slightly and run it — you should see it list the databases from your DB.

FROM golang:1.18-alpine as build

WORKDIR /app

ENV GO111MODULE=on
ENV CGO_ENABLED=0
ENV GOOS=linux
ENV GOARCH=amd64

COPY . .

RUN go build -o main main.go

FROM alpine:3.12
RUN apk --update add ca-certificates

WORKDIR /app

COPY --from=build /app/main .

EXPOSE 3000

CMD ["/app/main"]

Now write the Dockerfile as shown above, then save your credentials in ~/.aws/credentials:

[default]
aws_access_key_id = [access_key_id]
aws_secret_access_key = [access_key]

Alternatively, if you have awscli installed, aws configure does the same thing.

docker build -t restgo .
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin [ECR_URL]
docker tag restgo [ECR_URL]
docker push [ECR_URL]

Running the commands above uploads the Golang Docker image to ECR.


Original (Korean): tistory — published 2023-10-16, migrated to this blog. This translation was generated with the help of AI.

Comments

Delete this comment?

Related posts

Golang Dockerfile & ECR Upload · 나봄하랑