<p>Is there a way for the kubectl exec commands to be recorded by history command in the pod?
I want to collect all the commands executed on the container by monitoring history command.</p>
<p>Example:
<code>kubectl exec podname -n namespace -c container -- bash -c &quot;ls&quot;</code> ==&gt; Can this be recorded by history command.</p>

<p>A couple of things to clarify in order to get the full context of this behavior:</p>
<p>First, <code>kubectl exec</code> is a neat <a href="https://itnext.io/how-it-works-kubectl-exec-e31325daa910" rel="nofollow noreferrer">API-based</a> (<em>Warning: Medium member's story</em>) wrapper for <a href="https://docs.docker.com/engine/reference/commandline/exec/" rel="nofollow noreferrer"><code>docker exec</code></a>.</p>
<p>This is essential as it means that it'll use the Kubernetes API to relay your commands to Docker. This implies that whatever behavior, shell-related in this case, is directly linked to how Docker implemented the command execution within containers, and has not much to do with kubectl.</p>
<p>The second thing to have in mind is the command itself: <code>history</code>, which is an shell feature and not a separate binary.</p>
<p>The implementation depends on the shell used, but generally it caches the command history in memory before writing it to the  history file after the session is closed. This action can be &quot;forced&quot; using <a href="http://www.gnu.org/software/bash/manual/bash.html#Bash-History-Builtins" rel="nofollow noreferrer"><code>history</code> features</a> but can vary depending on the shell implementation and might not be an uniform, reliable approach while working with the <code>docker exec</code> command.</p>
<p>Considering these things and that your request seems to be aiming to monitor actions performed in your containers, maybe a better approach would be to use <a href="https://github.com/linux-audit/audit-documentation/wiki" rel="nofollow noreferrer">Linux audit</a> to <a href="https://serverfault.com/a/336234/504596">record commands executed by users</a>.</p>
<p>Not only this doesn't rely on the aforementioned points, it <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security_guide/sec-understanding_audit_log_files" rel="nofollow noreferrer">writes logs to a file</a> and this allows you to use your <a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/" rel="nofollow noreferrer">Kubernetes logging strategy</a> to pick them, exporting them to whatever you're using as log sink, facilitating posterior inspection.</p>
