fedemengo
fedemengo

Reputation: 696

Create docker container from within a container

I have docker on my host machine with a container running. I was wondering if it's possible, and what the best approach would be, to "trigger" a container creation from the running container.

Let's say my machine is host and I have a container called app (with id 123456789) running on host.

root@host $ docker contain ls
123456789    app_mage    ....    app

I would like to create a container on host from within app

root@123456789 $ docker run --name app2 ...
root@host docker container ls
123456789    app_mage    ....    app
12345678A    app_mage    ....    app2

What I need is for my app to be running on docker and to run arbitrary applications in an isolated environment (but I'd rather avoid docker-in-docker)

Upvotes: 5

Views: 3190

Answers (1)

Baily
Baily

Reputation: 1390

A majority of the Docker community will veer away from these types of designs, however it is very doable.

Similar to Starting and stopping docker container from other container you can simply mount the docker.sock file from the host machine into the container, giving it privilege to access the docker daemon.

To make things more automated, you could use the docker-py sdk to start containers from inside a container, which would in turn access the Docker deamon on the host machine hosting the container that you are spawning more containers from.

For example:

docker run -v /var/run/docker.sock:/var/run/docker.sock image1 --name test1

----

import docker
def create_container():
    docker.from_env().containers.run("image2", name="test2")

This example starts container test1, and runs that method inside the newly created container, which in turn creates a new container test2 running on the same host as test1.

Upvotes: 6

Related Questions