Execute command in linked docker container

2019-01-25 05:31发布

问题:

Is there any way posible to exec command from inside one docker container in the linked docker container? I don't want to exec command from the host.

回答1:

As long as you have access to something like the docker socket within your container, you can run any command inside any docker container, doesn't matter whether or not it is linked. For example:

# run a container and link it to `other`
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock \
           --link other:other myimage bash -l
bash$ docker exec --it other echo hello

This works even if the link was not specified.



回答2:

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

Example Project

https://github.com/reduardo7/docker-container-access



标签: docker