Run Go application in Docker Container

Generate a Go Application

Create Project folder HelloWorld. Open VS Code and type in Terminal :

1
go mod init HelloWorld 

Create a file hello.go with the following content :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to my website!")
	})

	fs := http.FileServer(http.Dir("static/"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	http.ListenAndServe(":3000", nil)
}

Run the application :

1
 go run .\hello.go

Create Docker Image

Create a docker file named ‘Dockerfile’ and add the following content :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#build stage
FROM golang:alpine AS builder
RUN apk add --no-cache git
WORKDIR /go/src/app
COPY . .
RUN go get -d -v ./...
RUN go build -o /go/bin/app -v ./...

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/app /app
ENTRYPOINT /app
LABEL Name=helloworld Version=0.0.1
EXPOSE 3000

alpine is a lightweight container. Create the container and execute it :

1
2
docker build --tag go-hellov1:latest .
docker run -it -p 80:3000 go-hellov1   

If all goes well, accessing http://localhost will show the message “Welcome to my website!”.