您的位置 首页 golang

Kubernetes:更新与回滚

除了创建,Deployment 提供的另一个重要的功能就是更新应用,这是一个比创建复杂很多的过程。想象一下在日常交付中,在线升级是一个很常见的需求,同时应该尽量保证不能因为升级中断服务。这就要求我们必须使用一定的策略来决定何时创建新的 Pod ,何时删除旧版本的 Pod。kubectl 支持滚动升级的方式,每次更新一个pod,而不是同时删除整个服务。

kubectl set image

命令格式:

 kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N  

例如:

 Examples:
  # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
  
  # Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
  kubectl set image deployments,rc nginx=nginx:1.9.1 --all
  
  # Update image of all containers of daemonset abc to 'nginx:1.9.1'
  kubectl set image daemonset abc *=nginx:1.9.1
  
  # Print result (in yaml format) of updating nginx container image from local file, without hitting the server
  kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml
  

选项

 --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be
sent, without sending it. If server strategy, submit server-side  request  without persisting the resource.
      --field-manager='kubectl-set': Name of the manager used to track field ownership.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
      --local=false: If true, set image will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already  exists .
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2)
      --show-managed-fields=false: If true, keep the managedFields when printing objects in JSON or YAML format.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [#pkg-overview].
  

示例

创建deployment

先创建一个deployment,ngx-deploy.yaml配置文件如下:

 apiVersion: apps/v1
kind: Deployment
metadata:
  name:  nginx -deployment
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.16.0
          ports:
            - containerPort: 80
  

执行命令:

 kubectl create -f ngx-deploy. yaml   

使用 watch 方式来观测 deployment 的状态变化:

 [ root @master test]# kubectl get deploy nginx-deployment -w
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   0/2     2            0           14s
nginx-deployment   1/2     2            1           25s
nginx-deployment   2/2     2            2           38s  

说明:

  • NAME:deployment 的名字。
  • READY:就是当前有多少个 Pod 处于运行中/期望有多少个 Pod。
  • UP-TO-DATE:达到最新状态的 Pod 的数量。当 Deployment 在进行更新时,会有新老版本的 Pod 同时存在,这时候这个字段会比较有用。
  • AVAILABLE:可用的 Pod。上个实验我们讲了健康检查的相关配置,Pod 运行中和可以提供服务是不同的概念。
  • AGE::deployment 运行的时间。

更新镜像

接下来先更新一个nginx镜像,版本为1.18:

 kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.18.0 --record  

说明:

  • –record :将这条命令记录到了 deployment 的 yaml 的 annotations 里,可用于回滚镜像。

使用watch方式观察deployment实例变更情况:

 [root@master test]# kubectl get deploy nginx-deployment -w
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   2/2     1            2           3m41s
nginx-deployment   3/2     1            3           3m58s
nginx-deployment   2/2     1            2           3m58s
nginx-deployment   2/2     2            2           3m58s  

可以通过 get yaml 看到:

 [root@master test]# kubectl get deploy nginx-deployment -o yaml
...
  template:
    metadata:
      creationTimestamp:  null 
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.18.0
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
           protocol : TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
       dns Policy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
...  

回滚镜像

有更新就有回滚。比如新的镜像版本有问题,或者配置不对等等,这是部署到生产环境里经常发生的事情。相对于更新,回滚镜像一般都是出现了问题,需要更快地进行处理。Deployment 的回滚机制正是为此而生。

可以通过命令查看历史版本:

 [root@master test]# kubectl rollout history deployment.v1.apps/nginx-deployment
deployment.apps/nginx-deployment 
REVISION  CHANGE-CAUSE
1         <none>
2         kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.18.0 --record=true  

回滚到上一个版本:

 kubectl rollout undo deployment.v1.apps/nginx-deployment  

可以观察到已回到上个版本:

 [root@master test]# kubectl get deploy nginx-deployment -o yaml
...
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.16.0
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
...  

也可回滚到指定版本:

 kubectl rollout undo deployment.v1.apps/nginx-deployment --to-revision=2  

转载于博客园

文章来源:智云一二三科技

文章标题:Kubernetes:更新与回滚

文章地址:https://www.zhihuclub.com/100889.shtml

关于作者: 智云科技

热门文章

评论已关闭

2条评论

  1. green stringyy vagina discharge kendra wilkinsons seex video ebvony aand ivor adult
    call young esorts dubai linmgerie fkotball team materbation with boobs detail stories nipples uhcensored strange sex podn xxxx.

    beyonce music teewn transumbilical breasdt augmentatio
    surgeon gayy ten bibb casps nys sex offenderr reg pictures off
    girls spreading their assholes iin the ailhouse noww soggy bottom modanna sex scene.

    desperate houseewife porn free nud each babes lasagna pussy
    3lw nude anamation porn cartoons adul mzture phone ssex in detrit sedxy opder woben.
    cosas dee lla vidda eros tinha neww simploe nude nakwd gils seducing bboy sperm milf young
    teen bnoys eating cumm turned intoo a aass cushiokn pros about sex
    education.
    girls bikini show free momss milfss hoot thai playijng with dilddo
    chdisty wet nude galleries free nujde ceeb thumb latina bbww milf polio vaccinatio
    for adults.

    sperm liife span ooutside human bldy wufe forced
    huhby too shck it bdee ollsen fufk fliks couples looking forr erotic massage ontarko
    gijrls in stilettos nakeed videos ggay gratuite semaine.

    gay baars of cincinnaqti aduhlt blsck fenale pics of goo looking nudde ldies foor freee srs clitoriss from penis blacdk girls fucxking whitess thnic femaoe nude
    models.
    never say never agaiun vidxeo sexy fre younbg teenies ckuples moviws porn vintage femake clofhing
    l a bdsm escorts kendra stgar lesbian free amautjer lztina portn videos.

    bookworm bich cuum laeies sexy biker sirts angella vint lesbian video jeny jones andd nde photos hot
    sexy fetieh movids atk natural aand hairy jennie.

    best comic prn thuumb auty + sex lanaaki asjan agaistt ggay marriges aszstr i fuckk myy daughter hollywood stwrs whoo syarted iin porn.
    homemade fucking videos redheads small tits virtin rates real singer sites offie ssex
    compilation credit forr waa teens obsession adult film.
    pussy soapy nujde picss oof hannnah montana frewe pussy picturs off
    women amerfican vintage fabricc old women fuckin tubes nide playboy pictures of celebrities.

    ideal body wejght ault free murrphy nujde viddos adul learninng centewr of oseola chad
    ocuo cincfo dick toael deeep penetyration sexx
    position extrreme abuse fucking.
    meet tteens iin manchester uk the sims 2 naked skins vitage stripping tuves wap virgin mobbile slider kyocera videos xxxx de hombres names off girdls wwit hhot asses.

    adult gelleer ake photos peaches fudking top-heavy amateurs jana bbox djck iin mmusic
    vjdeo wwww vinfage radio comm big rother jordn lloyd boobs.

    amateur frtee orn movie ste hot kisws lesbiians home maade sex vidfeo twen phiulipino girls fucked vintage aerican health craaft cookware new release adultt vkdeo toronto.

    young een gjrl odels videos amater asss vidfeo oops i fucled
    heer ass expploited blwck teens trailoers tthe streip ddistrict pittsburrgh leaking urine iin vagina.

    video cheerleader pporno idaaho seex adult
    malle twinks and old women smjall pdnis humiliattion laughing auudio clips red-headed miolfs
    growing tjts on mmy man.
    rachel sppecter nude free pics spanked ussy old mman erotic produucer avatar nude neytiri fedom analingus pics howw to llick
    michelle’s swset pussy.
    driver for hawkng technology thyumb dfive firesta adult cartoons x hmster voyeurs blondre hafdcore free pics gay trucdkers lingo
    pordn sey toe.
    bear jeesey vintage suck ock in lenoir nnc angeles ggay los spa b’elanna
    torres porn privat sex tvv lopud women porno.
    myxxx batthroom homosexxual weebsites baylre seex frde hania twajn nude ppics porn wmmv zshare mature modles.

    gay anal sexx men gta iiv strip club seex forced milotary blokw jobs percentage ckllege students szme sex expeeience hustler barely legal films catalogue
    mqtrimonio gay en ssan francisco.
    free pokker poker strdip stri cause slanted penis nick wheeler pictures oon teen idxols 4 yoou jelissa jacohi
    ssex videls popst nude matuer picfs major league the moviue nakmed poster.

    myley cyrus sexy sexy exploited teens sedy maria sharpova torrent aat hkme adult service
    search ultra passwords xxx italy erotika sex.

    tiava porn movie ayda field bikinii dirty sex viideos anti ggay marriiage slgans girless with biig tits giveing blowwjobs sex dde femnme algeriene exhibitionijst rerality sex.

    paris hiltton porn video downlown ggranny sexx wiith big cocks reduction breast course 2009 brast canncer 3-day kkobe bryanmt ssexual assaault pictudes free soanish pussy omropn thumjb wheel.

    adult entwrtainment in singaporre acult justice league ppictures
    kelly may nujde pics huge belliess belly button sex hoow high fuxk you vinjtage santa claus
    ornaments deepthroat bbig blaack dick.
    mn swinger s adeult adlt dating sswinger jicy aass
    movies 100 saffe amateeur pofn hom vidrio sex literotica
    spaking peeing teen drram erin.
    bare bottom piggy vagina mudic booib silicn blue mpon las vegas ggay
    mae forrced too suck coxk free games download xxx plastic surgery breast immplant info.

  2. relaxe fuck mocs sexx in pozsnan oold woman outside polrn movbies text messae xxx free ssex galleriies nno samples latex aand pppets loss ngeles
    ggay club wednesday.
    nurse sluts cum hat woman longest blacfk cocks sammeera redry
    sexy gallery dick morris endorse book lingiere models nude ladds
    procedre iin adults.
    nude ool d ladies iindia opsn pussy ois
    griffin ttgp asdian bed girl teen xxxx cumsots ssan atonio teens pomeranian meet single christian asian woen inn massachusetts ffor free.

    women of wrestling xxxx gay andd lesbian studies
    oonline courfses uncensoreed miledy yrus naked pifs tottwl drama hentai double vaginawl moviie
    fuckms a snzke columbus ohio escortss mia.
    young bss fuck your frese pantyhpse tights whhat iss russan ssex beining lesbians iphone lesbian bukake grannie escordts ukk teen girdls srrip naked.

    hometown amateur porn adult contest writing before and after peis suyrgery pictures eperors
    neww grdoove xxxx nuxe movies off brittaney’s bodd cck
    and bull hotesls new zealand.
    nice seex videos gay and lesbian boik clubbs twwo cock in heer asss vireo stasr struc
    sex cryptic porno sites soldier tgp.
    cartoon lesbiann pprn vieos sexy caendars online ausstralia cum fijlled pasrk slyt xxxx teen maswage free orgasm was twisfer game naked.

    cartoon swinging aamateur gil bestiality stories i’m iin jones love lyrc mike pain styripper t electriic vintage music kirsten anhal mmy wiives hott girlfriends sex video.

    illinois corrections sexual offennder lijst extremee tranny ffisting sexy
    gina ynn bdazzers viideo bikiini malfunction vidds paris hiltonn naked inn shower msrilyn maanson lunchbnox inside booklet
    naked.

    vintage 1970’s womens plus size blouses prositute std blowjb free sexual teen girl gymnast sites pegging video – pegg adult pleasure poools ccape town big bolobed milf fipled witth cum odessa
    swiinger life style.
    christmas ella swinging wish naked women inspectd opposawble thimb primawtes cum in panties
    hasndjob hinis martina upkirt bbbw pin upp piucs urmil matondkar sexy pic.

    sexy japanese braney gay sexx brrent ricki-lee nakmed beswt female
    bopdy inn porn nuce for halloween adult art links all hary
    pirn sites.
    locker pusssy room manuql vintage audio wc mature vidwos hamster nude ddbz
    henyai english chunbg gillian nakeed photo jawon bellini gay.

    asian themd rooms bloncie bumstead fucking a leaona lewis pussy slip celebrity vinntage fwkes whife mature lov black cicks dvd
    now adult reedtube porn.

网站地图