Using docker in go language project

Time:2020-10-21

Link to the original text: using docker in go language project

ContainerBundle the program and anything it needs, including dependencies, tools, configuration files, and so on. In this way, the program is not interfered by the environment, and the development environment and the generation environment are completely consistent.

On the basis of container, docker further encapsulates, from file system, network interconnection to process isolation, which greatly simplifies the creation and maintenance of containers. Compared with traditional virtual machine, docker also has many advantages, such as more efficient utilization of system resources and faster startup time.

In this article, you will learn how to use docker in a go language project through a simple go language project.

Using docker in go language project

Create a simple go language project

Let’s create a go language project as an example. At the command line, enter the following command to create a folder:

mkdir gdp

We will use the go module for dependency management. Go to the root of the project and initialize the go module:

cd gdp
go mod init github.com/linehk/gdp

We will create a simple hello server. Create a directory namedhello_server.goNew document for:

touch hello_server.go

The contents of the document are as follows:

package main

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

    "github.com/gorilla/mux"
)

func handler(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query()
    name := query.Get("name")
    if name == "" {
        name = "Guest"
    }
    log.Printf("Received request for %s.\n", name)
    w.Write([]byte(fmt.Sprintf("Hello, %s!\n", name)))
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", handler)
    server := &http.Server{
        Handler:      r,
        Addr:         ":8080",
        ReadTimeout:  10 * time.Second,
        WriteTimeout: 10 * time.Second,
    }
    log.Println("Starting Server.")
    if err := server.ListenAndServe(); err != nil {
        log.Fatal(err)
    }
}

This project usesgorilla/muxPackage to create an HTTP route (the package is imported to show the role of the docker container bundle dependency). The address islocalhost:8080

Try to compile and run the project locally

Let’s try to compile and run the project locally. You can compile a project by entering the following command at the project root directory:

go build

The go build command will generate agdpThe executable file of. You can run the file like this:

./gdp
2020/08/19 21:33:49 Starting Server.

Our Hello server is now running and you can try usingcurlOr other tools to interact with it:

curl http://localhost:8080
Hello, Guest!
curl http://localhost:8080?name=sulinehk
Hello, sulinehk!

Write dockerfile to define docker image

Let’s write for this projectDockerfile, create a file named dockerfile in the root directory. The contents are as follows:

#Pull the latest basic image of go language
FROM golang:latest

#Set / app as the current working directory in the container
WORKDIR /app

#Copy the file to the current working directory
COPY . .

#Setting goproxy environment variables
ENV GOPROXY="https://goproxy.cn"

#Download all dependencies
RUN go mod download

#Compile project
RUN go build -o gdp .

#Exposed port 8080
EXPOSE 8080

#Execute executable file
CMD ["./gdp"]

Build image and run container

ImageIs the actual software distribution package that contains everything you need to run the application.

The container is built according to the image, which is a running example of the image, similar to the relationship between structure definition and structure variable in go language.

  • Build image:
docker build -t gdp .
  • Run container:
docker run -d -p 8080:8080 gdp
aa6a1afbe1b13ad0b0d1d656e157f762c5fe2229a8e0d95a025df26396ffc08f
  • Interact with servers running in the container:
curl http://localhost:8080
Hello, Guest!
curl http://localhost:8080?name=sulinehk
Hello, sulinehk!

Here are some other docker commands:

Using docker in go language project

summary

As can be seen, a well-defined dockfile plays a connecting role in the whole process.

Using docker in go language project

Reference link

Docker: from introduction to practice

Docker Documentation