使用docker部署go项目并实现热编译

gin框架main.go入口:

package main

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

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

// 定义中间
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行了")
		// 设置变量到Context的key中,可以通过Get()取
		c.Set("request", "中间件")
		// 执行函数
		c.Next()
		// 中间件执行完后续的一些事情
		status := c.Writer.Status()
		fmt.Println("中间件执行完毕", status)
		t2 := time.Since(t)
		fmt.Println("time:", t2)
	}
}

func main() {
	// 1.创建路由
	r := gin.Default()
	r.Use(MiddleWare(), gin.Logger())
	// 2.绑定路由规则,执行的函数
	// gin.Context,封装了request和response
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!"+time.Now().Format("2006-01-02 15:04:05"))
	})

	//返回json http://127.0.0.1:8000/json
	r.GET("/json", func(c *gin.Context) {
		name := c.Query("name")
		//post传参用 c.PostForm("name")
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  18,
		})
	})

	//返回xml格式 http://127.0.0.1:8000/xml
	r.GET("/xml", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{
			"name": "xiaoming",
			"age":  18,
		})
	})

	//加载模板文件
	r.LoadHTMLGlob("templates/**/*")
	r.Static("/static", "./static")
	r.GET("/index/:id", func(c *gin.Context) {
		id := c.Param("id")
		fmt.Println(id)
		c.HTML(http.StatusOK, "user/index.html", gin.H{
			"title":   "我是index页面,参数id=" + id,
			"address": "www.chenqicheng.com",
			"users":   []string{"xiaoming", "xiaohei", "xiaohong"},
			"id":      id,
		})
	})

	// 路由组1 ,处理GET请求  //局部中间件
	v1 := r.Group("/api", MiddleWare())
	// {} 是书写规范
	{
		v1.GET("/get_user", func(c *gin.Context) {
			req, _ := c.Get("request")
			fmt.Println("request:", req)
			c.String(http.StatusOK, "api get_user")
		})
		v1.GET("get_info", func(c *gin.Context) {
			c.String(http.StatusOK, "api get_info")
		})
	}
	v2 := r.Group("/admin")
	{
		v2.GET("/login", func(c *gin.Context) {
			c.String(http.StatusOK, "admin login")
		})
		v2.POST("/submit", func(c *gin.Context) {
			c.String(http.StatusOK, "admin submit")
		})
	}

	// 3.监听端口,默认在8080
	// Run("里面不指定端口号默认为8080")
	r.Run(":8000")
}

Dockerfile:

FROM golang:latest

WORKDIR /www/src/gomod_study
COPY . /www/src/gomod_study
#开启gomodule
RUN go env -w GO111MODULE=on
#配置国内代理
RUN go env -w GOPROXY=https://goproxy.io,direct
#下载 go.mod 文件中指明的所有依赖
# RUN go mod download

#热编译
Run go get github.com/githubnemo/CompileDaemon
#RUN go build -o main .

EXPOSE 8000
#ENTRYPOINT ["./main"]
#监视目录中的 .go 文件并在文件更改时调用 go build
ENTRYPOINT CompileDaemon --build="go build -o main ." --command=./main

构建镜像(注意. copy的时候表示复制当前目录上下文)

docker build -t go:qc .

Sending build context to Docker daemon  475.1kB
Step 1/7 : FROM golang:latest
latest: Pulling from library/golang
0e29546d541c: Already exists 
9b829c73b52b: Already exists 
cb5b7ae36172: Already exists 
6494e4811622: Already exists 
6e1d20a8313e: Already exists 
593823f101dc: Already exists 
1b4aae56cdbe: Already exists 
Digest: sha256:c72fa9afc50b3303e8044cf28fb358b48032a548e1825819420fd40155a131cb
Status: Downloaded newer image for golang:latest
 ---> 276895edf967
Step 2/7 : WORKDIR /www/src/gomod_study
 ---> Running in 14938f8d6fda
Removing intermediate container 14938f8d6fda
 ---> 77226038fcb3
Step 3/7 : COPY . /www/src/gomod_study
 ---> 00b118993439
Step 4/7 : RUN go env -w GOPROXY=https://goproxy.io,direct
 ---> Running in e4dc0aa10c62
Removing intermediate container e4dc0aa10c62
 ---> 2290ae586964
Step 5/7 : RUN go build -o main .
 ---> Running in faa7742d3098
go: downloading github.com/gin-gonic/gin v1.7.7
go: downloading github.com/gin-contrib/sse v0.1.0
go: downloading github.com/mattn/go-isatty v0.0.14
go: downloading github.com/go-playground/validator/v10 v10.10.1
go: downloading github.com/golang/protobuf v1.5.2
go: downloading github.com/ugorji/go/codec v1.2.7
go: downloading gopkg.in/yaml.v2 v2.4.0
go: downloading golang.org/x/sys v0.0.0-20220408201424-a24fb2fb8a0f
go: downloading github.com/go-playground/universal-translator v0.18.0
go: downloading github.com/leodido/go-urn v1.2.1
go: downloading golang.org/x/crypto v0.0.0-20220408190544-5352b0902921
go: downloading golang.org/x/text v0.3.7
go: downloading google.golang.org/protobuf v1.28.0
go: downloading github.com/go-playground/locales v0.14.0
Removing intermediate container faa7742d3098
 ---> 69fccf34d635
Step 6/7 : EXPOSE 8000
 ---> Running in d2eda95a5c86
Removing intermediate container d2eda95a5c86
 ---> 9b71df9c09eb
Step 7/7 : ENTRYPOINT ["./main"]
 ---> Running in 6b3a8606ea35
Removing intermediate container 6b3a8606ea35
 ---> 9f129a69d8ea
Successfully built 9f129a69d8ea
Successfully tagged go:qc

创建并后台运行容器

docker run -d --name golang-qc -v /root/dnmp/www/gomod_study/:/www/src/gomod_study -p 8000:8000 go:qc

查看日志

docker logs golang-qc

[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:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (5 handlers)
[GIN-debug] GET    /json                     --> main.main.func2 (5 handlers)
[GIN-debug] GET    /xml                      --> main.main.func3 (5 handlers)
[GIN-debug] Loaded HTML Templates (7): 
        - header.html
        - public/header
        - index.html
        - user/index.html
        - 
        - footer.html
        - public/footer

[GIN-debug] GET    /static/*filepath         --> github.com/gin-gonic/gin.(*RouterGroup).createStaticHandler.func1 (5 handlers)
[GIN-debug] HEAD   /static/*filepath         --> github.com/gin-gonic/gin.(*RouterGroup).createStaticHandler.func1 (5 handlers)
[GIN-debug] GET    /index/:id                --> main.main.func4 (5 handlers)
[GIN-debug] GET    /api/get_user             --> main.main.func5 (6 handlers)
[GIN-debug] GET    /api/get_info             --> main.main.func6 (6 handlers)
[GIN-debug] GET    /admin/login              --> main.main.func7 (5 handlers)
[GIN-debug] POST   /admin/submit             --> main.main.func8 (5 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8000

访问8000端口查看: 访问成功!

修改main.go文件:

	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World success!我被修改了"+time.Now().Format("2006-01-02 15:04:05"))
	})

重新访问8000端口查看: 可以看到热编译成功!

docker-composer构建方式

执行命令docker-compose up -d golang-qc

version: "3"
services:
  golang-qc: 
    build:
      context: ./ #指定Dockerfile文件位置
    container_name: golang-qc
    ports:
      - "8000:8000"
    volumes:
      - ./:/www/src/gomod_study:rw
    networks:
      - default



zed
请先登录后发表评论
  • latest comments
  • 总共0条评论