Running containers

We mentioned earlier that containers are instances of images. When you want to run a Docker container, you can use the following command:

docker run IMAGE_NAME

There are plenty of Docker images available on the internet. Before creating a custom image, you should first review the list of images available on Docker Hub (https://hub.docker.com/).

Docker Hub is a cloud-based registry service that allows you to link to code repositories, build your images, and test them. It also stores manually pushed images and links to Docker Cloud so that you can deploy images to your hosts. Docker Hub provides a centralized resource for container and image discovery, distribution, and change management; user and team collaboration; and workflow automation throughout the development pipeline.

Let's say that you want to run a container using nginx. In this case, all that you need to do is execute the following command in the Terminal:

docker run nginx

Once you run this command, Docker will try to find the image locally. If it's unable to find it there, it will look for the image using all the registries available (we will talk about registries later on). In our case, this is Docker Hub. The first thing you should see in the terminal is an output similar to the following:

⋊> ~ docker run nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
f2aa67a397c4: Downloading [==================================> ] 15.74MB/22.5MB
3c091c23e29d: Downloading [=======> ] 3.206MB/22.11MB
4a99993b8636: Download complete

After executing this operation, you will get a string similar to d38bbaffa51cdd360761d0f919f924be3568fd96d7c9a80e7122db637cb8f374 that represents the image ID.

Some useful flags for running containers are as follows:

For example, the following command makes it possible to run nginx as a daemon and maps port 80 from the container to port 32888 on the host:

docker run -p 32888:80 -d nginx

Now you will have control of the terminal again, and you can see the nginx homepage in the http://localhost:32888/ URL, as shown in the following screenshot:

Nginx homepage

Containers only have the software and services that are strictly necessary for them to work, which is why you'll find that they don't even include an SSH entry. If you want to get into a container, you can use the -it flag, which executes a command within the container as follows:

⋊> ~ docker run -it nginx /bin/bash
# Now you're inside the container here

root@0c546aef5ad9:/#