部署描述

配置文件

~/Work/K8s/Deployment/nginx.yaml
# app的版本
apiVersion: apps/v1
# 描述: Deployment
kind: Deployment
# 元数据
metadata:
  # 名称
  name: nginx-deployment
  # 部署的应用标签
  labels:
    app: nginx
# 规格与预期设置
spec:
  # 启动数量
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  # 每个容器启动的相关配置
  template:
    metadata:
      labels:
        app: nginx
    # 规格与预期设置
    spec:
      # 容器数组: - 代表一个
      containers:
      - name: nginx
        # docker 镜像
        image: nginx
        # 容器内部使用端口
        ports:
        - containerPort: 80
        # 资源
        resources:
          # 每个nginx占用 cpu:100m,内存: 128Mi
          limits:
            cpu: 100m
            memory: 128Mi

启动

启动Deployment

$ kubectl apply -f ~/Work/K8s/Deployment/nginx.yaml

查看状态

$ kubectl get pods
NAME                                READY   STATUS              RESTARTS   AGE
nginx-deployment-875ddfd9f-4kcpq   0/1     ContainerCreating   0          7s
nginx-deployment-875ddfd9f-6tsvv   0/1     ContainerCreating   0          7s
nginx-deployment-875ddfd9f-zz2dz   0/1     ContainerCreating   0          7s

# 启动成功的状态
$ kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-875ddfd9f-4kcpq   1/1     Running   0          21s
nginx-deployment-875ddfd9f-6tsvv   1/1     Running   0          21s
nginx-deployment-875ddfd9f-zz2dz   1/1     Running   0          21s

访问测试

$ kubectl exec -it nginx-deployment-875ddfd9f-4kcpq -- /bin/bash
root@nginx-deployment-65c85456df-rm59r:/# curl 127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
root@nginx-deployment-65c85456df-rm59r:/#

服务管理

配置文件

~/Work/K8s/Service/nginx.yaml
# 版本
apiVersion: v1
# 描述: 服务
kind: Service
# 名称
metadata:
  name: nginx-service
# 设置
spec:
  # 控制容器标签为: nginx(template:labels:app: nginx
  selector:
    app: nginx
  # 管理容器的端口为容器使用的端口
  ports:
    - protocol: TCP
      port: 80

启动

启动

$ kubectl apply -f ~/Work/K8s/Service/nginx.yaml

查看服务状态

$ kubectl get svc
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1      <none>        443/TCP   29m
nginx-service   ClusterIP   10.96.51.132   <none>        80/TCP    7s

进入pod容器可通过服务ip或服务名随机访问管理的容器

$ kubectl exec -it nginx-deployment-875ddfd9f-4kcpq -- /bin/bash

# 容器内部访问服务
$ curl localhost
$ curl 10.96.51.132
$ curl nginx-service

删除

# 删除全部deplyment
$ kubectl delete deployment --all

# 查看pods
$ kubectl get pods
No resources found in default namespace.

目录结构

.
├── Dockerfile
└── main.go

镜像制作

demo

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
)

func main() {
    // http://127.0.0.1:8000/add?a=1&b=2
    http.HandleFunc("/add", func(writer http.ResponseWriter, request *http.Request) {
        v := "1.0.0"
        _ = request.ParseForm() // 解析参数
        fmt.Println("path:", request.URL.Path)
        a, b := 1, 1
        if request.Form["a"] != nil {
            a, _ = strconv.Atoi(request.Form["a"][0])
        }
        if request.Form["b"] != nil {
            b, _ = strconv.Atoi(request.Form["b"][0])
        }

        writer.Header().Set("Content-Type", "application/json")
        jsData, _ := json.Marshal(map[string]any{
            "version": v,
            "data":    fmt.Sprintf("%d+%d=%d", a, b, a+b),
        })
        _, _ = writer.Write(jsData)
    })

    // 监听服务
    _ = http.ListenAndServe(":8000", nil)
}

制作Dockerfile

FROM golang:1.18
# 拷贝代码(宿主机当前目录拷贝到虚拟机目录)
COPY . /go/src/demo/http-server
# 切换工作目录
WORKDIR /go/src/demo/http-server
# 暴露端口
EXPOSE 8000
# 配置环境&&# 编译
RUN go env -w GO111MODULE=on \
    && go env -w GOPROXY=https://goproxy.cn,direct \
    && go build -o app
