# run commands in a pod (or multiple pods)

If you want to inspect files inside a pod or run arbitrary commands inside of them, you can use `kubectl exec` to do so. Add the `-ti` option if you want to connect intereactively.

* Use **/bin/sh** instead of **/bin/bash**

## List pods and containers

1. If there are multiple containers in the pod you want to inspect, you should **specify the container name**
2. List of containers in a single pod:
    
    ```bash
    $ kubectl get po -n poc basic-tidb-0 -o json |   
        jq -r '.spec.containers\[\] | .name'  
    slowlog  
    tidb
    ```
    
3. List of all containers in all pods:
    
    ```bash
    $ kubectl get pods --all-namespaces -o go-template \\  
        --template='{{range .items -}}  
    {{- printf "%s\\t%s\\n" .metadata.namespace .[metadata.name](http://metadata.name/) }}{{range .spec.containers -}}  
    {{- printf "\\t%s\\n" .name}}{{end}}{{end}}'  
    kube-system coredns-66bff467f8-qv2mn  
        coredns  
    kube-system coredns-66bff467f8-vvmrc  
        coredns  
    kube-system etcd-kind-control-plane  
        etcd  
    kube-system kindnet-x8cp5  
        kindnet-cni  
    kube-system kube-apiserver-kind-control-plane  
        kube-apiserver  
    kube-system kube-controller-manager-kind-control-plane  
        kube-controller-manager  
    kube-system kube-proxy-7gfpx  
        kube-proxy  
    kube-system kube-scheduler-kind-control-plane  
        kube-scheduler  
    local-path-storage local-path-provisioner-bd4bb6b75-m2524  
        local-path-provisioner  
    pingcap tidb-controller-manager-54cfcbff7b-bmq8q  
        tidb-operator  
    pingcap tidb-scheduler-6799885d99-dtgx2  
        tidb-scheduler  
        kube-scheduler  
    poc basic-discovery-59c77754b4-dzjpm  
        discovery  
    poc basic-monitor-789d8f494c-r2nw5  
        prometheus  
        reloader  
        grafana  
    poc basic-pd-0  
        pd  
    poc basic-tidb-0  
        slowlog  
        tidb  
    poc basic-tikv-0  
        tikv
    ```
    
### Get a shell or execute a command in the pod

1. Use **\-ti** to get a tty and connect to stdin for interactive use
2. Separate your command and its options from `kubectl exec` with two dashes (`--`)  
    
    ```bash
    $ kubectl exec -n poc -ti basic-pd-0 -- /bin/sh
    / #
    ```
    
3. Inspect files or execute commands as needed  
    
    ```bash
    $ kubectl exec -n poc -ti basic-tidb-0 -c tidb -- /bin/sh  
    / # find / -name '\*.toml'  
    /etc/tidb/..2020\_08\_18\_21\_39\_00.741388802/tidb.toml  
    /etc/tidb/tidb.toml  
    / # cat /etc/tidb/tidb.toml  
    \[log\]  
    \[log.file\]  
    max-backups = 3
    ```  
      
### Execute command in multiple pods

If you want to execute a command in multiple pods, you can use a simple shell loop.

```bash
kubectl get po -n tidb -l app.kubernetes.io/component=tidb -o NAME |  
  while read -r pod; do   
    kubectl exec -n tidb -c tidb "$pod" -- /tidb-server -V  
  done
```
