Search code examples
dockercontainers

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.


Solution

  • 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