在go语言中使用docker
1、新建一个文件夹(这里文件名是docker_test),用作go项目的示例
先放上总体目录的结构:
2、在goland打开该文件夹,在项目根目录里创建一个名为hello.go的新文件。
文件写上如下内容:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// User 接收入参结构体
type User struct {
Name string `form:"name" json:"name"` //
}
func main() {
// 1.创建路由
r := gin.Default()
// 2.绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/hello", func(c *gin.Context) {
req := User{}
var name string
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
return
}
name = req.Name
fmt.Println(name)
if req.Name == "" {
name = "Hi!小小星"
}
c.JSON(http.StatusOK, gin.H{"name": name})
})
// 3.监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run(":8000")
}
3、依次执行下边两条命令
go mod init docker_test
go mod tidy
4、在本地编译该项目并运行
在根目录下执行命令go build
然后得到docker_test.exe二进制文件,./docker_test.exe
运行该文件,结果:
[GIN-debug] Listening and serving HTTP on :8000
5、服务已经运行起来了,使用curl或其他工具进行测试
curl http://localhost:8000/hello
{"name":"Hi!小小星"}
curl http://localhost:8000/hello?name=LiHua
{"name":"LiHua"}
6、在项目根目录下创建名为Dockerfile文件并编写,用来构建镜像
# 拉取 Go 语言最新的基础镜像
FROM golang:latest
# 设置容器内 /app 为当前工作目录
WORKDIR /app
# 把文件复制到当前工作目录
COPY . .
# 设置 GOPROXY 环境变量
ENV GOPROXY="https://goproxy.cn"
# 下载所有依赖项
RUN go mod download
# 编译项目
RUN go build -o docker_test .
# 容器端口
EXPOSE 8000
# 执行可执行文件
CMD ["./docker_test"]
7、构建镜像
执行命令docker build -t docker_test:v1 .
,注意后边是有个小数点的,别漏了
在这里我们指定了最终镜像的名称 -t docker_test:v1
等待一段时间…
8、运行容器
执行命令和结果:
docker run --name hello -d -p 8000:8000 docker_test:v1
91ce7091de5167d1e0885a63144963a3fa771048db630dcc1011340b829e470e
上边参数说明:
-d :后台方式运行
–name hello::容器名字为hello
-p:指定容器的端口,-p 8000:8000(主机端口:容器端口)
9、容器成功运行后,使用curl与容器内的服务进行交互
curl http://localhost:8000/hello
{"name":"Hi!小小星"}
curl http://localhost:8000/hello?name=LiHua
{"name":"LiHua"}
最后,测试成功!