Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubectl attach vs kubectl exec?

Tags:

kubernetes

by using kubectl exec -ti POD_NAME bash I am able to access the terminal inside the container and execute the command.

I can understand the usability and convenient of the above command. As K8s Operator I use exec regularly.

However, What is the use case of kubectl attach POD_NAME?

How can it be utilised? What is the real purpose of it? In what situation or circumstance it can be used?

like image 922
Suresh Vishnoi Avatar asked Apr 25 '18 19:04

Suresh Vishnoi


People also ask

What is kubectl exec?

The kubectl exec command lets you start a shell session inside containers running in your Kubernetes cluster. This command lets you inspect the container's file system, check the state of the environment, and perform advanced debugging tools when logs alone don't provide enough information.

What does kubectl attach do?

The kubectl attach command is similar to kubectl exec , but it attaches to the main process running in the container instead of running an additional one.

How does kubectl exec works?

The kubectl exec command is an invaluable tool for those of us who regularly work with containerized workloads on Kubernetes. It allows us to inspect and debug our applications, by executing commands inside our containers. The first exec command runs a date command inside my Nginx container.

Is kubectl exec ssh?

kubectl exec is just a small part of this and is used for debugging when things go wrong. However, if you step back and squint, kubectl exec serves the same purpose as ssh .


Video Answer


2 Answers

The use cases for kubectl attach are discussed in kubernetes/issue 23335.

It can attach to the main process run by the container, which is not always bash.
As opposed to exec, which allows you to execute any process within the container (often: bash)

# Get output from running pod 123456-7890, using the first container by default kubectl attach 123456-7890  # Get output from ruby-container from pod 123456-7890 kubectl attach 123456-7890 -c ruby-container 

This article proposes:

In addition to interactive execution of commands, you can now also attach to any running process. Like kubectl logs, you’ll get stderr and stdout data, but with attach, you’ll also be able to send stdin from your terminal to the program.
Awesome for interactive debugging, or even just sending ctrl-c to a misbehaving application.

  $> kubectl attach redis -i 

Again, the main difference is in the process you interact with in the container:

  • exec: any one you want to create
  • attach: the one currently running (no choice)
like image 53
VonC Avatar answered Sep 18 '22 14:09

VonC


The kubectl attach command is similar to kubectl exec, but it attaches to the main process running in the container instead of running an additional one.

like image 41
Gupta Avatar answered Sep 19 '22 14:09

Gupta