lmiguelvargasf
lmiguelvargasf

Reputation: 69655

How to run an existing stopped container and get inside the bash?

I am a newbie to Docker, and I know that in order to run a container I can use the following command:

docker run -it --name custom-container-name --hostname custom-hostname image-name bash

The previous command creates a container named custom-container-name which hostname is custom-hostname, and it uses the image image-name. I know that the -it flag gives me access to the bash. (please correct me if I am wrong)

Now, I have stopped this container, but I want use it again, so what is the command I should use to open this container again with its bash, as when I run the docker run ... command the first time it was created.

Upvotes: 29

Views: 30921

Answers (2)

Danyel
Danyel

Reputation: 2250

The general solution to inspect a stopped container which works in every case and doesn't assume anything about the container is to turn the container into an image using docker commit <CONTAINER_ID|CONTAINER_NAME>. You can then run any command you like on it, including bash.

A more general answer as the accepted one didn't help me. In my case I have a container which builds something that runs for a very long time and is now stopped. I can't docker start it because it will exit immediately since the build is already finished. I also don't want to run it again or modify it because the build takes >5 hours and is extremely flaky.

Upvotes: 0

Andrew
Andrew

Reputation: 423

The problem I think you're running into is that the command you provide is exiting immediately and for the container to keep running it needs a command that will not exit. One way I've found to keep containers running is to use the -d option like so:

docker run -dt --name custom-container-name --hostname custom-hostname image-name

That should start it running as a daemon in the background. Then you can open a shell in the container with:

docker exec -it custom-container-name /bin/bash

If the default user for the image is root (or unset) this should provide you a root shell within the container.

You can use docker inspect to see the details of the image to see what the default command and user are:

docker inspect image-name | less

Also, if your container exists, and its status is "Exited", you can start that container, and then use docker exec as follows:

docker start custom-container-name
docker exec -it custom-container-name /bin/bash

Upvotes: 28

Related Questions