# 启动服务
ENTRYPOINT [ "./app" ]

构建镜像

# 构建镜像
$ docker build -t demo-http-server .

# 查看镜像
$ docker image ls | grep "demo-http-server"
demo-http-server    latest       739a8da0c6a6   7 seconds ago    828MB

# 运行容器
$ docker container run -d -p 9000:8000 demo-http-server

# 宿主机访问测试
$ curl http://127.0.0.1:9000/add?a=1&b=2

镜像瘦身

修改Dockerfile

# 定义第一步用来编译的环境(使用alpine镜像)
FROM golang:1.18-alpine AS go-alpine-builder
# 拷贝代码
COPY . /go/src/http-server
# 设置工作目录
WORKDIR /go/src/http-server
# 设置执行命令
RUN go env -w GO111MODULE=on \
    && go env -w GOPROXY=https://goproxy.cn,direct \
    && go build -o app

# 重制作镜像-通过dockerhub可查看golang1.18-alpine对应的alpine版本
FROM alpine:3.15
COPY --from=go-alpine-builder /go/bin/http-server/app /bin/http-server

# 暴露端口
EXPOSE 8000

ENTRYPOINT [ "/bin/http-server" ]

构建镜像

# 构建镜像
$ docker build -t demo-http-server .

# 查看镜像大小
$ docker image ls | grep "demo-http-server"
demo-http-server    latest       70141db073c1   44 seconds ago   11.6MB

环境配置

配置优先级: 命令行 > 环境变量 > 配置文件 > 默认值

Go依赖包

支持配置优先级的依赖包

$ go get github.com/namsral/flag

提取配置

package main

import (
    "encoding/json"
    "fmt"
    "github.com/namsral/flag"
    "net/http"
    "strconv"
)

var version = flag.String("version", "1.0.0", "rpc http server version")
var addr = flag.String("addr", ":8000", "rpc http server address")
var pattern = flag.String("pattern", "/add", "rpc http server route")

func main() {
    // 解析配置
    flag.Parse()
    // http://127.0.0.1:8000/add?a=1&b=2
    http.HandleFunc(*pattern, func(writer http.ResponseWriter, request *http.Request) {
        _ = request.ParseForm() // 解析参数
        fmt.Println("path:", request.URL.Path)
        a, b := 1, 1
        if request.Form["a"] != nil {
            a, _ = strconv.Atoi(request.Form["a"][0])
        }
        if request.Form["b"] != nil {
            b, _ = strconv.Atoi(request.Form["b"][0])
        }

        writer.Header().Set("Content-Type", "application/json")
        jsData, _ := json.Marshal(map[string]any{
            "version": *version,
            "data":    fmt.Sprintf("%d+%d=%d", a, b, a+b),
        })
        _, _ = writer.Write(jsData)
    })

    fmt.Printf("rpc started at: %s, version: %s, pattern: %s\n", *addr, *version, *pattern)
    // 监听服务
    _ = http.ListenAndServe(":8000", nil)
}

查看配置说明

$ go run main.go --help
Usage of /var/folders/fs/p4w_956n2234yqms7jlftsn00000gn/T/go-build3091959094/b001/exe/main:
  -addr=":8000": rpc http server address
  -pattern="/add": rpc http server route
  -version="1.0.0": rpc http server version
exit status 2

测试

默认启动

$ go run main.go                         
rpc started at: :8000, version: 1.0.0, pattern: /add

设置环境变量启动

$ export VERSION=1.0.1
$ export ADDR=:8002

$ go run main.go
rpc started at: :8002, version: 1.0.1, pattern: /add

命令行启动

$ go run main.go --addr=:8003 --version=1.0.3
rpc started at: :8003, version: 1.0.3, pattern: /add

移除环境变量

$ unset VERSION
$ unset ADDR

上传镜像

# 镜像tap
$ docker tag demo-http-server qvbilam/http-server:1.0-alpine3.15

# 提交镜像1.0版本
$ docker commit -a "qvbilam" -m "go http server" qvbilam/http-server:1.0-alpine3.15

# 登陆
$ docker login

# 推送
$ docker push qvbilam/http-server:1.0-alpine3.15

image-20240711140109197

Last modification:July 23rd, 2024 at 03:55 pm