So before starting the question here are my understanding for the docker.
Now Images are the ones on which the Containers are created and Dockerfile is like a flow what to do. In simple words Images are Classes and Containers are Objects of Images.
Now I don't want to take the approach of the Dockerfile
where you specify the steps to perform while creating the container.
I want to install some of the basic entities over Linux like MongoDb,Redis etc and run my server over them.
So I started like this:
I downloaded the Ubuntu image from Docker Hub via docker pull ubuntu
which returned me 18261df960118..7a16(big hex key)
Now I have to create a container for this image, to achieve that I did:
docker create -h abc.com --name abc.com 18261df960118..7a16
which returned me the id of the container.
docker start containerId
followed by docker attach containerId
.But every time it is saying:
You cannot attach to a stopped container, start it first.
Edit: In my original post I mention: "try to think like with VMs". I recently fell into this, which says not to do so:
Stop thinking about a container as a mini-VM and instead start thinking about it as just a process.
also, worth-reading article: Containers are not VMs
Original post:
The logic with Docker containers is that they are supposed to have a service up and running. If this service stops, they exit and go to "stopped" state. (As you learn more about Docker, you will understand how this works and you will be able to use ENTRYPOINT
and CMD
). But let's skip this for a while and try to think like with VMs, run a new container and get inside to type some commands...
docker container create -it --name test ubuntu
445cad0a3afea97494635361316e5869ad3b9ededdd6db46d2c86b4c1461fb75
$ docker container start test
test
$ docker container exec -it test bash
root@445cad0a3afe:/# your are inside, you can type your commands here!
when you created the container, you didn't use the -i
flag which helps Keep STDIN open even if not attached
. This practically means that when the container starts, it uses the CMD
set in the official ubuntu Dockerfile, which is bash
and then exits immediately.
You can test this with an image like nginx
. If you run a new nginx container and try to attach to it, you will see that logs from nginx are being printed out and you are not able to type any command in the shell. This happens because the CMD of the image is the following:
# Define default command.
CMD ["nginx"]
To be able to "attach" to a container like that but also be able to use the shell (some others may also mention this like doing something equivalent to ssh
to the container), you will have to run:
docker container exec -it your_container_name bash
I suggest you also read: