Kubernetes Trick: Using the watch Command
If you prefer to work with Kubernetes from the command line, you‘ve probably faced this problem. You’ve installed some application in a Kubernetes cluster using kubectl apply or Helm. How do you now follow what’s going on with the installation? Did the application start successfully, or did some Pod fail?
You might just re-run the kubectl get pods command multiple times, but that’s tedious and unsatisfying:
➜ ~ kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 0/1 ContainerCreating 0 31s
my-release-wordpress-ddd8857f6-66bcm 0/1 Running 0 31s
➜ ~ kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 0/1 Running 0 41s
my-release-wordpress-ddd8857f6-66bcm 0/1 Running 0 41s
➜ ~ kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 0/1 Running 0 51s
my-release-wordpress-ddd8857f6-66bcm 0/1 Running 0 51s
➜ ~ kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 0/1 Running 0 62s
my-release-wordpress-ddd8857f6-66bcm 0/1 Running 0 62s
➜ ~ kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 1/1 Running 0 76s
my-release-wordpress-ddd8857f6-66bcm 1/1 Running 0 76s
If this problem is known to you, then here’s how to simplify your life with the watch command.
On Linux, this command is usually present out of the box. On a Mac, you can install the watch command simply by running:
brew install watch
Then, you can use the watch command to execute a command over and over again with a specified interval. The watch command also conveniently displays the output in the same place on the full screen:
- The
-nargument defines the repeat interval in seconds. - The
-dflag highlights the differences between consecutive runs of the specified command. - The
watchcommand and its arguments are immediately followed by the command you actually want to execute.
watch -n 1 -d kubectl get pods
Here’s what the result looks like:
Every 1,0s: kubectl get pods
NAME READY STATUS RESTARTS AGE
my-release-mariadb-0 1/1 Running 0 4m8s
my-release-wordpress-ddd8857f6-66bcm 1/1 Running 0 4m8s
This way, it’s much easier to follow the status of the Kubernetes installation of your application, but that’s not the only place where it’s useful. Once you’re comfortable with the watch command, you’ll start using it everywhere!