一、Kubernetes支持YAML和JSON格式创建资源对象

  • JSON格式用于接口之间消息的传递
  • YAML格式用于配置和管理
  • YAML是一种简洁的非标记性语言
  • 语法格式:
    缩进标识层级关系
    不支持制表符缩进,使用空格缩进
    通常开头缩进两个空格
    字符后缩进一个空格,如冒号,逗号,短横杆等
    “—”表示YAML格式,一个文件的开始
    “#”表示注释
[root@localhost ~]# mkdir demo
[root@localhost ~]# cd demo/
[root@localhost demo]# vim nginx-deployment.yaml
apiVersion: apps/v1
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
       image: nginx:1.15.4
       ports:
       - containerPort: 80

[root@localhost demo]# kubectl create -f nginx-deployment.yaml 

[root@localhost demo]# kubectl get pods
发布资源使得资源能够被外界所能访问:
[root@localhost demo]# vim nginx-service.yaml
apiVersion: v1  
kind: Service  
metadata:
  name: nginx-service
  labels:
    app: nginx  
spec:
  type: NodePort  
  ports:
  - port: 80
   targetPort: 80  
  selector:
    app: nginx

[root@localhost demo]# kubectl create -f nginx-service.yaml 
service/nginx-service created
[root@localhost demo]# kubectl get svc
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        13d
nginx-service   NodePort    10.0.0.225   <none>        80:47722/TCP   23s

二、k8s里面的端口问题详解:

在这里插入图片描述

  • port
    port是k8s集群内部访问service的端口,即通过clusterIP: port可以访问到某个service
  • nodePort
    nodePort是外部访问k8s集群中service的端口,通过nodeIP: nodePort可以从外部访问到某个service。
  • targetPort
    targetPort是pod的端口,从port和nodePort来的流量经过kube-proxy流入到后端pod的targetPort上,最后进入容器。
  • containerPort
    containerPort是pod内部容器的端口,targetPort映射到containerPort。

三、生成yaml、json文件的方法:

//自动测试命令的正确性,并不执行创建
[root@localhost demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-deployment created (dry run)

//查看生成yaml格式
[root@localhost demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o yaml

//查看生成json格式
[root@localhost demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o json
[root@localhost demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o yaml > my-deployment.yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
[root@localhost demo]# ls
my-deployment.yaml  nginx-deployment.yaml  nginx-service.yaml
//将现有的资源生成模板导出
[root@localhost demo]# kubectl get deploy/nginx --export -o yaml

//保存到文件中
[root@localhost demo]# kubectl get deploy/nginx --export -o yaml > my-deploy.yaml
//查看字段帮助信息
[root@localhost demo]# kubectl explain pods.spec.containers
Logo

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

更多推荐