问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/55317195/run-command-from-one-container-to-another