How to create and dockerize a Go application.

black and gray laptop computer turned on doing computer codes
Reading Time: 3 minutes

Go is a procedural , open source programming language famous for its simplicity , efficiency and reliability. So GO is popularly known for its network program and infrastructure.

  • Go is highly used for cloud based or server side applications.
  • Many CLI tools are written in Go.

Whats interesting about Go is that it has its own data type string.At bottom it is still a sequence of byte but with some additional features.

  • Its immutable
  • It has fixed length
  • Length is also given at the same time.

Unlike the C lang the Golang memory layout starts from the last part first i.e the Len which is the length.

Above are a few use case and many more are there . So today we will look as how to dockerize a go application. First let’s create a simple Go application.

Prerequisite

  • Docker installed
  • Go installed

To install go refer to the below – https://www.educative.io/edpresso/how-to-install-go-on-ubuntu

Creating a GO application :-

Now , in this demo lets create a demo app i which further is dockerized . To create the application follow the below steps.

Our application will contain a simple main.go file which would contain the program to print hello world.

The main.go file will contain the below code.To start below first run the below command:-

go mod init

The below file is the main.go file which contains whole of the code.

package main
 
import (
 "encoding/json"
 "fmt"
 "log"
 "net/http"
 
 "github.com/gorilla/mux"
)
 
func main() {
 router := mux.NewRouter()
 router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
   response := map[string]string{
     "message": "Welcome to my hello application",
   }
   json.NewEncoder(rw).Encode(response)
 })
 
 router.HandleFunc("/{name}", func(rw http.ResponseWriter, r *http.Request) {
   vars := mux.Vars(r)
   name := vars["name"]
   var message string
   if name == "" {
     message = "Hello World"
   } else {
     message = "Hello " + name
   }
   response := map[string]string{
     "message": message,
   }
   json.NewEncoder(rw).Encode(response)
 })
 
 log.Println("Server is running!")
 fmt.Println(http.ListenAndServe(":8081", router))
}

To run the above program first install the gorilla/mux package and declare the path. To install the package run the below command.

go get github.com/gorilla/mux

Now to run the above application run the below command.

go run main.go

The above image is the output . The output will be visible on localhost:8081.

Dockerizing the above application.

To dockerize the application we need to write a docker file which will further generate a docker image.

Docker image contains all the needful that an application needs to run.

An image includes everything needed to run an application- the code or binary, runtimes, dependencies, and any other filesystem objects required.

An image consists of your app definition and everything needed to run the application in the simplest terms.

To start make a dockerfile in the same directory.It will contain the below code.You can write your own dockerfile to run the application.


FROM golang:1.17-alpine as build-env
 
ENV APP_NAME my-hello-app
ENV CMD_PATH main.go
 
COPY . $GOPATH/src/$APP_NAME
WORKDIR $GOPATH/src/$APP_NAME
 
RUN CGO_ENABLED=0 go build -v -o /$APP_NAME $GOPATH/src/$APP_NAME/$CMD_PATH
 
FROM alpine:3.14
 
ENV APP_NAME my-hello-app
 
COPY --from=build-env /$APP_NAME .
 
EXPOSE 8081
 
CMD ./$APP_NAME

The above dockerfile is multi stage dockerfile which contains steps for building the app and running the application. In the above file i have passed env of application name and cmd path.The file contains the env declared above.

To build the above docker image run the below command in the same directory where dockerfile is there.

docker build -t mygo .

The above will build an image with name mygo with latest tag. The output will be like :

Now to run the above image run the below command.

docker run -d -p 8081:8081 mygo:latest

After running the above command the container will start on 8081. Then when you will run localhost:8081 on your browser the output will display. Though the application runs in container yet it will be exposed on 8081. Now , the application runs in the container with all its dependencies.

Conclusion

So in the above we learnt how to create an app and dockerize it. Further if the application is big and you don’t want to build image again and again then use a docker-compose file. It acts like a container orchestrator. Now , lets learn more about go through the below link.

The below link is helpful for more information –

https://blog.knoldus.com/getting-started-with-golang/

Written by 

Rishivant is a enthusiastic devops learner at Knoldus. He believes in going 1% up everyday and showcases his learning in his work.