The golang application packages the docker image and runs it

Time:2021-10-27

Use the gin framework to build a most basic web service to illustrate the whole process.

Write program code

main.go

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run("0.0.0.0:8080") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Note that the host in docker cannot be configured127.0.0.1perhaps192.168.0.1Otherwise, the host machine will not be able to access the port. Therefore, when the service is started, it should be bound to0.0.0.0Come on.

Write dockerfile file

FROM golang:alpine
MAINTAINER JiangHongJie "[email protected]"
#Working directory in docker
WORKDIR $GOPATH/src/gin_docker
#Synchronize the current directory to the docker working directory, or configure only the required directories and files (configuration directory, compiled program, etc.)
ADD . ./
#For well-known reasons, some packages will have download timeouts. The proxy service of go module is also used in docker
ENV GO111MODULE=on
ENV GOPROXY="https://goproxy.io"
#Specify the file name after compilation. You can use the default file name without setting. The last step is to execute the file name
RUN go build -o gin_docker .
EXPOSE 8080
#This is consistent with the compiled file name
ENTRYPOINT  ["./gin_docker"]

Build docker image

sudo docker build -t gin_docker .

View the image list when the build is complete

[email protected]:~/go_project/gin_docker$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
gin_docker          latest              ed64de3e98e9        2 hours ago         469MB
logforce            latest              3cfe19164260        3 hours ago         511MB
                            d20ebc82d1e6        6 hours ago         810MB
                            c19c1e8968e1        6 hours ago         828MB
golang              alpine              30df784d6206        2 weeks ago         370MB

Start container

[email protected]:~/go_project/gin_docker$ docker run --name gin_docker -p 8080:8080 -d gin_docker
ae97da70bc94a4c9a235f44a7d12030b283a2fabd56fc2be1a70ffef3a805c71
[email protected]:~/go_project/gin_docker$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
ae97da70bc94        gin_docker          "./gin_docker"      24 seconds ago      Up 22 seconds       0.0.0.0:8080->8080/tcp   gin_docker

Access services

[email protected]:~/go_project/gin_docker$ curl 127.0.0.1:8080/ping
{"message":"pong"}

Reference articles

  • Failed to download golang.org/x package when using docker build