kubernetes kubectl是否与映像一起运行会创建部署Yaml文件

时间:2019-12-24 15:09:30

标签: docker kubernetes kubectl

我正在尝试使用Minikube和Docker来理解Kubernetes架构的概念。

我用Dockerfile创建了一个Spring Boot应用程序,创建了标签并推送到Dockerhub。

为了在K8s集群中部署映像,我发出了以下命令,

# deployed the image
$ kubectl run <deployment-name> --image=<username/imagename>:<version> --port=<port the app runs>

# exposed the port as nodeport
$ kubectl expose deployment <deployment-name> --type=NodePort

一切正常,我能够看到正在运行kubectl get pods的1个吊舱

我推送到Dockerhub的Docker映像没有任何部署YAML文件。

以下命令产生了Yaml输出

kubectl命令是否可以直接创建部署Yaml文件?

 $ kubectl get deployments --output yaml 
apiVersion: v1
items:
- apiVersion: apps/v1
  kind: Deployment
  metadata:
    annotations:
      deployment.kubernetes.io/revision: "1"
    creationTimestamp: "2019-12-24T14:59:14Z"
    generation: 1
    labels:
      run: hello-service
    name: hello-service
    namespace: default
    resourceVersion: "76195"
    selfLink: /apis/apps/v1/namespaces/default/deployments/hello-service
    uid: 90950172-1c0b-4b9f-a339-b47569366f4e
  spec:
    progressDeadlineSeconds: 600
    replicas: 1
    revisionHistoryLimit: 10
    selector:
      matchLabels:
        run: hello-service
    strategy:
      rollingUpdate:
        maxSurge: 25%
        maxUnavailable: 25%
      type: RollingUpdate
    template:
      metadata:
        creationTimestamp: null
        labels:
          run: hello-service
      spec:
        containers:
        - image: thirumurthi/hello-service:0.0.1
          imagePullPolicy: IfNotPresent
          name: hello-service
          ports:
          - containerPort: 8800
            protocol: TCP
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
        dnsPolicy: ClusterFirst
        restartPolicy: Always
        schedulerName: default-scheduler
        securityContext: {}
        terminationGracePeriodSeconds: 30
  status:
    availableReplicas: 1
    conditions:
    - lastTransitionTime: "2019-12-24T14:59:19Z"
      lastUpdateTime: "2019-12-24T14:59:19Z"
      message: Deployment has minimum availability.
      reason: MinimumReplicasAvailable
      status: "True"
      type: Available
    - lastTransitionTime: "2019-12-24T14:59:14Z"
      lastUpdateTime: "2019-12-24T14:59:19Z"
      message: ReplicaSet "hello-service-75d67cc857" has successfully progressed.
      reason: NewReplicaSetAvailable
      status: "True"
      type: Progressing
    observedGeneration: 1
    readyReplicas: 1
    replicas: 1
    updatedReplicas: 1
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

2 个答案:

答案 0 :(得分:1)

是的,kubectl run创建一个部署。如果您查看标签字段,则可以看到run: hello-service。该标签稍后将在选择器中使用。

答案 1 :(得分:1)

我认为使用命令性命令创建kubernetes资源时,了解幕后情况的最简单方法(与编写和应用yaml定义文件的声明性方法相比)是运行带有2个其他标志的简单示例:

import aiohttp
import asyncio
import async_timeout
import feedparser

import pprint

INTERVAL = 60

async def fetch(session, url):
    with async_timeout.timeout(10):
        async with session.get(url) as response:
            return await response.text()

async def fetchfeeds(loop, feedurls, ircsock):
    last_entry = None

    feeds = []

    for url in feedurls:
        feeds.append({'url':url, 'last':""})

    while True:
        for feed in feeds:
            async with aiohttp.ClientSession(loop=loop) as session:
                html = await fetch(session, feed['url'])
                rss = feedparser.parse(html)
                if feed['last']:
                    if feed['last']['title'] != rss['entries'][0]['title'] and feed['last']['link'] != rss['entries'][0]['link']:
                        print("new entry")
                        feed['last'] = rss['entries'][0]

                        print("MSG {}".format(feed['last']['title']))
                        print("MSG {}".format(feed['last']['link']))
                else:
                    feed['last'] = rss['entries'][0]

        await asyncio.sleep(INTERVAL)

loop = asyncio.get_event_loop()
loop.run_until_complete(fetchfeeds(loop, ['https://n-o-d-e.net/rss/rss.xml',
    "http://localhost:8000/rss.xml"], None))

btn.addEventListener("click", function(e){
    cell.getColumn().hide();
});

这些标志的名称是不言自明的,因此我认为不再需要评论来解释它们的作用。您只需尝试以下示例,就会看到效果:

--dry-run

如您所见,它会生成适当的yaml清单,而不应用它并创建实际的部署:

--output yaml

kubectl run nginx-example --image=nginx:latest --port=80 --dry-run --output yaml 命令相同:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    run: nginx-example
  name: nginx-example
spec:
  replicas: 1
  selector:
    matchLabels:
      run: nginx-example
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx-example
    spec:
      containers:
      - image: nginx:latest
        name: nginx-example
        ports:
        - containerPort: 80
        resources: {}
status: {}

产生以下输出:

expose

现在是最酷的部分。您可以使用简单的输出重定向:

kubectl expose deployment nginx-example --type=NodePort --dry-run --output yaml

保存生成的apiVersion: v1 kind: Service metadata: creationTimestamp: null labels: run: nginx-example name: nginx-example spec: ports: - port: 80 protocol: TCP targetPort: 80 selector: run: nginx-example type: NodePort status: loadBalancer: {} kubectl run nginx-example --image=nginx:latest --port=80 --dry-run --output yaml > nginx-example-deployment.yaml kubectl expose deployment nginx-example --type=NodePort --dry-run --output yaml > nginx-example-nodeport-service.yaml 定义,以便您可以根据需要进一步修改它们,并使用DeploymentNodePort Service进行应用。

顺便说一句。 kubectl apply -f filename.yamlkubectl create -f filename.yaml是基于生成器的命令,正如您在创建部署时可能会注意到的(您可能会收到消息:kubectl run),它们使用kubectl expose标志。如果未明确指定,它将获取kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.的默认值--generator,因此默认情况下会创建一个kubectl run。但是您可以通过提供--generator=deployment/apps.v1beta1来进行修改,而不是Deployment会创建一个--generator=run-pod/v1 nginx-example。回到上一个示例时,它看起来可能像这样:

Deployment

我希望它回答了您的问题,并澄清了使用命令式命令创建kubernetes资源的机制。