I have two dockerized projects: one using NodeJS and the other one using Python
I want to trigger a Python script execution (on the container with the Python app) from the NodeJS app.
Basically the NodeJS app would run something like exec('python3 script.py')
, but it's expected to be run on the Python app container.
How can I achieve this exact behavior? Thanks in advance!
For containers to communicate with other, they need to be part of the same “network”. Docker creates a virtual network called bridge by default, and connects your containers to it. In the network, containers are assigned an IP address, which they can use to address each other.
Running Commands in an Alternate Directory in a Docker Container. To run a command in a certain directory of your container, use the --workdir flag to specify the directory: docker exec --workdir /tmp container-name pwd.
It is possible to grant a container access to docker so that it can spawn other containers on your host. You do this by exposing the docker socket inside the container, e.g: docker run -v /var/run/docker. sock:/var/run/docker.
Docker containers are an implementation of the micro-service architecture. As such, they are expected to be fairly decoupled and communicate between themselves using TCP (HTTP typically). So your python container should expose some REST call (for instance).
There is a way to get around that, but it is not recommended since it opens up your docker daemon to anyone running inside the nodejs container. I'm listing it here since it can be useful during development.
1 - Install the Docker CLI
In your nodejs Dockerfile, add the following lines:
ENV DOCKER_VERSION=18.09.4
RUN curl -sfL -o docker.tgz "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" && \
tar -xzf docker.tgz docker/docker --strip=1 --directory /usr/local/bin && \
rm docker.tgz
This installs only the bare minimum CLI part of the full docker download.
2 - Bind mount the docker socket .
In your compose file, add the following:
services:
mypython:
container_name: mypython
...
mynodejs:
...
volumes:
- /var/run/docker.sock:/var/run/docker.sock
3 - Call your python script .
From inside your nodejs container, you can now use the docker CLI.
# Log into your nodejs container first
docker exec -it mynodejs sh
# and execute some command in another container
docker exec mypython python3 script.py
The above is the easiest way to do it. You can also avoid installing the Docker CLI and use the Docker API directly but it typically requires you to write multiple lines for what Docker CLI does in just one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With