I have two docker containers, A and B, that are spun up with docker-compose files. I want to be able to bring the container B down with the command `docker-compose -f docker-compose.B.yaml down’ from within container A.
Is this possible?
I tried to mount container B’s docker compose file and /var/run/docker.sock
. But when I run the command using a sub process in python (again from within container A), I get a ‘no resource found error’.
docker:
services:
Service A:
image: imageA:rel_1.0.0
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /path/to/docker-compose.B.yaml:/projectA/docker-compose.B.yaml
.
.
.
python:
#docker-compose.py
import subprocess
compose_file_path = '/projectA_directory/docker-compose.B.yaml'
command = f"docker-compose -f {compose_file_path} down"
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
logger.info(f"Command output: {result.stdout}")
logger.error(f"Command error: {result.stderr}")
Error:
ContainerA | ERROR | 2024-07-29T19:56:51-0600 | docker-compose.py:62 | Command error: Warning: No resource found to remove for project "projectA".
2
Answers
Docker compose assigns a "project name" to your containers, which by default is based on the name of the directory that contains your
compose.yaml
file. That is, if have:And
compose.yaml
looks like this:Then when I run
docker compose up
from within themyproject
directory:I end up with the following containers:
Each of those containers has some labels assigned to it:
The
com.docker.compose.project
label is how docker compose identifies containers that belong to your current project. If you rename a directory, like this:Then compose will have the wrong project name, and it won’t be able to interact with those containers:
We can set an explicit project name using the
--project-name
(-p
) command line option:Or by setting the
COMPOSE_PROJECT_NAME
environment variable:In your question, it looks like you are mounting your compose project under a different directory name in the container than you are using on the host. You can solve this by either:
--project-name
argument to docker compose, orCOMPOSE_PROJECT_NAME
environment variableIt’s possible.
call.sh
file to the same directory as docker-compose.yml.change
192.168.0.101
to your host ip address.2. Modify your docker-compose files
/projectA/call.sh docker stop containerB_name
in your python code.