K8s 1.7更新Deployment时保留镜像版本方法及镜像可选性咨询
Great question! Let’s break this down step by step for your Kubernetes 1.7 setup and the follow-up about newer versions.
Problem 1: Keeping Existing Image Tags When Applying deployment.yml in Kubernetes 1.7
Kubernetes 1.7 does require the spec.template.spec.containers[0].image field to be present in your deployment manifest, and there’s no built-in --ignore-image-change flag for kubectl apply at this version. However, you have two reliable workarounds to update resource limits without resetting your image tag:
Use
kubectl patchto target only resource limits
Instead of applying the full deployment file, usekubectl patchto modify just the resource constraints section. This completely avoids touching the image field. For example:# Update CPU and memory limits (adjust container name and values to match your setup) kubectl patch deployment app \ --patch '{"spec":{"template":{"spec":{"containers":[{"name":"your-container-name","resources":{"limits":{"cpu":"1","memory":"1Gi"}}}]}}}}'This directly edits the resource limits in the cluster’s current deployment state, leaving your existing image tag untouched.
Dynamically inject the current image tag into your manifest before applying
Write a quick script to pull the current image tag from the cluster, replace the${some_image}:latestplaceholder in yourdeployment.yml, then apply the modified file. This ensures you’re using the exact same tag that’s already running, so no image reset occurs:# Fetch the current image from the live deployment CURRENT_IMAGE=$(kubectl get deployment app -o jsonpath='{.spec.template.spec.containers[0].image}') # Replace the placeholder and apply the manifest sed "s|${some_image}:latest|$CURRENT_IMAGE|" deployment.yml | kubectl apply -f -
Problem 2: Optional Image Field in Kubernetes 1.10+
Yes, this is true! The ability to omit the image field in your deployment manifest (and have kubectl apply preserve the existing tag) was introduced in Kubernetes 1.9, and the 1.10 documentation explicitly marks the image field as optional (earlier versions required it).
In Kubernetes 1.9+, you can simply remove the image line from your deployment.yml. When you run kubectl apply -f deployment.yml, Kubernetes will merge your changes (like updated resource limits) into the existing deployment state without overwriting the image tag that’s already running. This is exactly the behavior you’re aiming for—no scripts or patch commands needed, just a simplified manifest.
Note: This only works with kubectl apply (which uses strategic merge patching). If you use kubectl replace, the image field will still be required, as that command replaces the entire resource definition.
内容的提问来源于stack exchange,提问作者benjah1

