如何使用kubectl补丁更改kubernetes容器的端口?

时间:2019-08-29 09:43:00

标签: docker kubernetes

我想更改在我的kubernetes集群上运行的容器的端口。手动,我知道可以在基础YAML文件本身中进行更改。但是我想使用“ kubectl patch”之类的命令来更改端口。

Nginx.yaml


apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels: 
    app: nginx 
spec:
  type: NodePort     
  ports:
  - name: nginxport
    port: 80
    targetPort: 80
    nodePort: 30000
  selector:
    app: nginx
    tier: frontend    

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
      tier: frontend
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: nginx
        tier: frontend
    spec:

      containers:
      - image: suji165475/devops-sample:#{Build.BuildId}#
        name: nginx
        ports:
        - containerPort: 80
          name: nginxport

任何人都可以使用我的nginx.yaml作为更改容器属性(例如containerport,targetport,nodeport,port)的示例,向我展示“ kubectl patch”命令的示例。我也想知道在什么基础上应用kubectl补丁。我的意思是它如何知道要对哪个容器进行补丁以及以什么标准(例如containerid,name等)知道,因为稍后我将创建一个html按钮来基于进行kubectl补丁一些条件,例如containerid或名称。请提供帮助。

1 个答案:

答案 0 :(得分:2)

例如,您要将服务中的目标端口更新为8080。请按照以下步骤

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels: 
    app: nginx 
spec:
  type: NodePort     
  ports:
  - name: nginxport
    port: 80
    targetPort: 80
    nodePort: 30000
  selector:
    app: nginx
    tier: frontend 

使用以下命令修补nginx服务

# kubectl patch svc nginx --patch \
>   '{"spec": { "type": "NodePort", "ports": [ { "nodePort": 30000, "port": 80, "protocol": "TCP", "targetPort": 8080 } ] } }'
service/nginx patched

to update nodeport and targetport use the below command

kubectl patch svc nginx --patch \
  '{"spec": { "type": "NodePort", "ports": [ { "nodePort": 32000, "port": 80, "protocol": "TCP", "targetPort": 8080 } ] } }'

验证targetPort已更新为8080

master $ kubectl get svc nginx -oyamlapiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2019-08-29T11:08:45Z"
  labels:
    app: nginx
  name: nginx
  namespace: default
  resourceVersion: "5837"
  selfLink: /api/v1/namespaces/default/services/nginx
  uid: 5e7f6165-ca4d-11e9-be03-0242ac110042
spec:
  clusterIP: 10.105.220.186
  externalTrafficPolicy: Cluster
  ports:
  - name: nginxport
    nodePort: 30000
    port: 80
    protocol: TCP
    targetPort: 8080
  selector:
    app: nginx
    tier: frontend
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

遵循类似的部署方式

kubectl patch deploy nginx --patch .....