Saturday, December 28, 2019

Simple golang webapp on docker for quick test

Golang App

mkdir golang-web-app
cd golang-web-app
vim main.go
package main

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

func main() {

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		hostname, err := os.Hostname()
		if err != nil {
			panic(err)
		}

		fmt.Fprintf(w, "Hello from host: %q The current  time is %q", hostname,time.Now().String())
	})


	log.Fatal(http.ListenAndServe(":8080", nil))

}

Run and Unit test it

go run main.go
access the localhost:8080

Dockerfile

FROM golang:1.12.0-alpine3.9
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]

Build Docker Image

docker build -t golang-web-app .
-- after above step done verify the status of docker image
docker images

Run Docker container

 docker run -p  8080:8080 -it golang-web-app

if everything goes well you can access the http://localhost:8080 endpoint.