k8s实战五 用service创建前后端应用

官方建议 后端应用 端口不指定, 前端像nginx这种可以指定

1 用deployment创建后端应用

cat hello.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello
spec:
  selector:
    matchLabels:  # 这么多label 。。。
      app: hello
      tier: backend
      track: stable
  replicas: 7  # 7个pod 牛掰
  template:
    metadata:
      labels:
        app: hello
        tier: backend
        track: stable
    spec:
      containers:  # 这个应该是google的案例应用
        - name: hello
          image: "gcr.io/google-samples/hello-go-gke:1.0"
          ports:
            - name: http
              containerPort: 80
kubectl create -f hello.yaml

2 创建后端服务的 service object

cat hello-service.yaml

kind: Service  #service 类型
apiVersion: v1
metadata:
  name: hello
spec:
  selector:
    app: hello
    tier: backend
  ports:
  - protocol: TCP
    port: 80     # service 端口是 80
    targetPort: http

执行创建service

kubectl create -f hello-service.yaml

3 创建前端应用

3.1 前言

注意 前端应用这里使用的 nginx
nginx配置如下

upstream hello {
    server hello;   # 这里hello 就是后端 service 的名字, 自动做了dns  https://kubernetes.io/docs/concepts/services-networking/service/#dns
}

server {
    listen 80;

    location / {
        proxy_pass http://hello;
    }
}

如果 你想用原生的nginx,并且创建pod的时候就把配置文件放进去,请使用configMap

3.2 部署

cat frontend.yaml

apiVersion: v1  
kind: Service  # 前端的service
metadata:
  name: frontend
spec:
  selector:
    app: hello
    tier: frontend
  ports:
  - protocol: "TCP"  # TCP
    port: 80		# service 内 80
    targetPort: 80	# 对外暴露 80
  type: LoadBalancer  # 这个是LoadBalancer的service
---   # 下一段
apiVersion: apps/v1      # 就是个nginx服务
kind: Deployment  		# deployment类型
metadata:
  name: frontend
spec:
  selector:
    matchLabels:
      app: hello
      tier: frontend
      track: stable
  replicas: 1			# 就1个
  template:
    metadata:
      labels:
        app: hello
        tier: frontend
        track: stable
    spec:
      containers:
      - name: nginx
        image: "gcr.io/google-samples/hello-frontend:1.0"
        lifecycle:  # 这是容器的钩子函数  https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/
          preStop:  # 容器停止前
            exec:   # 运行下面命令
              command: ["/usr/sbin/nginx","-s","quit"]

执行构建

kubectl create -frontend.yaml

立即监视前端服务启动状态

 kubectl get service frontend --watch

状态更替

NAME       TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)  AGE
frontend   ClusterIP  10.51.252.116   <pending>     80/TCP   10s


NAME       TYPE        CLUSTER-IP      EXTERNAL-IP        PORT(S)  AGE
frontend   ClusterIP   10.51.252.116   XXX.XXX.XXX.XXX    80/TCP   1m

验证

curl http://<EXTERNAL-IP>

{"message":"Hello"}
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