List all available docker images
We can start by listing all the images available on our system. If you have a new installation of docker, it should return empty.
sudo docker images
Running our first container
A container is a running instance of an image. So, in order to run a container, we need to have an image. Later on, we will be creating our own images, but for now we will be using a freely available image from Docker Hub, which is a free public registry of images maintained by the Docker team.
So, you can head on over to https://hub.docker.com/ and search for "docker/getting-started". This image is a demo image offered by the docker team as part of their tutorial. To download it(or any other image), on your terminal, execute the following.
sudo docker pull docker/getting-started
This will start downloading the image and any necessary dependencies.
After it's finished downloading, we can verify by listing the available images.
sudo docker images
Now we can run our container.
sudo docker run -d -p 8000:80 docker/getting-started
Lets break this down.
The -p
is used to bind a port on the host machine to a port on the container. Here, we're binding the port 8000
on our host machine to the port 80
on the container.
-d
will run the command in detached mode.
Now you can head on over to localhost:8000 on your web browser to confirm that the container is working properly.
Managing containers
To list all the running containers, we can use ps
.
sudo docker ps
Something to note is that, every time you use docker run
, it will start a new container each time. To list all the containers, we can use the -a flag.
sudo docker ps -a
To start an existing container, use docker start
with the container id or the container name.
sudo docker start <container name/id>
# example
sudo docker start 5c8b30b23a47
To stop a running container, use docker stop.
sudo docker stop <container name/id>
# example
sudo docker stop 5c8b30b23a47
To completely remove a docker container, first stop it. Then we can delete it.
# Stop the container first
sudo docker stop <container name/id>
# Removing the container
sudo docker rm <container name/id>