如何在Kubernetes中执行类似`docker run -ti --rm alpine ls /`的命令?
--rm behavior in kubectl? Great question! In Kubernetes, the equivalent of Docker's --rm flag (which automatically deletes a container after it finishes executing its command) is creating a temporary, one-off Pod that gets cleaned up automatically once its task completes. Here's exactly how to replicate that workflow:
Basic One-Off Command (Matching Your Example)
To mirror your Docker command docker run -ti --rm alpine ls /, use this kubectl command:
kubectl run temp-alpine --image=alpine --restart=Never --rm --command -- ls /
Let's break down the key parameters that make this work like Docker's --rm:
--restart=Never: Tells Kubernetes this is a one-time task—don't restart the Pod once it finishes successfully (or fails). This is critical to avoid the Pod lingering in a restart loop.--rm: This directly maps to Docker's--rmflag. It instructs Kubernetes to delete the Pod resource immediately after it terminates, whether the command succeeded or failed.--command --: Separates kubectl's own arguments from the command you want to run inside the container. Everything after the second--is passed directly to the container, just like in Docker.temp-alpine: An arbitrary name for your temporary Pod (you can change this to anything you want).
Interactive Session Example
If you want an interactive terminal (like using Docker's -ti flags), add the -it parameters to attach to the container's stdin/stdout:
kubectl run temp-alpine --image=alpine --restart=Never --rm -it --command -- sh
When you exit the shell session, the Pod will be automatically deleted right away.
Handling Commands with Arguments
If your command requires additional arguments (e.g., ls -l /), just append them after the command:
kubectl run temp-alpine --image=alpine --restart=Never --rm --command -- ls -l /
内容的提问来源于stack exchange,提问作者Bill

