The golang application packages the docker image and runs it


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

Write program code


package main

import ""

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
	r.Run("") // listen and serve on (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
#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 .
#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
[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>8080/tcp   gin_docker

Access services

[email protected]:~/go_project/gin_docker$ curl

Reference articles

  • Failed to download package when using docker build