A Beginner's Guide to Docker Image Commands: Managing Docker Images
Tags: cloud, docker
Published: 2024-03-13 19:22:57

In the world of containerization, Docker has emerged as a dominant force, simplifying the way developers build, ship, and run applications. At the core of Docker's functionality are Docker images, lightweight, standalone, executable packages that contain everything needed to run a piece of software, including the code, runtime, libraries, and dependencies.

Managing Docker images is a crucial aspect of working with Docker, and understanding the various Docker image commands is key to efficiently handling your Docker images. In this blog post, we'll explore some of the most common Docker image commands, demystifying their usage and highlighting best practices along the way.

Whether you're just getting started with Docker or looking to enhance your Docker skills, this guide will equip you with the knowledge you need to manage Docker images like a seasoned pro. Let's dive in!

## Docker pull

This command downloads a docker image from a public or private registry (example being Docker Hub) to your local image. 

Docker images are stored in repositories, which can be public (like Docker Hub) or private (self-hosted or on a different registry). Thus, when you use docker pull, Docker contacts the specified registry and downloads the image to your local machine. If the image already exists locally, Docker will check if there is a newer version available on the registry and download it if necessary.

#### Syntax

```
docker pull <image_name>:<tag>
```

#### Example

```
docker pull ubuntu:latest
```
This downloads the latest version of the official Ubuntu image.

## docker images

This command will list all Docker images that are currently available on your local system. 

Docker images are stored locally on your machine after being downloaded from a registry or built using a Dockerfile. The docker images command provides a list of all these images, along with their repository name, tag, image ID, and size. It allows you to see what images you have available to use for creating and running containers. 

You can use the output of docker images to manage your images, such as removing images that are no longer needed or checking the versions of images that you have downloaded. Images listed as <none> in the repository column are usually intermediate images created during the build process and can be removed using `docker rmi`.

#### Syntax

```
docker images
```

#### Example


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qp7sp9ld6qexc75q7jzi.png)

In this example, the output shows three images: nginx with the latest tag, mysql with the 5.7 tag, and an unnamed image (with repository and tag set to <none>) that can be removed if not needed.

## docker run

docker run creates a running container instance from a certain docker image

When you run  docker run <image_name>, Docker looks for the specified image locally. If the image is not found locally, Docker will attempt to download it from a registry before creating the container. 

You can also specify options and arguments with the docker run command to customize the container's behavior, such as setting environment variables, exposing ports, or mounting volumes.

#### Syntax

```
docker run [options] <image_name>:<tag> [command] [arguments]
```

- Options (e.g., `-d `for detached mode, `-p` for port mapping) can be used to customize container behavior.
- Replace `<image_name>` and `<tag> `as explained earlier.
- command (optional): The command to run within the container.
- arguments (optional): Arguments to pass to the command.


#### Example

Let’s look at an example to understand this syntax better

```
docker run -d --name my-container -p 8080:80 nginx:latest nginx -g 'daemon off;'
```

In the above example the following have been used:

- Options: `-d, --name, -p` are options that modify the behavior of the docker run command.
- -d runs the container in detached mode, meaning it runs in the background.
- --name my-container sets the name of the container to my-container.
- `-p 8080:80`maps port 8080 on the host to port 80 in the container, allowing you to access the nginx web server running in the container from your host machine at http://localhost:8080.
- Image name and tag:  `nginx:latest` specifies the Docker image to use (nginx in this case) and its tag (latest).
- Command: `nginx -g 'daemon off;'` is the command that overrides the default command specified in the Dockerfile and is executed when the container starts.

Here’s another simpler example:

```
docker run -it ubuntu:latest bash
```

This starts a new container based on the ubuntu:latest image in interactive mode (-it) and  start an interactive Bash shell inside that container. This allows you to execute commands and interact with the Ubuntu environment within the container.

## docker inspect

Displays detailed information about a specific Docker image.

In general, The docker inspect command provides detailed information about a Docker object, such as an image or container. It returns a JSON object containing various metadata and configuration details.

When used with an image, docker inspect provides information like the image ID, size, tags, creation date, and details about the image's layers.

When used with a container, docker inspect provides information about the container's configuration, network settings, volumes, and more.

You can use docker inspect to troubleshoot issues, understand how images or containers are configured, and retrieve specific details for scripting or automation purposes.

#### Syntax

```
docker inspect <image_or_container_id>
```

