How do I run a command on an already existing Docker container?

So I think the answer is simpler than many misleading answers above.

To start an existing container which is stopped

docker start <container-name/ID>

To stop a running container

docker stop <container-name/ID>

Then to login to the interactive shell of a container

docker exec -it <container-name/ID> bash

To start an existing container and attach to it in one command

docker start -ai <container-name/ID>

Beware, this will stop the container on exit. But in general, you need to start the container, attach and stop it after you are done.


Your container will exit as the command you gave it will end. Use the following options to keep it live:

  • -i Keep STDIN open even if not attached.
  • -t Allocate a pseudo-TTY.

So your new run command is:

docker run -it -d shykes/pybuilder bin/bash

If you would like to attach to an already running container:

docker exec -it CONTAINER_ID /bin/bash

In these examples /bin/bash is used as the command.


To expand on katrmr's answer, if the container is stopped and can't be started due to an error, you'll need to commit it to an image. Then you can launch bash in the new image:

docker commit [CONTAINER_ID] temporary_image
docker run --entrypoint=bash -it temporary_image

In October 2014 the Docker team introduced docker exec command: https://docs.docker.com/engine/reference/commandline/exec/

So now you can run any command in a running container just knowing its ID (or name):

docker exec -it <container_id_or_name> echo "Hello from container!"

Note that exec command works only on already running container. If the container is currently stopped, you need to first run it with the following command:

docker run -it -d shykes/pybuilder /bin/bash

The most important thing here is the -d option, which stands for detached. It means that the command you initially provided to the container (/bin/bash) will be run in the background and the container will not stop immediately.

Tags:

Docker