lqshow / notes

Cheat Sheet
10 stars 2 forks source link

k8s 使用 Pod 来部署应用 #38

Open lqshow opened 5 years ago

lqshow commented 5 years ago

Pod 是 k8s 进行资源调度的最小部署单位,里面包含了很多的 container,实际上每一个 container 对应一个应用实例。我们先来看下如何通过 k8s 来部署一个 container。

1. 创建 Pod

Pod 的 yaml 定义如下

apiVersion: v1
kind: Pod

metadata:
  name: nginx-po
  labels:
    app: nginx

spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80

执行命令生成 Pod

kubectl create -f nginx-pod.yml

看下 Pod 的信息

➜  kubectl get po -o wide -l app=nginx
NAME       READY     STATUS    RESTARTS   AGE       IP          NODE
nginx-po   1/1       Running   0          5m        10.1.0.69   docker-for-desktop

验证下 pod 内的容器是否正常运行

# 使用 kubectl 端口转发
➜  kubectl port-forward nginx-po 3000:80
Forwarding from 127.0.0.1:3000 -> 80
Forwarding from [::1]:3000 -> 80
# kubectl port-forward 将 localhost:3000的请求转发到 nginx-pod Pod 的80端口
➜  curl localhost:3000
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    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>

验证 pod 与 pod 间的通信

kubectl run busybox-curl --rm -ti --image=lqshow/busybox-curl curl $(kubectl get pod nginx-po -o go-template='{{.status.podIP}}')

2. 创建 Service

以上 pod 定义的 yaml 是不能直接访问 pod 内的网络的,访问 Pod 需要通过 Service 来实现。

我们知道每个 Pod 都有一个自己的 IP 地址,当 Pod 发生故障后,新的 Pod 会分配到一个新的 IP 地址。Service 是通过 label 来维护 Pod 的映射关系,完全不需要关心 Pod的 IP 地址,正如下面Service spec的定义,通过 selector 来筛选 Pod

Service 的 yaml 定义如下

apiVersion: v1
kind: Service

metadata:
  name: nginx-svc
  labels:
    app: nginx

spec:
  ports:
  - port: 3000
    name: http
    targetPort: 80
    protocol: TCP

  selector:
    app: nginx

  type: NodePort

执行命令生成 Service

kubectl create -f nginx-svc.yml

看下 Service 的信息

➜  kubectl get svc -o wide -l app=nginx
NAME        TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE       SELECTOR
nginx-svc   NodePort   10.101.115.134   <none>        3000:31876/TCP   29s       app=nginx

通过访问localhsot 的31876端口能看到 nginx 的页面

image

Service Port的说明

Port Desc
port service暴露在cluster ip上的端口(3000)
targetPort pod上的容器端口(80)
nodePort 节点端口(31876)

port 和 nodePort 都是 Service 上的端口

port 暴露给集群内客户访问服务(cluster Ip:port)

nodePort 暴露给集群外客户访问服务(node Ip:nodePort)

从这两个端口到来的数据都需要经过反向代理 kube-proxy 流入后端 pod 的 targetPod,从而到达 pod 上的容器内。