#### Example on an Image

```
docker inspect ubuntu:latest
```

Output

```
[
    {
        "Id": "sha256:3339fe25b7e8c0da71a528d937d7acae0861dfb6421ee8bce4b5a605cb14059a",
        "RepoTags": [
            "ubuntu:latest"
        ],
        "RepoDigests": [],
        "Parent": "",
        "Comment": "",
        "Created": "2022-01-01T00:00:00.000000000Z",
        "Container": "",
        "ContainerConfig": {
            "Hostname": "abcd1234",
            "Domainname": "",
            "User": "",
            ...
        },
        ...
    }
]

```
Here’s an explanation of a few key elements from the above output

- `"Id": "sha256:3339fe25b7e8c0da71a528d937d7acae0861dfb6421ee8bce4b5a605cb14059a"`:  Unique identifier (SHA256 hash) for the container.
- `"RepoTags": ["ubuntu:latest"]`: Tags associated with the image, in this case, the latest tag for the ubuntu repository.
- `"Created": "2022-01-01T00:00:00.000000000Z"`: Date and time when the container was created.
- `"ContainerConfig"`: { ... }: Configuration details for the container, such as hostname, domain name, user, etc. This section provides the configuration used when a container is created from this image.

#### Example on a container

```
docker inspect my-container
```

Output

```
[
    {
        "Id": "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234",
        "Created": "2022-01-01T00:00:00.000000000Z",
        "Path": "bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            ...
        },
        "Image": "sha256:3339fe25b7e8c0da71a528d937d7acae0861dfb6421ee8bce4b5a605cb14059a",
        "...
    }
]

```
Here’s an explanation of a few key elements from the above output

- `"Id":"abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234"`: Unique identifier (SHA256 hash) for the container.
- `"Created": "2022-01-01T00:00:00.000000000Z"`: Date and time when the container was created.
- `"Path": "bash"`: The path to the command that was run when the container was started. In this case, it is bash. This means that when the container was started, it executed the bash command as its main process. In Docker, the command specified after the image name in the docker run command (or the default command specified in the Dockerfile if no command is specified) is the initial command that the container runs. In this case, the bash command is commonly used to start an interactive shell within the container.
- `"State": { "Status": "running", "Running": true, ... }`: Information about the current state of the container, such as whether it is running, paused, or stopped.
- `"Image": "sha256:3339fe25b7e8c0da71a528d937d7acae0861dfb6421ee8bce4b5a605cb14059a"`: The image used to create the container, identified by its image ID.

## docker build

Build a Docker image from a Dockerfile and context.

The Dockerfile contains instructions on how to build the image, such as which base image to use, what commands to run, and what files to include.

docker build command reads the Dockerfile and executes the instructions to create a new Docker image.

The context is the set of files and directories located at the specified PATH or URL. These files are sent to the Docker daemon for building the image. What this means is, when you use docker build to create a Docker image, you provide a "context" to the Docker daemon. This "context" is simply the set of files and directories that Docker will use to build the image. For example, if you run docker build ., the current directory (denoted by .) and all its files and subdirectories will be sent to Docker as the context. Docker will then use these files to follow the instructions in your Dockerfile and create the image.

Each instruction in the Dockerfile adds a new layer to the image, allowing for efficient reuse of layers between images.

#### Syntax

```
docker build [OPTIONS] PATH | URL
```
Some options that can be pass to this command include:

- `-t, --tag`: Name and optionally a tag in the 'name:tag' format to apply to the resulting image.
- `--build-arg`: Set build-time variables that are accessed like environment variables in the Dockerfile.
- `-f, --file`: Name of the Dockerfile (Default is 'PATH/Dockerfile').
- `--force-rm`: Always remove intermediate containers, even after unsuccessful builds.
- `--no-cache`: Do not use cache when building the image.
- `--pull`: Always attempt to pull a newer version of the base image before building.

#### Example:

```
docker build -t my-image:latest .
```
In this example, docker build would build a Docker image named my-image with the tag latest using the Dockerfile located in the current directory (.).

## docker save

This command  saves a Docker image as a tar archive to the local filesystem.

It is used to export a Docker image as a tarball file (A tarball file is a file archive format used to bundle files and directories together, commonly used in Unix and Linux systems. In Windows, the equivalent of a tarball file would be a ZIP file.), which allows you to save the image locally or transfer it to another machine.

