Running background process with kubectl exec

3/12/2018

I am trying to execute a python program as a background process inside a container with kubectl as below (kubectl issued on local machine):

kubectl exec -it -- bash -c "cd some-dir && (python xxx.py --arg1 abc &)"

When I login to the container and check "ps -ef" I do not see this process running. Also there is no output from kubectl command itself.

Is the kubectl command issued correct?.

Is there a better way to achieve the same?

How can I see the output/logs printed of the background process being run?

If I need to stop this background process after some duration, what is the best way to do this?

Thanks

-- user1650281
background-process
kubernetes
linux
python

2 Answers

3/12/2018

Actually, the best way to make this kind of things is adding an entry point to your container and run execute the commands there. Like:

entrypoint.sh:

#!/bin/bash
set -e

cd some-dir && (python xxx.py --arg1 abc &)
./somethingelse.sh

exec "$@"

You wouldn't need to go manually inside every single container and run the command.

-- Idir Ouhab Meskine
Source: StackOverflow

3/12/2018

The nohup Wikipedia page can help; you need to redirect all three IO streams (stdout, stdin and stderr) - an example with yes:

kubectl exec pod -- bash -c "yes > /dev/null 2> /dev/null &" 

nohup is not required in the above case because I did not allocate a pseudo terminal (no -t flag) and the shell was not interactive (no -i flag) so no HUP signal is sent to the yes process on session termination. See this answer for more details.

Redirecting /dev/null to stdin is not required in the above case since stdin already refers to /dev/null (you can see this by running ls -l /proc/YES_PID/fd in another shell).

To see the output you can instead redirect stdout to a file.

To stop the process you'd need to identity the PID of the process you want to stop (pgrep could be useful for this purpose) and send a fatal signal to it (kill PID for example).

If you want to stop the process after a fixed duration, timeout might be a better option.

-- dippynark
Source: StackOverflow