Run python script on container from another container on same pod

4/20/2020

I have two containers on same k8 pod, container1, container2

I have python script in container1, How can I run this python script on container2 ?

I mean something like ssh:

ssh user@container2 python < script_on_container1.py 
-- ArmoArmo
kubernetes

3 Answers

4/21/2020

You can use this script; https://gist.github.com/ahmetkotan/b592bf9919cfac7daa2e2e6c2e95772d

python kubernetes_api_exec.py <pod_name> container2 python < script_on_container1.py

or another commands. For example;

python kubernetes_api_exec.py <pod_name> container2 date
python kubernetes_api_exec.py <pod_name> container2 uname -a
-- origamic
Source: StackOverflow

4/20/2020

A workaround for your problem is by doing the following steps:

  1. Create a volume and share it between both containers (con1 and con2) of the pod.
  2. In con1, create a cronjob that runs after <X> mins and read a file that is available on the shared volume.
  3. So whenever con2 makes any changed in that file, con1 will perform any operation specified in the shared file via share volume.

I hope this helps.

-- Irtiza
Source: StackOverflow

4/20/2020

You can't; you need to make a network request from one container to the other.

I would suggest prototyping this first in a local Python virtual environment. In container2, run some lightweight HTTP server like Flask, and when it receives a request, it calls whatever code the script would have run. Once you've demonstrated this working, you can set up the same thing in local Docker containers, and if that works, make these two processes into two separate Kubernetes deployments.

In general with containers you can't "run commands" in other containers. In your proposed solution, containers don't typically run ssh daemons, and maintaining valid login credentials without compromising them is really hard. (If you put an ssh private key into a Docker image, anyone who has the image can trivially extract it. Kubernetes secrets make this a little bit better but not great.) The standard pattern for one container to invoke another is through a network path, generally either a direct HTTP request or through a queueing system like RabbitMQ.

-- David Maze
Source: StackOverflow