The saved tarball contains all the layers of the Docker image, along with its metadata.

Once saved, you can use docker load  (next command below) to import the image back into Docker on the same or another machine. This command is useful for creating backups of Docker images or sharing them with others who do not have direct access to a Docker registry.

#### Syntax

```
docker save <image_name>:<tag> -o <output_file.tar>
```

#### Example

```
docker save ubuntu:latest -o ubuntu_latest.tar
```

In this example, the docker save command saves the ubuntu:latest image as a tarball file named ubuntu_latest.tar.

## docker load

This command loads a docker image from a tar archive

It is used to import a Docker image that was previously saved as a tarball file using the docker save command. It reads the tarball file and imports the image into the Docker image repository on your local system.

After loading the image, you can use it to create and run containers as you would with any other Docker image.

#### Syntax

```
docker load <image_tar_file>  # Load from a tar archive
docker load  # Load from standard input (STDIN)
```

#### Example

```
docker load -i ubuntu_latest.tar
```

In this example, the docker load command imports the ubuntu_latest.tar tarball file, which contains a Docker image, into the local Docker image repository.

This command essentially enables you to import Docker images from external sources like tar archives, allowing you to use pre-built or custom images without directly pulling them from a registry.

## docker tag

This command creates a tag for an existing docker image

Tags are used to identify different versions or variants of an image. By default, Docker images are tagged with latest if no tag is specified. However, it's good practice to use explicit tags to version your images.

Tags are specified in the format <repository>:<tag>, where <repository> is the name of the image repository and <tag> is the tag you want to assign to the image. After tagging an image, you can use the new tag to reference the image when running containers or pushing it to a registry.

#### Syntax

```
docker tag <image_name>:<existing_tag> <image_name>:<new_tag>
docker tag <source_image_name>:<source_tag> <target_image_name>:<target_tag>

```

#### Examples

```
docker tag ubuntu:latest ubuntu:mytag
```

In this example, the docker tag command creates a new tag mytag for the ubuntu:latest image, resulting in the image being tagged as ubuntu:mytag.

Here's another example:

```
docker pull ubuntu:18.04  # Download the Ubuntu 18.04 image
docker tag ubuntu:18.04 my-ubuntu:v1  # Create a custom tag 'v1' for the image

```

This creates a new tag named v1 for the existing ubuntu:18.04 image.


## docker rmi

Removes a Docker image.

This command is used to delete images from your local machine that are no longer needed to free up disk space. It can remove one or more Docker images from your local Docker image cache.

You can specify the image to remove by its name or ID. If the image is in use by a container, you will need to stop and remove the container before you can remove the image. You can use the command  docker stop to halt the running container

#### Syntax

```
docker rmi <image_name_or_id>
```

#### Example

```
docker rmi ubuntu:mytag
//docker rmi removes the ubuntu:mytag image

```

## docker image prune

Removes unused Docker images from the local system.

This command is used to remove unused images that are not referenced by any containers. It cleans up your local Docker image cache by removing images that are not currently in use, which is useful for freeing up disk space. You can use the -a or --all flag to also remove unused images that have tags other than <none>, which are usually intermediate images created during the build process.

#### Syntax

```
docker image prune [OPTIONS]
```


Options:

- `-a, --all`: Remove all unused images, not just dangling ones.
- `--filter filter`: Provide filter values (e.g., until, label, before) to specify the images to prune.

## docker push

This command is used to push a Docker image to a remote registry, such as Docker Hub or a private registry. It allows you to share your Docker images with others or deploy them to production environments. 

Before you can push an image, you need to tag it with the name of the registry where you want to push it. This is typically done using the `-t` flag when building the image or using the `docker tag` command.

Once the image is tagged, you can use docker push to upload it to the specified registry. 

You'll need to authenticate with the registry using `docker login `before pushing the image.

When you push an image, Docker uploads all the image layers to the registry. This allows others to pull the image and use it on their own systems.

#### Syntax

```
docker push <image_name>:<tag>
```

#### Example

```
docker push my-username/my-image:latest
```

In this example, docker push would push the my-image image with the latest tag to the Docker Hub registry under the my-username account.



Throughout this blog post, we've covered some of the most common Docker image commands, including docker build, docker tag, docker push, and more. We've explored how each command works and how it can be used to enhance your Docker experience.

Start experimenting with Docker image commands today and see how they can transform the way you build, ship, and run your applications. 

Happy containerizing!