将httpserver做成一个镜像
一,首先将http脚本转换成linux下能运行的二进制文件
zhaojinqiao@B-LBE6LVDL-1748 03 % ls httpserver httpserver.go httpsev main main.go zhaojinqiao@B-LBE6LVDL-1748 03 % env GOOS=linux go build -o httpser httpserver.go zhaojinqiao@B-LBE6LVDL-1748 03 % ls httpser httpserver httpserver.go httpsev main main.go
二,将httpsev拷贝到linux环境下的httpsever文件夹

Dockerfile内容如下:
FROM ubuntu:latest COPY httpsev /httpsev EXPOSE 80 ENTRYPOINT /httpsev
三,镜像构建:
docker build -t http .

四,进入这个镜像:
docker run -it --entrypoint /bin/sh http:latest

五:容器内启动http服务:

六,宿主机访问docker内的http服务
- docker ps(找到容器container id)
- docker inspect cf70f0434fa1|grep -i pid
- nsenter -t 16377 -n ip a
- curl 172.17.0.20:8000

第二种方式,标准写法:
go语言写的server ,main.go
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"strings"
)
func index(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("<h1>Welcome to Cloud Native</h1>"))
// 03.设置version
os.Setenv("VERSION", "v0.0.1")
version := os.Getenv("VERSION")
w.Header().Set("VERSION", version)
fmt.Printf("os version: %s \n", version)
// 02.将requst中的header 设置到 reponse中
for k, v := range r.Header {
for _, vv := range v {
fmt.Printf("Header key: %s, Header value: %s \n", k, v)
w.Header().Set(k, vv)
}
}
// 04.记录日志并输出
clientip := getCurrentIP(r)
//fmt.Println(r.RemoteAddr)
log.Printf("Success! Response code: %d", 200)
log.Printf("Success! clientip: %s", clientip)
}
// 05.健康检查的路由
func healthz(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "working")
}
func getCurrentIP(r *http.Request) string {
// 这里也可以通过X-Forwarded-For请求头的第一个值作为用户的ip
// 但是要注意的是这两个请求头代表的ip都有可能是伪造的
ip := r.Header.Get("X-Real-IP")
if ip == "" {
// 当请求头不存在即不存在代理时直接获取ip
ip = strings.Split(r.RemoteAddr, ":")[0]
}
return ip
}
// ClientIP 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。
func ClientIP(r *http.Request) string {
xForwardedFor := r.Header.Get("X-Forwarded-For")
ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
if ip != "" {
return ip
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
func main() {
mux := http.NewServeMux()
// 06. debug
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.HandleFunc("/", index)
mux.HandleFunc("/healthz", healthz)
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatalf("start http server failed, error: %s\n", err.Error())
}
}
Dockerfile:
FROM golang:1.17 AS builder ENV GO111MODULE=off \ CGO_ENABLED=0 \ GOOS=linux \ GOARCH=amd64 WORKDIR /build COPY . . RUN go build -o httpserver . FROM scratch COPY --from=builder /build/httpserver / EXPOSE 8080 ENTRYPOINT ["/httpserver"]
将这两个文件放入同一目录下:

然后执行命令:docker build -t httpserver:0.0.3 .

docker镜像已经build好了
全世界的程序员们联合起来吧!

浙公网安备 33010602011771号