Docker Community Forums

Share and learn in the Docker community.

Execute command from a container to another container?

Hi guys,

I have a small question about docker property and hope you can help me.

My question is:

  • Is it possible to execute command from a container to another container?

Example:

It runs two containers with the following names:

  • container_one (based on centos)
  • container_two (based on centos)

I now producing the two containers from the Image centos and let it run in the background:

  • docker run -itd --name container_one centos /bin/bash
  • docker run -itd --name container_two centos /bin/bash

Now I log me in “container_one”

  • docker exec -it container_one /bin/bash

Now I am in the terminal of “container_one” and wants from this terminal, for example, a file create in “container_two”. Is there a way, the command “touch test” of “container_one” made in “container_two” run, so that the file in “container_two” generated.

1 Like

Not really. The usual way for one container to cause another container to do something is with a network request, typically HTTP.

(You can, by publishing the Docker socket into the launching container, but that gives the container unrestricted root-level access over the entire host system, which isn’t something you should do lightly.)

1 Like

Thanks :slight_smile:

I think this can be possible by using “docker in docker” concept.

Run container_two by mounting docker.sock volume use below command.

Ensure that you have started container_two with the following Docker flag
-v “/var/run/docker.sock:/var/run/docker.sock”

and then from container_two you can do all docker commands.

Note - Please provide read,write access to the user for /var/run/docker.sock file on Linux.

1 Like

With docker-compose:

version: '2.1'

services:

  site:
    image: ubuntu
    container_name: test-site
    command: sleep 999999

  dkr:
    image: docker
    privileged: true
    working_dir: "/dkr"
    volumes:
      - ".:/dkr"
      - "/var/run/docker.sock:/var/run/docker.sock"
    command: docker ps -a

Then try:

docker-compose up -d site
docker-compose up dkr

result:

Attaching to tmp_dkr_1
dkr_1   | CONTAINER ID        IMAGE                             COMMAND                  CREATED                  STATUS                   PORTS                     NAMES
dkr_1   | 25e382142b2e        docker                            "docker-entrypoint..."   Less than a second ago   Up Less than a second                              tmp_dkr_1

See this answer on stackoverflow: https://stackoverflow.com/a/63690421/10534470

Use docker ps to see the name of the existing container.
Then use the command docker exec -it /bin/bash to get a bash shell in the container.
Or directly use docker exec -it to execute whatever command you specify in the container.