How to retain docker alpine container after “exit”

2020-02-28 05:53发布

问题:

Like for example if I use command docker run -it alpine /bin/sh it starts a terminal after which I can install packages and all. Now when I use exit command it goes back to the terminal. (main one)

So how can I access the same container again? When I run that command again, I get a fresh alpine.

Please help

回答1:

The container lives as long as the specified run command process is still running. When you specify to run /bin/sh, once you exit, the sh process will die and so will you container.

If you want to keep your container running, you have to keep the process inside running. For your case (I am not sure what you want to acheive, I assume you are just testing), the following will keep it running

docker run -d --name alpine alpine tail -f /dev/null

Then you can sh into the container using

docker exec -it alpine sh  


回答2:

You should use docker start, which allows you to start a stopped container. If you didn't name your container, you'll need to get it's name/id using docker ps.

For example,

$docker ps
CONTAINER ID        IMAGE                        COMMAND
4c01db0b339c        alpine                       bash    

$docker start -i -a 4c01db0b339c   


回答3:

Pull an image

docker image pull alpine

See that image is there

docker image ls   OR  just docker images

see what is inside the alpine

docker run alpine ls -al

Now your question is how to stay with the shell

docker container run -it alpine /bin/sh

You are inside shell script command line. Some distribution may have bash shell.

 docker exec -it 5f4 sh
 / # (<-- you can run linux command here!)

At this point, you can use command line of alpine and do

ls -al

type exit to come out- You can run it in detached mode and it will keep running.

With exec command we can login again

docker container run -it -d alpine /bin/sh

verify that it is UP and copy the FIRST 2 -3 digits of the container ID

docker container ls

login with exec command

docker exec -it <CONTAINER ID or just 2-3 digits> sh

You will need to STOP otherwise it will keep running.

docker stop <CONTAINER ID>


回答4:

Run Alpine in background

$ docker run --name alpy -dit alpine
$ docker ps

Attach to Alpine

$ docker attach alpy


回答5:

What you should do is below

docker run -d --name myalpine alpine tail -f /dev/null

This would make sure that your container doesn't die. Now whenever you need to install packages inside you just get inside the container using sh

docker exec -it myalpine /bin/sh

If for some reason your container dies, you can still start it again using

docker start myalpine