Create Docker container from image without startin

2019-06-16 21:37发布

问题:

As part of my deployment strategy, I am managing Docker containers with Upstart.

To do that, I need to pull an image from a registry and create a named container (as suggested on Upstart script to run container won't manage lifecycle )

Is there a way to create the container without first running the image? I don't want to have to start a container (which may introduce side effects), stop it, and then manage elsewhere.

For example, something like:

docker.io create -e ENV1=a -e ENV2=b -p 80:80 --name my_first_container sample/containe

回答1:

You can achieve that by using Docker Remote API.

First of all adjust how docker daemon is running. Configure it to listen to HTTP requests on port 4243 in addition to the default unix socket:

sudo sh -c "echo 'DOCKER_OPTS=\"-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock\"' > /etc/default/docker"

Now, you can use the /containers/create endpoint to create a container without running it:

curl -X POST -H "Content-Type: application/json" http://localhost:4243/containers/create?name=my_first_container -d '
{
    "Name": "dtest2",
    "AttachStdin": "false",
    "AttachStdout": "false",
    "AttachStderr": "false",
    "Tty": "false",
    "OpenStdin": "false",
    "StdinOnce": "false",
    "Cmd":["/bin/bash", "-c", "echo Starting;sleep 20;echo Stopping"],
    "Image": "ubuntu",
    "DisableNetwork": "false"
}
'

Pay attention to the ?name=my_first_container parameter I added to the curl request url. This is how you name your container.

Side note - The same can be achieved without adding the HTTP interface, however it seems easier to show the solution using a simple curl POST request.



回答2:

In case anyone else comes across this question, it can now be done with the docker create command. See https://docs.docker.com/engine/reference/commandline/create/



标签: docker