Docker Commands Tutorial | Getting Started With Docker In Linux
======
Essential Docker Commands For beginners
This detailed Docker tutorial covers the essential **Docker commands**, such as how to create a new container, run the container, remove a container and so on. In addition, this guide also explains how to build your own custom Docker image from an existing container and how to remove containers and images. Without further ado, let us **get started with Docker basics usage**!
### Docker Installation Steps
Docker can be installed in most modern Linux operating systems. If you haven't installed Docker yet, refer the following guides:
* [Install Docker Engine And Docker Compose In AlmaLinux, CentOS, Rocky Linux][1]
* [How to Install Docker And Docker Compose In Ubuntu][2]
### What Is Docker Image And Docker Container?
Before getting started with Docker, let me clarify what is a **Docker image** and a **Docker Container**.
A Docker Image is the file that decides how a Container should behave, and Docker Container is the running or stopped stage of a Docker image.
The containers are isolated from the rest of host's files.
When we run a Docker container, it uses an isolated filesystem which provided by a Docker image. The Docker image consists of everything needed to run an application - all dependencies, configuration, scripts, binaries, etc.
The image also contains other configuration for the container, such as environment variables, a default command to run, and other metadata.
### Getting Started With Docker In Linux
All steps given below are tested in Ubuntu 22.04, 20.04 and 18.04 LTS server edition. However, the steps provided in the subsequent sections are common to all Linux platforms. For example, you can run the same commands in a RHEL-based system(E.g. AlmaLinux) too.
#### 1. Search Docker Images
We can get the images from either from the official docker library called [Docker hub][3], or create our own.
For those wondering, Docker hub is an online central repository where all Docker users build, test, and save their Docker images. Docker hub has tens of thousands of Docker images and the number of images is growing everyday.
You can search for the any Docker images with **"docker search"** command from command line.
For instance, to search for docker images based on **Alpine** Linux, run:
```
$ sudo docker search alpine
```
**Sample Output:**
![Search Docker Images][4]
To search images based on **Ubuntu**, run:
```
$ sudo docker search ubuntu
```
You can even search images for any application, for example **Nginx**, like below:
```
$ sudo docker search nginx
```
Docker hub has a wide range of images. Be it an operating system, application, or combination of multiple applications (E.g. LAMP stack), you will find pre-built Docker images for everything in Docker hub.
If something you're looking for is not available, you can build it and make it available for public via Docker hub or keep it private for your own use.
#### 2. Download Docker Images
To download Docker image for Ubuntu OS, run the following command from the Terminal:
```
$ sudo docker pull ubuntu
```
The above command will download the latest Ubuntu image from the **Docker hub**.
You can also download a specific version of Ubuntu image using command:
```
$ sudo docker pull ubuntu:20.04
```
Docker allows us to download any images and start the container based on that image regardless of the host OS.
For example, to download Alpine OS image, run:
```
$ sudo docker pull alpine
```
![Download Docker Images][5]
#### 3. List Docker Images
All downloaded Docker images will be saved in **/var/lib/docker/** directory.
To view the list of downloaded Docker images, run:
```
$ sudo docker images
```
**Sample Output:**
```
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest 27941809078c 3 weeks ago 77.8MB
ubuntu 20.04 20fffa419e3a 3 weeks ago 72.8MB
alpine latest e66264b98777 5 weeks ago 5.52MB
```
![List Docker Images][6]
As you see above, I have downloaded three Docker images - **Ubuntu****latest**, **Ubuntu 20.04** and **Alpine Linux**.
Now, let us go ahead and see how to start or run the containers based on the downloaded images.
#### 4. Run Docker Containers
We can start a container in two ways - either using its Docker **Image****TAG** or **Image ID**.
**TAG** refers to a particular snapshot of the image and the **IMAGE ID** is the corresponding unique identifier for that image.
Take a look at the following screenshot:
![Docker Image Tag and ID][7]
As you see in the above results, the tags are **"latest"** and **"20.04"**.
* 27941809078c is the IMAGE ID of Ubuntu latest Dockerimage,
* 20fffa419e3a is the image id of Ubuntu 20.04 Docker image
* and `e66264b98777` is the image id of Alpine latest Docker image.
##### 4.1. Run Containers Using Tag
Once you downloaded the Docker images of your choice, run the following command to start a Docker container and connect to it by using its TAG.
```
$ sudo docker run -t -i ubuntu:latest /bin/bash
```
Or,
```
$ sudo docker run -it ubuntu:latest /bin/bash
```
Here,
* -t : Assigns a new Pseudo Terminal inside the Ubuntu container.
* -i :Allows us to make an interactive connection by grabbing the standard in (STDIN) of the container.
* ubuntu:latest: Ubuntu docker image with Tag "latest".
* /bin/bash: BASH shell for the new container. This is optional. If you don't mention the shell, the default shell will be assigned to the container.
After starting the container, you'll be automatically landed into the Container's shell (Command prompt):
![Run Containers Using Tag][8]
The new container based on the Ubuntu latest image has been started now. A unique ID and a name will be given to all the newly containers. As you can see in the above output, the Ubuntu container ID is **2f2a5b826762**. We will see where to find the name of the container in a minute.
You can now start working in the container. Once you're done with the Container, you can return back to the host system's Terminal (In my case, it is Ubuntu 22.04 LTS) without terminating the Container (guest os).
##### 4.2. Detach From Running Containers
To detach from a running container (without terminating it), press **CTRL+P** followed by **CTRL+Q**.
Now, you are back to your original host computer's terminal window. Please note that the container is still running in the background and we didn't terminate it yet.
##### 4.3. Run Containers Using IMAGE Id
The another way to start a container and connect to it is by using the IMAGE ID as shown below:
```
$ sudo docker run -it 20fffa419e3a /bin/bash
```
Here,
* 20fffa419e3a- Image id
To detach from the container and return back to the host system's Terminal, press **CTRL+P** and **CTRL+Q**. Again, we only detached from the container but didn't stop it. The container is still running in the background.
##### 4.4. Run Containers In Detached Mode
In the previous sections, we started a container and attached to it immediately. And then we detached from the container once our work with that container is completed.
You can also start container in detached mode (without automatically attaching it).
Similarly we can stop a docker container using its name or ID. If you're already inside the container's shell, you can stop the container by simply running the following command:
```
# exit
```
You can also stop (power off the container) from the Docker host system using the following command:
```
$ sudo docker stop 10615254bb45
```
You can exit multiple containers with space-separated as shown below.
```
$ sudo docker stop 35b5ee8c3d3a 10615254bb45
```
After exiting the container, verify if it is really stopped by listing the running containers with command:
```
$ sudo docker ps
```
#### 8. Kill Docker Containers
The docker stop command will gracefully turn off a running container. Sometimes, you may stuck with an unresponsive container or you want to forcibly shutdown a container.
To kill a container by sending a `SIGKILL` to a running container, run:
```
$ sudo docker kill 10615254bb45
```
#### 9. Automatically Delete Containers After Closing Them
You may want to test a Container and then delete it once you're done with the Container. If so, you can automatically delete the Container after closing it by using `--rm` flag:
```
$ sudo docker run -it --rm debian:latest
```
Once you exit from the Container, it will be automatically deleted.
![Automatically Delete Containers][12]
As you see in the above output, I created a new Debian container. Once I exit from the container, it is automatically deleted. The `docker ps -a` output shows that the Debian container doesn't exist.
#### 10. Assign Name To Containers
If you closely look into the output of previous commands, each container is given a random name when you start a container. If you don't name your Containers, Docker will name them for you automatically.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
80b53b7e661d alpine:latest "/bin/sh" 3 seconds ago Up 2 seconds bold_margulis
2af79e97a825 alpine:latest "/bin/sh" 6 seconds ago Up 5 seconds recursing_taussig
```
As you see in the above output, even though I have created two containers using the same docker image, they both gets different ID and name.
If you want to assign a static name to the container, use `--name` flag like below:
```
$ sudo docker run -it -d --name ostechnix_alpine alpine:latest
```
The above command will create run a new Container called **ostechnix_alpine** in detached mode.
let us view list of the running Containers:
```
$ sudo docker ps
```
**Sample Output:**
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
397111fac537 alpine:latest "/bin/sh" 2 seconds ago Up 2 seconds ostechnix_alpine
80b53b7e661d alpine:latest "/bin/sh" 7 minutes ago Up 7 minutes bold_margulis
2af79e97a825 alpine:latest "/bin/sh" 7 minutes ago Up 7 minutes recursing_taussig
```
![Assign Name To Containers][13]
Did you notice the name of the first Container in the above output? Yes, we've assigned a custom name (i.e. `ostechnix_alpine` ) to the Container.
Assigning custom names to containers gives us a benefit. We can easily identify what is installed in that container by looking at the name of the container name.
#### 11. Build Custom Docker Images
Docker is not just for downloading and using the existing containers. You can create your own custom docker image as well.
Let us start an Ubuntu container:
```
$ sudo docker run -it ubuntu:latest
```
Now, you will be in the container's shell.
Then, install any software or do whatever you want in the container.
For example, let us install **Apache web server** in the container.
```
# apt update
# apt install apache2
```
Similarly, install and test any software of your choice in the Container.
Once you're done, detach from the container (don't exit it) and return back to the host system's shell. Please do not stop or power-off the Container. To detach from the container without stopping it, press `CTRL+P` followed by `CTRL+Q`.
From your Docker host terminal, run the following command to find the container ID:
```
$ sudo docker ps
```
Finally, create a Docker image of the running Container using command:
To remove all stopped containers, all images, build cache, all networks, run:
```
$ sudo docker system prune -a
```
Be careful while using this command. It will delete all unused containers, networks, images (both dangling and unreferenced).
![Delete Everything In Docker][16]
By default, volumes are not removed to prevent important data from being deleted even if there is currently no container using the volume.
If you want to delete everything including the Volumes, use the `--volumes` flag.
```
$ sudo docker system prune -a --volumes
```
### Docker Troubleshooting
Docker won't let you to delete the Docker images if they are used by any running or stopped containers.
For example, when I try to delete a Docker Image with ID**b72889fa879c**, from one of my old Ubuntu server. I got the following error:
```
Error response from daemon: conflict: unable to delete b72889fa879c (must be forced) - image is being used by stopped container dde4dd285377
```
This is because the Docker image that you want to delete is currently being used by another Container.
So, let us check the running Container using command:
```
$ sudo docker ps
```
**Sample Output:**
![Show running docker containers][17]
Oops! There is no running container.
Let us again check for all containers (running and stopped) with command:
```
$ sudo docker ps -a
```
**Sample Output:**
![Show running and stopped docker containers][18]
As you see, there are still some stopped containers are using one of the Docker images. So, let us delete all of the containers.
**Example:**
```
$ sudo docker rm 12e892156219
```
Similarly, remove all containers as shown above using their respective container's ID.
Once you deleted all containers, finally remove the Docker images.
**Example:**
```
$ sudo docker rmi b72889fa879c
```
That's it. Now verify if there are any other Docker images in the host with command:
```
$ sudo docker images
```
You will now probably won't have any docker images.
### Conclusion
In this comprehensive **getting started with Docker tutorial**, we explained Docker basics such as creating, running, searching, removing containers and also building own Docker image from a Container. We also explained how to delete Docker containers and images when they are no longer necessary.
Hope you a got the basic idea about **Docker usage**.
For more details, refer the official resource links given at the end of this guide or drop a comment in the comment section below.