Docker container doesn't start, showing as 

2019-07-14 07:05发布

问题:

I am trying to understand how docker works when it comes to starting / getting into a container. I am new to this so bear with me. I tried finding the answer to my need in SO but could not so far.

I am trying to achieve 3 basic things:

  • Start a container
  • Make sure all ports are mapped to my container (i.e. I can see my container's apache from outside my container)
  • SSH or get console into my container

Here is what I am using to start a container:

caldav@caldav:~/docker/caldav-server$ sudo docker run -it -d -P  caldav-server service apache2 start

48fbea1865e302768a863767bf01b08f35f0221a4b29e5f2208d57e54660ef42

But when I run ps, I see it as 'exited n seconds ago':

CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
48fbea1865e3        caldav-server       "service apache2 sta   2 seconds ago       Exited (0) 1 seconds ago 

What does this even mean? And obviously, I dont get to see it up and running when I go to http://[IP_ADDRESS]

UPDATE: Ok, when I remove the apache start command it seems to stay up:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
20d5daca6237        caldav-server       "/bin/bash"         10 seconds ago      Up 9 seconds                            thirsty_ritchie     

But then I dont seem to be able to get console into it. This is what I tried:

docker attach 20d5daca6237

Which is fine (gives me bash access). However, when I try to exit it by typing

$ exit

it then shows the container as the 'exited' status in ps. Am I doing it wrong?

回答1:

A Docker container runs only as long as its initial command does. In this case, that command is service apache2 start, which exits after no more than a couple seconds, at which point the container stops as well. If you want to run a daemon in a container, you need to either make the daemon the primary program and make it run in the foreground or else use an image with a command that can handle daemons, like phusion/baseimage.



回答2:

When you attach to a container and then exit, your shell is killed and then your container stops as that is your init process.

Try these ideas:

If you need to get a console to any docker image all you have to do is use 'docker exec'

docker exec -ti [containername/hash] /bin/bash

Or install the Jpetazzo's nsenter / docker-enter tools

https://github.com/jpetazzo/nsenter

they are much easier than the docker exec

after running

docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter

just use

docker-enter [containername]



标签: docker