准备项目
初始化一个项目
# mkdir demobuild # cd demobuild/ # go mod init gindemo go: creating new go.mod: module gindemo
编写代码gindemo.go
packagemainimport"github.com/gin-gonic/gin"funcmain() { r :=gin.Default() r.GET("/ping", func(c*gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run("0.0.0.0:9091") // listen and serve on 0.0.0.0:8080}
尝试运行
没运行成功,提示需要安装gin
#gorungindemo.gogindemo.go:3:8: norequiredmoduleprovidespackagegithub.com/gin-gonic/gin; toaddit: gogetgithub.com/gin-gonic/gin
安装依赖
#gogetgithub.com/gin-gonic/gingoget: addedgithub.com/gin-gonic/ginv1.7.4
再次运行
#gorungindemo.go[GIN-debug] [WARNING] CreatinganEngineinstancewiththeLoggerandRecoverymiddlewarealreadyattached.[GIN-debug] [WARNING] Runningin"debug"mode.Switchto"release"modeinproduction.-usingenv: exportGIN_MODE=release-usingcode: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET/ping-->main.main.func1 (3handlers) [GIN-debug] ListeningandservingHTTPon0.0.0.0:9091
多阶段构建
编写Dockerfile
FROM golang:1.17 as build WORKDIR /go/src/gindemo COPY . . RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOPROXY=https://goproxy.cn,direct go build -ldflags="-w-s" -o gindemo . FROM ubuntu:18.04 WORKDIR /usr/local/demo COPY --from=build /go/src/gindemo/gindemo . EXPOSE9091CMD ["./gindemo"]
查看目录结构
# tree. |-- Dockerfile |-- gindemo.go |-- go.mod `-- go.sum0 directories, 4 files
执行构建镜像
如果没有多阶段构建,你的操作可能如下:
- 在本地把go程序编译好,再通过docker的方式拷贝到容器镜像中,那么本地环境是存在差异的
- 在容器镜像中,先是安装go环境,然后配置go可执行文件环境变量,最后编译,强耦合在一起了
# docker build . -t morebuild:test
检测镜像是否构建成功
# docker images|grep morebuildmorebuild test 4a0218330261 25 seconds ago 69.5MB
项目运行
运行容器
docker run -it-d-p9091:9091 morebuild:test
查看容器内部
45f54为容器运行部分ID
# docker exec -it 45f54 bashroot@45f541ce524f:/usr/local/demo# pwd/usr/local/demo root@45f541ce524f:/usr/local/demo# lsgindemo root@45f541ce524f:/usr/local/demo# ps -efUID PID PPID C STIME TTY TIME CMD root 10006:13 pts/0 00:00:00 ./gindemo root 110006:13 pts/1 00:00:00 bashroot 2311006:13 pts/1 00:00:00 ps-ef
curl访问
curl http://127.0.0.1:9091/ping
查看容器日志
# docker logs -f 45f54[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in"debug" mode. Switch to "release" mode in production. - using env: exportGIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET /ping --> main.main.func1 (3 handlers) [GIN-debug] Listening and serving HTTP on 0.0.0.0:9091 [GIN] 2021/10/29 -06:23:43 | 200 | 58.471µs | 172.17.0.1 | GET "/ping"
至此已经演示完毕了