How do I run a command on an already existing Dock

2020-01-23 13:27发布

I created a container with -d so it's not interactive.

docker run -d shykes/pybuilder bin/bash

I see that the container has exited:

CONTAINER ID        IMAGE                     COMMAND             CREATED             STATUS                      PORTS               NAMES
d6c45e8cc5f0        shykes/pybuilder:latest   "bin/bash"          41 minutes ago      Exited (0) 2 seconds ago                        clever_bardeen

Now I would like to run occasional commands on the machine and exit. Just to get the response.

I tried to start the machine. I tried attaching. I thought I could call run with a container, but that does not seem to be allowed. Using start just seems to run and then exist quickly.

I'd like to get back into interactive mode after exiting.

I tried:

docker attach d6c45e8cc5f0

But I get:

2014/10/01 22:33:34 You cannot attach to a stopped container, start it first

But if I start it, it exits anyway. Catch 22. I can't win.

标签: docker
17条回答
在下西门庆
2楼-- · 2020-01-23 13:39

A quick way to resume and access the most recently exited container:

docker start -a -i `docker ps -q -l`
查看更多
手持菜刀,她持情操
3楼-- · 2020-01-23 13:42

Unfortunately it is impossible to override ENTRYPOINT with arguments with docker run --entrypoint to achieve this goal.

Note: you can override the ENTRYPOINT setting using --entrypoint, but this can only set the binary to exec (no sh -c will be used).

查看更多
迷人小祖宗
4楼-- · 2020-01-23 13:45

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.

查看更多
Emotional °昔
5楼-- · 2020-01-23 13:46

Creating a container and sending commands to it, one by one:

docker create --name=my_new_container -it ubuntu
docker start my_new_container
// ps -a says 'Up X seconds'
docker exec my_new_container /path/to/my/command
// ps -a still says 'Up X+Y seconds'
docker exec my_new_container /path/to/another/command
查看更多
SAY GOODBYE
6楼-- · 2020-01-23 13:46
# docker exec -d container_id command 

Ex:

# docker exec -d xcdefrdtt service jira stop 
查看更多
你好瞎i
7楼-- · 2020-01-23 13:49

This is a combined answer I made up using the CDR LDN answer above and the answer I found here.

The following example starts an Arch Linux container from an image, and then installs git on that container using the pacman tool:

sudo docker run -it -d archlinux /bin/bash
sudo docker ps -l
sudo docker exec -it [container_ID] script /dev/null -c "pacman -S git --noconfirm"

That is all.

查看更多
登录 后发表回答