Go实现httpserver的源代码编写Dockerfile搭建镜像测试httpserver服务是否成功开启,并通过nsenter查看容器网络配置上传到Docker hub另一种Dockerfile编写方式 Go实现httpserver的源代码
创建main.go文件
package mainimport ("fmt""log""net""net/http""net/http/pprof""os""strings")func main() {mux := http.NewServeMux() //多路复用处理函数mux.HandleFunc("/", mainIndex) //handler,谁来处理requestmux.HandleFunc("/healthz", healthz) //healthz, 返回200,作为健康检查mux.HandleFunc("/debug/pprof/", pprof.Index) //mux的debug模块mux.HandleFunc("/debug/pprof/profile", pprof.Profile)mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)mux.HandleFunc("/debug/pprof/trace", pprof.Trace)err := http.ListenAndServe(":8080", mux) //启动服务if err != nil {log.Fatal("start server failed: %s n", err.Error())}}func mainIndex(w http.ResponseWriter, r *http.Request) {//w.Write([]byte("Welcome to
FROM golang:1.17 AS builderENV GO111MODULE=off CGO_ENABLED=0 GOOS=linux GOARCH=amd64WORKDIR /buildCOPY 、.RUN go build -o httpserver .FROM scratchCOPY --from=builder /build/httpserver /EXPOSE 8080ENTRYPOINT ["/httpserver"]
搭建镜像docker build读取Dockerfile文件,搭建镜像,-t为容器添加tag
docker build 、-t httpserver:0.0.1docker run -d -p 8080:8080 httpserver:0.0.1
测试httpserver服务是否成功开启,并通过nsenter查看容器网络配置 httpserver容器运行成功
[root@localhost httpserver]# docker ps ConTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESd2e1fe4e03f2 httpserver:0.0.1 "/httpserver" 2 hours ago Up 2 hours 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp brave_chaum[root@localhost httpserver]# PID=$(docker inspect --format "{{ .State.Pid }}" brave_chaum)[root@localhost httpserver]# nsenter -t $PID -n ip a1: lo:
[root@localhost httpserver]# docker tag 3fe3921ec1f0 henryli98/httpserver:0.0.1[root@localhost httpserver]# docker push henryli98/httpserver:0.0.1The push refers to repository [docker.io/henryli98/httpserver]af92bb057461: Pushed 0.0.1: digest: sha256:06cb18e9d2cb4d79f3891eb848b23e5e89b80bc1f535c74766bfc1fe2644180d size: 528
另一种Dockerfile编写方式FROM golang:1.17 AS buildWORKDIR /httpserver/COPY 、.ENV CGO_ENABLED=0ENV GO111MODULE=onENV GOPROXY=https://goproxy.cn,directRUN GOOS=linux go build -installsuffix cgo -o httpserver main.goFROM busyboxCOPY --from=build /httpserver/httpserver /httpserver/httpserverEXPOSE 8360ENV ENV localWORKDIR /httpserver/ENTRYPOINT ["./httpserver"]
本文章参考极客时间课程内容,个人学习记录使用