Table des matières

Version : 2024.01

Last update : 2024/12/17 13:46

DOE602 - Getting started with Docker

Contents

Introduction to Docker

Virtualisation and Containerisation

Traditional virtualisation requires the use of a hypervisor:

Docker is a lightweight virtualisation application launched in 2013 that uses images and containers.

Docker consists of three components: a server, a client and one or more repositories:

An image is an executable package containing everything needed to run a given piece of software, including :

A container is an instance of the image running in memory. It is isolated from the host environment by default but can access host files and ports depending on configuration.

Containers run applications natively using the kernel of the host machine. As a result, the performance of a container is superior to that of a virtual machine, which has to go through a hypervisor to access the host machine's resources.

The AUFS file system

To manage the container file system, Docker initially used the AUFS filesystem. AUFS is a file system in the UnionFS family. A UnionFS file system assembles multiple directories on top of each other and then presents them in the form of a single directory containing the most recent objects using a union mount. AUFS directories are called branches and are located in /var/lib/docker/aufs :

OverlayFS and Overlay2

The AUFS file system was then replaced in Docker by the OverlayFS file system. This file system combines two directories called Layers. The bottom layer is called lowerdir and the top layer is called upperdir. The unified view is called merged. If the container and image layers contain the same object, the container “wins” and hides the object in the image:

Image 2

The OverlayFS file system can only manage two levels. This implies excessive use of inodes in the case of a multi-level image, as each image must reside in its own directory, which is located in /var/lib/docker/overlay. Physical links are then used to reference data in the lower levels.

This limitation led to the introduction of the Overlay2 file system currently used by Docker. Overlay2 is capable of handling 128 layers.

Important - Note that Docker can also use the BTRFS file system.

Docker Daemon and Docker Engine

The Docker Daemon, called dockerd, along with the REST API and Docker CLI are collectively called the Docker Engine :

The Docker Engine can use plugins. These plugins, available for download from the public Docker Registry, called the Docker Hub, add extra functionality to the Docker Engine. Currently, plugins exist for :

You can also create your own plugins.

Docker CE and Docker EE

Docker CE

Docker comes in two versions Docker CE (Docker Community Edition) and Docker EE (Docker Enterprise Edition).

Docker CE is :

Docker CE comes in two sub-versions:

Docker EE

Docker EE is :

Docker EE includes:

Docker EE is available in three sub-versions, known as Tiers:

To see the differences between the two versions, go to https://docs.docker.com/engine/installation/.

Docker and Mirantis

Docker EE was acquired by Mirantis in November 2019.

As a result, Miratis has renamed certain Docker EE components:

LAB #1 - Working with Docker

Docker is available for Windows™ and Mac as binary :

Platform x86_64 / amd64
Docker Desktop for macOS pkg
Docker Desktop for Windows™ exe or msi

Docker is available for Linux as an rpm or deb package:

Platform x86_64 / amd64 ARM ARM64 / AARCH64
CentOS rpm rpm
Fedora rpm rpm
Debian deb deb deb
Ubuntu deb deb deb
Raspian deb deb

Packages are available either from the Docker repository or from the OS package manager. Docker can also be installed using automated scripts provided by Docker.

Please note that since the names of Docker packages have changed, you should uninstall any previous version of Docker before installing the current version:

For example under Debian and Ubuntu:

# apt-get remove docker docker-engine docker.io containerd runc

Under CentOS and Fedora:

# yum remove docker docker-client docker-client-latest docker-latest docker-common docker-engine docker-logrotate docker-latest-logrotate

Docker is available in three channels:

1.1 - Installing docker under Linux

Debian 11

Docker is not in the Debian repositories. In order to install it, you need to add the docker repository. First, you need to install the packages that allow Debian to use an https repository:

root@debian11:~# apt-get update
...
root@debian11:~# apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
ca-certificates is already the newest version (20210119).
gnupg2 is already the newest version (2.2.27-2+deb11u2).
The following packages were automatically installed and are no longer required:
  libopengl0 linux-headers-5.10.0-15-amd64 linux-headers-5.10.0-15-common
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
  python3-distro-info python3-software-properties unattended-upgrades
Suggested packages:
  bsd-mailx default-mta | mail-transport-agent needrestart powermgmt-base
The following NEW packages will be installed:
  apt-transport-https curl python3-distro-info python3-software-properties
  software-properties-common unattended-upgrades
0 upgraded, 6 newly installed, 0 to remove and 0 not upgraded.
Need to get 661 kB of archives.
After this operation, 1,567 kB of additional disk space will be used.
Do you want to continue? [Y/n] y

Download the official docker GPG key:

root@debian11:~# curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
OK

Check that the key ID is 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88 :

root@debian11:~# apt-key fingerprint 0EBFCD88
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
pub rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
uid [ unknown] Docker Release (CE deb) <docker@docker.com>
sub rsa4096 2017-02-22 [S]

Add the stable docker repository:

root@debian11:~# add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"

Important - Note that the lsb_release -cs command returns the name of the Debian version.

Now install the docker-ce package:

root@debian11docker:~# apt-get update
...
root@debian11:~# apt-get install docker-ce
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libopengl0 linux-headers-5.10.0-15-amd64 linux-headers-5.10.0-15-common
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
  containerd.io docker-buildx-plugin docker-ce-cli docker-ce-rootless-extras
  docker-compose-plugin git git-man liberror-perl libslirp0 pigz slirp4netns
Suggested packages:
  aufs-tools cgroupfs-mount | cgroup-lite git-daemon-run | git-daemon-sysvinit
  git-doc git-el git-email git-gui gitk gitweb git-cvs git-mediawiki git-svn
The following NEW packages will be installed:
  containerd.io docker-buildx-plugin docker-ce docker-ce-cli
  docker-ce-rootless-extras docker-compose-plugin git git-man liberror-perl
  libslirp0 pigz slirp4netns
0 upgraded, 12 newly installed, 0 to remove and 0 not upgraded.
Need to get 121 MB of archives.
After this operation, 452 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

Lastly, check the version of Docker client and server:

root@debian11:~# docker version
Client: Docker Engine - Community
 Version: 24.0.5
 API version: 1.43
 Go version: go1.20.6
 Git commit: ced0996
 Built:             Fri Jul 21 20:35:45 2023
 OS/Arch: linux/amd64
 Context: default

Server: Docker Engine - Community
 Engine:
  Version: 24.0.5
  API version: 1.43 (minimum version 1.12)
  Go version: go1.20.6
  Git commit: a61e2b4
  Built:            Fri Jul 21 20:35:45 2023
  OS/Arch: linux/amd64
  Experimental: false
 containerd:
  Version: 1.6.22
  GitCommit:        8165feabfdfe38c65b599c4993d227328c231fca
 runc:
  Version: 1.1.8
  GitCommit: v1.1.8-0-g82f18fe
 docker-init:
  Version: 0.19.0
  GitCommit: de40ad0

Important - Note that the docker-ce package needs the containerd.io and docker-ce-cli packages. Also note that the above procedure installs the most recent version of Docker.

In the event that you wish to install a different version, you should first note the versions available:

root@debian11:~# apt-cache madison docker-ce
 docker-ce | 5:24.0.5-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:24.0.4-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:24.0.3-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:24.0.2-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:24.0.1-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:24.0.0-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.6-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.5-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.4-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.3-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.2-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.1-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:23.0.0-1~debian.11~bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.24~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.23~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.22~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.21~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.20~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.19~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.18~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.17~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.16~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.15~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.14~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.13~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.12~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.11~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.10~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.9~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.8~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.7~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages
 docker-ce | 5:20.10.6~3-0~debian-bullseye | https://download.docker.com/linux/debian bullseye/stable amd64 Packages

In the event that you want to install Docker version 24.0.1, the installation command would become:

# apt-get install docker-ce=5:24.0.1-1~debian.11~bullseye docker-ce-cli=5:24.0.1-1~debian.11~bullseye containerd.io

If you prefer to use the Docker installation script, you should download it first:

Important - Note that these scripts should not be used in a production environment.

root@debian11:~# curl -fsSL https://get.docker.com -o get-docker.sh

root@debian11:~# ls
get-docker.sh

Next, we need to run the script:

root@debian11:~# chmod +x get-docker.sh 

root@debian11:~# ./get-docker.sh 
# Executing docker install script, commit: c2de0811708b6d9015ed1a2c80f02c9b70c8ce7b
Warning: the "docker" command appears to already exist on this system.

If you already have Docker installed, this script can cause trouble, which is
why we're displaying this warning and provide the opportunity to cancel the
installation.

If you installed the current Docker package using this script and are using it
again to update Docker, you can safely ignore this message.

You may press Ctrl+C now to abort this script.
+ sleep 20
^C

Important - Note the use of ^C to NOT continue executing the script.

Start a hello-world image container:

root@debian11:~# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
719385e32844: Pull complete 
Digest: sha256:dcba6daec718f547568c562956fa47e1b03673dd010fe6ee58ca806767031d1c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

Important - Note that if the image used to generate the container is not present on the host system, it is automatically downloaded from a repository (by default the docker.io repository) using the docker pull command.

CentOS 8

Connect to your CentOS_10.0.2.45_SSH VM from your Debian_10.0.2.46_SSH VM :

root@debian11:~# ssh -l trainee 10.0.2.45
The authenticity of host '10.0.2.45 (10.0.2.45)' can't be established.
ECDSA key fingerprint is SHA256:Q7T/CP0SLiMbMAIgVzTuEHegYS/spPE5zzQchCHD5Vw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.2.45' (ECDSA) to the list of known hosts.
trainee@10.0.2.45's password: trainee
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Wed Nov 15 05:24:16 2023 from 10.0.2.1
[trainee@centos8 ~]$

Become the root user:

[trainee@centos8 ~]$ su -
Password: fenestros
[root@centos8 ~]# 

Add the docker repository:

[root@centos8 ~]# yum install -y yum-utils
Last metadata expiration check: 0:05:37 ago on Fri 18 Aug 2023 15:53:49 CEST.
Package yum-utils-4.0.21-3.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!

[root@centos8 ~]# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
Adding repo from: https://download.docker.com/linux/centos/docker-ce.repo

Remove the podman package and install Docker :

[root@centos8 ~]# yum remove podman
Dependencies resolved.
======================================================================================
 Package           Arch    Version                                  Repository   Size
======================================================================================
Removing:
 podman            x86_64  3.3.1-9.module_el8.5.0+988+b1f0b741      @appstream   48 M
Removing dependent packages:
 cockpit-podman    noarch  33-1.module_el8.5.0+890+6b136101         @appstream  438 k
Removing unused dependencies:
 conmon            x86_64  2:2.0.29-1.module_el8.5.0+890+6b136101   @appstream  164 k
 podman-catatonit  x86_64  3.3.1-9.module_el8.5.0+988+b1f0b741      @appstream  760 k

Transaction Summary
======================================================================================
Remove  4 Packages

Freed space: 49 M
Is this ok [y/N]: y
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                              1/1 
  Running scriptlet: cockpit-podman-33-1.module_el8.5.0+890+6b136101.noarch       1/1 
  Erasing          : cockpit-podman-33-1.module_el8.5.0+890+6b136101.noarch       1/4 
  Erasing          : podman-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_64            2/4 
  Running scriptlet: podman-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_64            2/4 
  Erasing          : podman-catatonit-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_6   3/4 
  Erasing          : conmon-2:2.0.29-1.module_el8.5.0+890+6b136101.x86_64         4/4 
  Running scriptlet: conmon-2:2.0.29-1.module_el8.5.0+890+6b136101.x86_64         4/4 
  Verifying        : cockpit-podman-33-1.module_el8.5.0+890+6b136101.noarch       1/4 
  Verifying        : conmon-2:2.0.29-1.module_el8.5.0+890+6b136101.x86_64         2/4 
  Verifying        : podman-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_64            3/4 
  Verifying        : podman-catatonit-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_6   4/4 
Installed products updated.

Removed:
  cockpit-podman-33-1.module_el8.5.0+890+6b136101.noarch                              
  conmon-2:2.0.29-1.module_el8.5.0+890+6b136101.x86_64                                
  podman-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_64                                   
  podman-catatonit-3.3.1-9.module_el8.5.0+988+b1f0b741.x86_64                         

Complete!
[root@centos8 ~]# yum install docker-ce docker-ce-cli containerd.io --allowerasing
Last metadata expiration check: 0:05:43 ago on Fri 18 Aug 2023 16:04:20 CEST.
Dependencies resolved.
======================================================================================
 Package Arch Version Repository Size
======================================================================================
Installing:
 containerd.io x86_64 1.6.22-3.1.el8 docker-ce-stable 34 M
     replacing runc.x86_64 1.0.2-1.module_el8.5.0+911+f19012f9
 docker-ce x86_64 3:24.0.5-1.el8 docker-ce-stable 24 M
 docker-ce-cli x86_64 1:24.0.5-1.el8 docker-ce-stable 7.2 M
Installing dependencies:
 docker-ce-rootless-extras x86_64 24.0.5-1.el8 docker-ce-stable 4.9 M
 libcgroup x86_64 0.41-19.el8 baseos 70 k
Installing weak dependencies:
 docker-buildx-plugin x86_64 0.11.2-1.el8 docker-ce-stable 13 M
 docker-compose-plugin x86_64 2.20.2-1.el8 docker-ce-stable 13 M
Removing dependent packages:
 buildah x86_64 1.22.3-2.module_el8.5.0+911+f19012f9
                                                               @appstream 28 M
 containers-common noarch 2:1-2.module_el8.5.0+890+6b136101
                                                               @appstream 236 k

Transaction Summary
======================================================================================
Install 7 Packages
Remove 2 Packages

Total download size: 96 M
Is this ok [y/N]: y

Transaction Summary
======================================================================================
Install 7 Packages
Remove 2 Packages

Total download size: 96 M
Is this ok [y/N]: y
Downloading Packages:
(1/7): libcgroup-0.41-19.el8.x86_64.rpm 279 kB/s | 70 kB 00:00    
(2/7): docker-buildx-plugin-0.11.2-1.el8.x86_64.rpm 3.2 MB/s | 13 MB 00:04    
(3/7): docker-ce-cli-24.0.5-1.el8.x86_64.rpm 3.1 MB/s | 7.2 MB 00:02    
(4/7): docker-ce-24.0.5-1.el8.x86_64.rpm 2.0 MB/s | 24 MB 00:11    
(5/7): containerd.io-1.6.22-3.1.el8.x86_64.rpm 1.6 MB/s | 34 MB 00:20    
(6/7): docker-ce-rootless-extras-24.0.5-1.el8.x86_64. 322 kB/s | 4.9 MB 00:15    
(7/7): docker-compose-plugin-2.20.2-1.el8.x86_64.rpm 961 kB/s | 13 MB 00:13    
--------------------------------------------------------------------------------------
Total 3.7 MB/s | 96 MB 00:25     
Docker CE Stable - x86_64 67 kB/s | 1.6 kB 00:00    
Importing GPG key 0x621E9F35:
 Userid : "Docker Release (CE rpm) <docker@docker.com>"
 Fingerprint: 060A 61C5 1B55 8A7F 742B 77AA C52F EB6B 621E 9F35
 From: https://download.docker.com/linux/centos/gpg
Is this ok [y/N]: y
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing : 1/1 
  Installing : docker-compose-plugin-2.20.2-1.el8.x86_64 1/10 
  Running scriptlet: docker-compose-plugin-2.20.2-1.el8.x86_64 1/10 
  Installing: docker-buildx-plugin-0.11.2-1.el8.x86_64 2/10 
  Running scriptlet: docker-buildx-plugin-0.11.2-1.el8.x86_64 2/10 
  Installing: docker-ce-cli-1:24.0.5-1.el8.x86_64 3/10 
  Running scriptlet: docker-ce-cli-1:24.0.5-1.el8.x86_64 3/10 
  Installing: containerd.io-1.6.22-3.1.el8.x86_64 4/10 
  Running scriptlet: containerd.io-1.6.22-3.1.el8.x86_64 4/10 
  Running scriptlet: libcgroup-0.41-19.el8.x86_64 5/10 
  Installing: libcgroup-0.41-19.el8.x86_64 5/10 
  Running scriptlet: libcgroup-0.41-19.el8.x86_64 5/10 
  Installing: docker-ce-rootless-extras-24.0.5-1.el8.x86_64 6/10 
  Running scriptlet: docker-ce-rootless-extras-24.0.5-1.el8.x86_64 6/10 
  Installing: docker-ce-3:24.0.5-1.el8.x86_64 7/10 
  Running scriptlet: docker-ce-3:24.0.5-1.el8.x86_64 7/10 
  Erasing : buildah-1.22.3-2.module_el8.5.0+911+f19012f9.x86_64 8/10 
  Erasing : containers-common-2:1-2.module_el8.5.0+890+6b136101.noar 9/10 
  Obsoleting : runc-1.0.2-1.module_el8.5.0+911+f19012f9.x86_64 10/10 
  Running scriptlet: runc-1.0.2-1.module_el8.5.0+911+f19012f9.x86_64 10/10 
  Verifying : libcgroup-0.41-19.el8.x86_64 1/10 
  Verifying : containerd.io-1.6.22-3.1.el8.x86_64 2/10 
  Verifying : runc-1.0.2-1.module_el8.5.0+911+f19012f9.x86_64 3/10 
  Verifying : docker-buildx-plugin-0.11.2-1.el8.x86_64 4/10 
  Verifying : docker-ce-3:24.0.5-1.el8.x86_64 5/10 
  Verifying : docker-ce-cli-1:24.0.5-1.el8.x86_64 6/10 
  Verifying : docker-ce-rootless-extras-24.0.5-1.el8.x86_64 7/10 
  Verifying: docker-compose-plugin-2.20.2-1.el8.x86_64 8/10 
  Verifying : buildah-1.22.3-2.module_el8.5.0+911+f19012f9.x86_64 9/10 
  Verifying : containers-common-2:1-2.module_el8.5.0+890+6b136101.noar 10/10 
Installed products updated.

Installed:
  containerd.io-1.6.22-3.1.el8.x86_64                                                 
  docker-buildx-plugin-0.11.2-1.el8.x86_64                                            
  docker-ce-3:24.0.5-1.el8.x86_64                                                     
  docker-ce-cli-1:24.0.5-1.el8.x86_64                                                 
  docker-ce-rootless-extras-24.0.5-1.el8.x86_64                                       
  docker-compose-plugin-2.20.2-1.el8.x86_64                                           
  libcgroup-0.41-19.el8.x86_64                                                        
Removed:
  buildah-1.22.3-2.module_el8.5.0+911+f19012f9.x86_64                                 
  containers-common-2:1-2.module_el8.5.0+890+6b136101.noarch                          

Complete!

Then start the docker service :

[root@centos8 ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: d>
   Active: inactive (dead)
     Docs: https://docs.docker.com
[q] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Press the q key

[root@centos8 ~]# systemctl start docker

[root@centos8 ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: d>
   Active: active (running) since Fri 2023-08-18 16:19:35 CEST; 3s ago
     Docs: https://docs.docker.com
 Main PID: 49974 (dockerd)
    Tasks: 13
   Memory: 32.1M
   CGroup: /system.slice/docker.service
           └─49974 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.>

Aug 18 16:19:33 centos8.ittraining.loc systemd[1]: Starting Docker Application Contai>
Aug 18 16:19:33 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:33.5501>
Aug 18 16:19:33 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:33.8396>
Aug 18 16:19:34 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:34.9656>
Aug 18 16:19:35 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:35.1732>
Aug 18 16:19:35 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:35.2581>
Aug 18 16:19:35 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:35.2583>
Aug 18 16:19:35 centos8.ittraining.loc dockerd[49974]: time="2023-08-18T16:19:35.6677>
Aug 18 16:19:35 centos8.ittraining.loc systemd[1]: Started Docker Application Contain>
[q] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Press the q key
[root@centos8 ~]# 

If you want to install a different version, you should first check which versions are available:

[root@centos8 ~]# yum list docker-ce --showduplicates | sort -r
Last metadata expiration check: 0:03:42 ago on Fri 18 Aug 2023 16:11:47 CEST.
Installed Packages
docker-ce.x86_64 3:24.0.5-1.el8 docker-ce-stable 
docker-ce.x86_64 3:24.0.5-1.el8 @docker-ce-stable
docker-ce.x86_64 3:24.0.4-1.el8 docker-ce-stable 
docker-ce.x86_64 3:24.0.3-1.el8 docker-ce-stable 
docker-ce.x86_64 3:24.0.2-1.el8 docker-ce-stable 
docker-ce.x86_64 3:24.0.1-1.el8 docker-ce-stable 
docker-ce.x86_64 3:24.0.0-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.6-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.5-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.4-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.3-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.2-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.1-1.el8 docker-ce-stable 
docker-ce.x86_64 3:23.0.0-1.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.9-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.8-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.7-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.6-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.5-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.4-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.3-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.24-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.2-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.23-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.22-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.21-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.20-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.19-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.18-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.17-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.16-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.15-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.14-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.1-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.13-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.12-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.11-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.10-3.el8 docker-ce-stable 
docker-ce.x86_64 3:20.10.0-3.el8 docker-ce-stable 
docker-ce.x86_64 3:19.03.15-3.el8 docker-ce-stable 
docker-ce.x86_64 3:19.03.14-3.el8 docker-ce-stable 
docker-ce.x86_64 3:19.03.13-3.el8 docker-ce-stable 
Available Packages

[root@centos8 ~]# yum list docker-ce-cli --showduplicates | sort -r
Last metadata expiration check: 0:08:33 ago on Thu 14 Dec 2023 09:52:33 EST.
docker-ce-cli.x86_64              1:24.0.7-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.6-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.5-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.4-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.3-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.2-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.1-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:24.0.0-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.6-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.5-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.4-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.3-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.2-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.1-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:23.0.0-1.el8                docker-ce-stable
docker-ce-cli.x86_64              1:20.10.9-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.8-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.7-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.6-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.5-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.4-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.3-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.24-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.2-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.23-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.22-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.21-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.20-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.19-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.18-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.17-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.16-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.15-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.14-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.1-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:20.10.13-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.12-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.11-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.10-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:20.10.0-3.el8               docker-ce-stable
docker-ce-cli.x86_64              1:19.03.15-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:19.03.14-3.el8              docker-ce-stable
docker-ce-cli.x86_64              1:19.03.13-3.el8              docker-ce-stable
Available Packages

In the event that you want to install Docker version 24.0.4, the installation command would become:

# yum install docker-ce-3:24.0.4-1.el8 docker-ce-cli-1:24.0.4-1.el8 containerd.io --allowerasing

If you prefer to use the Docker installation script, you should download it first:

Important - Note that these scripts should not be used in a production environment.

[root@centos8 ~]# curl -fsSL https://get.docker.com -o get-docker.sh

[root@centos8 ~]# ls
anaconda-ks.cfg Downloads Music Videos
CentOS-8.1.1911-x86_64-boot.iso get-docker.sh Pictures
Desktop home Public
Documents initial-setup-ks.cfg Templates

Next, we need to run the script:

[root@centos8 ~]# chmod +x get-docker.sh

[root@centos8 ~]# ./get-docker.sh 
# Executing docker install script, commit: c2de0811708b6d9015ed1a2c80f02c9b70c8ce7b
Warning: the "docker" command appears to already exist on this system.

If you already have Docker installed, this script can cause trouble, which is
why we're displaying this warning and provide the opportunity to cancel the
installation.

If you installed the current Docker package using this script and are using it
again to update Docker, you can safely ignore this message.

You may press Ctrl+C now to abort this script.
+ sleep 20
^C

Important - Note the use of ^C to NOT continue executing the script.

Start a hello-world image container:

[root@centos8 ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
719385e32844: Pull complete 
Digest: sha256:dcba6daec718f547568c562956fa47e1b03673dd010fe6ee58ca806767031d1c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

Important - Note that if the image used to generate the container is not present on the host system, it is automatically downloaded from a repository ( by default the docker.io repository) using the docker pull command.

Exit from your CentOS_10.0.2.45_SSH VM:

[root@centos8 ~]# exit
logout
[trainee@centos8 ~]$ exit
logout
Connection to 10.0.2.45 closed.
root@debian11:~#

1.2 - Starting a Container

Start a container from the ubuntu:latest image in interactive mode using the -i and -t options, passing bash as an argument so that it is launched when the container is started :

root@debian11:~# docker run -it ubuntu bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
b237fe92c417: Pull complete 
Digest: sha256:ec050c32e4a6085b423d36ecd025c0d3ff00c38ab93a3d71a460ff1c44fa6d77
Status: Downloaded newer image for ubuntu:latest

root@83b0d8979a33:/# ls
bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var

root@83b0d8979a33:/# cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04.3 LTS"

Important - Note that in this case the container is launched with bash as the argument, which will launch /bin/bash in the container.

View the list of packages installed in the ubuntu container:

root@83b0d8979a33:/# dpkg -l
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                    Version                                 Architecture Description
+++-=======================-=======================================-============-========================================================================
ii  adduser                 3.118ubuntu5                            all          add and remove users and groups
ii  apt                     2.4.9                                   amd64        commandline package manager
ii  base-files              12ubuntu4.4                             amd64        Debian base system miscellaneous files
ii  base-passwd             3.5.52build1                            amd64        Debian base system master password and group files
ii  bash                    5.1-6ubuntu1                            amd64        GNU Bourne Again SHell
ii  bsdutils                1:2.37.2-4ubuntu3                       amd64        basic utilities from 4.4BSD-Lite
ii  coreutils               8.32-4.1ubuntu1                         amd64        GNU core utilities
ii  dash                    0.5.11+git20210903+057cd650a4ed-3build1 amd64        POSIX-compliant shell
ii  debconf                 1.5.79ubuntu1                           all          Debian configuration management system
ii  debianutils             5.5-1ubuntu2                            amd64        Miscellaneous utilities specific to Debian
ii  diffutils               1:3.8-0ubuntu2                          amd64        File comparison utilities
ii  dpkg                    1.21.1ubuntu2.2                         amd64        Debian package management system
ii  e2fsprogs               1.46.5-2ubuntu1.1                       amd64        ext2/ext3/ext4 file system utilities
ii  findutils               4.8.0-1ubuntu3                          amd64        utilities for finding files--find, xargs
ii  gcc-12-base:amd64       12.3.0-1ubuntu1~22.04                   amd64        GCC, the GNU Compiler Collection (base package)
ii  gpgv                    2.2.27-3ubuntu2.1                       amd64        GNU privacy guard - signature verification tool
ii  grep                    3.7-1build1                             amd64        GNU grep, egrep and fgrep
ii  gzip                    1.10-4ubuntu4.1                         amd64        GNU compression utilities
ii  hostname                3.23ubuntu2                             amd64        utility to set/show the host name or domain name
ii  init-system-helpers     1.62                                    all          helper tools for all init systems
ii  libacl1:amd64           2.3.1-1                                 amd64        access control list - shared library
ii  libapt-pkg6.0:amd64     2.4.9                                   amd64        package management runtime library
ii  libattr1:amd64          1:2.5.1-1build1                         amd64        extended attribute handling - shared library
ii  libaudit-common         1:3.0.7-1build1                         all          Dynamic library for security auditing - common files
ii  libaudit1:amd64         1:3.0.7-1build1                         amd64        Dynamic library for security auditing
ii  libblkid1:amd64         2.37.2-4ubuntu3                         amd64        block device ID library
ii  libbz2-1.0:amd64        1.0.8-5build1                           amd64        high-quality block-sorting file compressor library - runtime
ii  libc-bin                2.35-0ubuntu3.1                         amd64        GNU C Library: Binaries
ii  libc6:amd64             2.35-0ubuntu3.1                         amd64        GNU C Library: Shared libraries
ii  libcap-ng0:amd64        0.7.9-2.2build3                         amd64        An alternate POSIX capabilities library
ii  libcap2:amd64           1:2.44-1ubuntu0.22.04.1                 amd64        POSIX 1003.1e capabilities (library)
ii  libcom-err2:amd64       1.46.5-2ubuntu1.1                       amd64        common error description library
ii  libcrypt1:amd64         1:4.4.27-1                              amd64        libcrypt shared library
ii  libdb5.3:amd64          5.3.28+dfsg1-0.8ubuntu3                 amd64        Berkeley v5.3 Database Libraries [runtime]
ii  libdebconfclient0:amd64 0.261ubuntu1                            amd64        Debian Configuration Management System (C-implementation library)
ii  libext2fs2:amd64        1.46.5-2ubuntu1.1                       amd64        ext2/ext3/ext4 file system libraries
ii  libffi8:amd64           3.4.2-4                                 amd64        Foreign Function Interface library runtime
ii  libgcc-s1:amd64         12.3.0-1ubuntu1~22.04                   amd64        GCC support library
ii  libgcrypt20:amd64       1.9.4-3ubuntu3                          amd64        LGPL Crypto library - runtime library
ii  libgmp10:amd64          2:6.2.1+dfsg-3ubuntu1                   amd64        Multiprecision arithmetic library
ii  libgnutls30:amd64       3.7.3-4ubuntu1.2                        amd64        GNU TLS library - main runtime library
ii  libgpg-error0:amd64     1.43-3                                  amd64        GnuPG development runtime library
ii  libgssapi-krb5-2:amd64  1.19.2-2ubuntu0.2                       amd64        MIT Kerberos runtime libraries - krb5 GSS-API Mechanism
ii  libhogweed6:amd64       3.7.3-1build2                           amd64        low level cryptographic library (public-key cryptos)
ii  libidn2-0:amd64         2.3.2-2build1                           amd64        Internationalized domain names (IDNA2008/TR46) library
ii  libk5crypto3:amd64      1.19.2-2ubuntu0.2                       amd64        MIT Kerberos runtime libraries - Crypto Library
ii  libkeyutils1:amd64      1.6.1-2ubuntu3                          amd64        Linux Key Management Utilities (library)
ii  libkrb5-3:amd64         1.19.2-2ubuntu0.2                       amd64        MIT Kerberos runtime libraries
ii  libkrb5support0:amd64   1.19.2-2ubuntu0.2                       amd64        MIT Kerberos runtime libraries - Support library
ii  liblz4-1:amd64          1.9.3-2build2                           amd64        Fast LZ compression algorithm library - runtime
ii  liblzma5:amd64          5.2.5-2ubuntu1                          amd64        XZ-format compression library
ii  libmount1:amd64         2.37.2-4ubuntu3                         amd64        device mounting library
ii  libncurses6:amd64       6.3-2ubuntu0.1                          amd64        shared libraries for terminal handling
ii  libncursesw6:amd64      6.3-2ubuntu0.1                          amd64        shared libraries for terminal handling (wide character support)
ii  libnettle8:amd64        3.7.3-1build2                           amd64        low level cryptographic library (symmetric and one-way cryptos)
ii  libnsl2:amd64           1.3.0-2build2                           amd64        Public client interface for NIS(YP) and NIS+
ii  libp11-kit0:amd64       0.24.0-6build1                          amd64        library for loading and coordinating access to PKCS#11 modules - runtime
ii  libpam-modules:amd64    1.4.0-11ubuntu2.3                       amd64        Pluggable Authentication Modules for PAM
ii  libpam-modules-bin      1.4.0-11ubuntu2.3                       amd64        Pluggable Authentication Modules for PAM - helper binaries
ii  libpam-runtime          1.4.0-11ubuntu2.3                       all          Runtime support for the PAM library
ii  libpam0g:amd64          1.4.0-11ubuntu2.3                       amd64        Pluggable Authentication Modules library
ii  libpcre2-8-0:amd64      10.39-3ubuntu0.1                        amd64        New Perl Compatible Regular Expression Library- 8 bit runtime files
ii  libpcre3:amd64          2:8.39-13ubuntu0.22.04.1                amd64        Old Perl 5 Compatible Regular Expression Library - runtime files
ii  libprocps8:amd64        2:3.3.17-6ubuntu2                       amd64        library for accessing process information from /proc
ii  libseccomp2:amd64       2.5.3-2ubuntu2                          amd64        high level interface to Linux seccomp filter
ii  libselinux1:amd64       3.3-1build2                             amd64        SELinux runtime shared libraries
ii  libsemanage-common      3.3-1build2                             all          Common files for SELinux policy management libraries
ii  libsemanage2:amd64      3.3-1build2                             amd64        SELinux policy management library
ii  libsepol2:amd64         3.3-1build1                             amd64        SELinux library for manipulating binary security policies
ii  libsmartcols1:amd64     2.37.2-4ubuntu3                         amd64        smart column output alignment library
ii  libss2:amd64            1.46.5-2ubuntu1.1                       amd64        command-line interface parsing library
ii  libssl3:amd64           3.0.2-0ubuntu1.10                       amd64        Secure Sockets Layer toolkit - shared libraries
ii  libstdc++6:amd64        12.3.0-1ubuntu1~22.04                   amd64        GNU Standard C++ Library v3
ii  libsystemd0:amd64       249.11-0ubuntu3.9                       amd64        systemd utility library
ii  libtasn1-6:amd64        4.18.0-4build1                          amd64        Manage ASN.1 structures (runtime)
ii  libtinfo6:amd64         6.3-2ubuntu0.1                          amd64        shared low-level terminfo library for terminal handling
ii  libtirpc-common         1.3.2-2ubuntu0.1                        all          transport-independent RPC library - common files
ii  libtirpc3:amd64         1.3.2-2ubuntu0.1                        amd64        transport-independent RPC library
ii  libudev1:amd64          249.11-0ubuntu3.9                       amd64        libudev shared library
ii  libunistring2:amd64     1.0-1                                   amd64        Unicode string library for C
ii  libuuid1:amd64          2.37.2-4ubuntu3                         amd64        Universally Unique ID library
ii  libxxhash0:amd64        0.8.1-1                                 amd64        shared library for xxhash
ii  libzstd1:amd64          1.4.8+dfsg-3build1                      amd64        fast lossless compression algorithm
ii  login                   1:4.8.1-2ubuntu2.1                      amd64        system login tools
ii  logsave                 1.46.5-2ubuntu1.1                       amd64        save the output of a command in a log file
ii  lsb-base                11.1.0ubuntu4                           all          Linux Standard Base init script functionality
ii  mawk                    1.3.4.20200120-3                        amd64        Pattern scanning and text processing language
ii  mount                   2.37.2-4ubuntu3                         amd64        tools for mounting and manipulating filesystems
ii  ncurses-base            6.3-2ubuntu0.1                          all          basic terminal type definitions
ii  ncurses-bin             6.3-2ubuntu0.1                          amd64        terminal-related programs and man pages
ii  passwd                  1:4.8.1-2ubuntu2.1                      amd64        change and administer password and group data
ii  perl-base               5.34.0-3ubuntu1.2                       amd64        minimal Perl system
ii  procps                  2:3.3.17-6ubuntu2                       amd64        /proc file system utilities
ii  sed                     4.8-1ubuntu2                            amd64        GNU stream editor for filtering/transforming text
ii  sensible-utils          0.0.17                                  all          Utilities for sensible alternative selection
ii  sysvinit-utils          3.01-1ubuntu1                           amd64        System-V-like utilities
ii  tar                     1.34+dfsg-1ubuntu0.1.22.04.1            amd64        GNU version of the tar archiving utility
ii  ubuntu-keyring          2021.03.26                              all          GnuPG keys of the Ubuntu archive
ii  usrmerge                25ubuntu2                               all          Convert the system to the merged /usr directories scheme
ii  util-linux              2.37.2-4ubuntu3                         amd64        miscellaneous system utilities
ii  zlib1g:amd64            1:1.2.11.dfsg-2ubuntu9.2                amd64        compression library - runtime
root@83b0d8979a33:/# exit
exit
root@debian11:~# 

The options for the docker run command can be viewed with the command :

root@debian11:~# docker run --help

Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Create and run a new container from an image

Aliases:
  docker container run, docker run

Options:
      --add-host list Add a custom host-to-IP mapping (host:ip)
      --annotation map Add an annotation to the container (passed through to the OCI runtime) (default map[])
  -a, --attach list Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list Block IO weight (relative device weight) (default [])
      --cap-add list Add Linux capabilities
      --cap-drop list Drop Linux capabilities
      --cgroup-parent string Optional parent cgroup for the container
      --cgroupns string Cgroup namespace to use (host|private)
                                       host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --cidfile string Write the container ID to the file
      --cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int Limit CPU real-time period in microseconds
      --cpu-rt-runtime int Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int CPU shares (relative weight)
      --cpus decimal Number of CPUs
      --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
  -d, --detach Run container in background and print container ID
      --detach-keys string Override the key sequence for detaching a container
      --device list Add a host device to the container
      --device-cgroup-rule list Add a rule to the cgroup allowed devices list
      --device-read-bps list Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list Limit read rate (IO per second) from a device (default [])
      --device-write-bps list Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list Limit write rate (IO per second) to a device (default [])
      --disable-content-trust Skip image verification (default true)
      --dns list Set custom DNS servers
      --dns-option list Set DNS options
      --dns-search list Set custom DNS search domains
      --domainname string Container NIS domain name
      --entrypoint string Overwrite the default ENTRYPOINT of the image
  -e, --env list Set environment variables
      --env-file list Read in a file of environment variables
      --expose list Expose a port or a range of ports
      --gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list Add additional groups to join
      --health-cmd string Command to run to check health
      --health-interval duration Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int Consecutive failures needed to report unhealthy
      --health-start-period duration Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help Print usage
  -h, --hostname string Container host name
      --init Run an init inside the container that forwards signals and reaps processes
  -i, --interactive Keep STDIN open even if not attached
      --ip string IPv4 address (e.g., 172.30.100.104)
      --ip6 string IPv6 address (e.g., 2001:db8::33)
      --ipc string IPC mode to use
      --isolation string Container isolation technology
      --kernel-memory bytes Kernel memory limit
  -l, --label list Set meta data on a container
      --label-file list Read in a line delimited file of labels
      --link list Add link to another container
      --link-local-ip list Container IPv4/IPv6 link-local addresses
      --log-driver string Logging driver for the container
      --log-opt list Log driver options
      --mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes Memory limit
      --memory-reservation bytes Memory soft limit
      --memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
      --mount mount Attach a filesystem mount to the container
      --name string Assign a name to the container
      --network network Connect a container to a network
      --network-alias list Add network-scoped alias for the container
      --no-healthcheck Disable any container-specified HEALTHCHECK
      --oom-kill-disable Disable OOM Killer
      --oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
      --pid string PID namespace to use
      --pids-limit int Tune container pids limit (set -1 for unlimited)
      --platform string Set platform if server is multi-platform capable
      --privileged Give extended privileges to this container
  -p, --publish list Publish a container's port(s) to the host
  -P, --publish-all Publish all exposed ports to random ports
      --pull string Pull image before running ("always", "missing", "never") (default "missing")
  -q, --quiet Suppress the pull output
      --read-only Mount the container's root filesystem as read only
      --restart string Restart policy to apply when a container exits (default "no")
      --rm Automatically remove the container when it exits
      --runtime string Runtime to use for this container
      --security-opt list Security Options
      --shm-size bytes Size of /dev/shm
      --sig-proxy Proxy received signals to the process (default true)
      --stop-signal string Signal to stop the container
      --stop-timeout int Timeout (in seconds) to stop a container
      --storage-opt list Storage driver options for the container
      --sysctl map Sysctl options (default map[])
      --tmpfs list Mount a tmpfs directory
  -t, --tty Allocate a pseudo-TTY
      --ulimit ulimit Ulimit options (default [])
  -u, --user string Username or UID (format: <name|uid>[:<group|gid>])
      --userns string User namespace to use
      --uts string UTS namespace to use
  -v, --volume list Bind mount a volume
      --volume-driver string Optional volume driver for the container
      --volumes-from list Mount volumes from the specified container(s)
  -w, --workdir string Working directory inside the container

1.3 - Viewing the List of Containers and Images

To view all containers, use the docker ps command with the -a option:

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND    CREATED         STATUS                     PORTS     NAMES
83b0d8979a33   ubuntu        "bash"     4 minutes ago   Exited (0) 2 minutes ago             upbeat_diffie
5d17db3bbb20   hello-world   "/hello"   16 hours ago    Exited (0) 16 hours ago              charming_hoover

Important - Note that each container can be referenced by its CONTAINER ID or by its NAME.

To view the list of images, use the docker images command:

root@debian11:~# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
ubuntu        latest    01f29b872827   2 weeks ago    77.8MB
hello-world   latest    9c7a54a9a43c   3 months ago   13.3kB

Important - Note that each image is referenced by its IMAGE ID.

1.4 - Searching for an Image in a Repository

To search for a docker image in the default repository, use the docker search command:

root@debian11:~# docker search --filter=stars=5 centos
NAME                        DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
centos                      DEPRECATED; The official build of CentOS.       7627      [OK]       
kasmweb/centos-7-desktop    CentOS 7 desktop for Kasm Workspaces            40                   
couchbase/centos7-systemd   centos7-systemd images with additional debug…   8                    [OK]
dokken/centos-7             CentOS 7 image for kitchen-dokken               5                    
eclipse/centos_jdk8         CentOS, JDK8, Maven 3, git, curl, nmap, mc, …   5                    [OK]
dokken/centos-stream-9                                                      6                                         

Important - Note that each image is referenced by the NAME column. The NAME is in the format repository/maintainer/name except in the case where it is the “official” image of the publisher in which case the format is simply repository/name. The notion of STARS comes from Docker Hub and is an indication of community satisfaction.

1.5 - Deleting a Container

To remove a container, the docker rm command should be used, referencing the container either by its NAME or by its CONTAINER ID :

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND    CREATED         STATUS                     PORTS     NAMES
83b0d8979a33   ubuntu        "bash"     5 minutes ago   Exited (0) 4 minutes ago             upbeat_diffie
5d17db3bbb20   hello-world   "/hello"   16 hours ago    Exited (0) 16 hours ago              charming_hoover

root@debian11:~# docker rm upbeat_diffie
upbeat_diffie

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND    CREATED        STATUS                    PORTS     NAMES
5d17db3bbb20   hello-world   "/hello"   16 hours ago   Exited (0) 16 hours ago             charming_hoover

root@debian11:~# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
ubuntu        latest    01f29b872827   2 weeks ago    77.8MB
hello-world   latest    9c7a54a9a43c   3 months ago   13.3kB

Important - Note that when using the CONTAINER ID, it is not necessary to use the whole ID. For example, in the case above, the CONTAINER ID of the upbeat_diffie container was 83b0d8979a33. The delete command could have used 83b0d8979a33, 83b0d8 or even 83b.

1.6 -Creating an Image from a Modified Container

Modify the ubuntu container:

root@debian11:~# docker run -it ubuntu

root@4377355f88c2:/# ls 
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@4377355f88c2:/# rm -rf /home

root@4377355f88c2:/# ls
bin  boot  dev  etc  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@4377355f88c2:/# exit
exit
root@debian11:~#
</code

<WRAP center round important 50%>
**Important** - Note here the deletion of the **home** directory in the **4377355f88c2** container.
</WRAP>

See the difference between the container and the base image:

<code>
root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED              STATUS                          PORTS     NAMES
4377355f88c2   ubuntu        "/bin/bash"   About a minute ago   Exited (0) About a minute ago             romantic_northcutt
5d17db3bbb20   hello-world   "/hello"      16 hours ago         Exited (0) 16 hours ago                   charming_hoover

root@debian11:~# docker diff romantic_northcutt
C /root
A /root/.bash_history
D /home

Important - The output of the docker diff command contains letters with the following meanings: C = Create, D = Delete, A = Add.

Create another container from the base image:

root@debian11:~# docker run -it ubuntu

root@e4caf92a5ceb:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@e4caf92a5ceb:/# exit
exit

root@debian11:~# 

Important - In this new container, the /home directory is present given that it was generated from the original image, unchanged since it was compiled.

Now create the ubuntu_1 image from the first ubuntu container (in the case below - romantic_northcutt) using the docker commit command:

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED          STATUS                      PORTS     NAMES
e4caf92a5ceb   ubuntu        "/bin/bash"   44 seconds ago   Exited (0) 32 seconds ago             affectionate_ishizaka
4377355f88c2   ubuntu        "/bin/bash"   6 hours ago      Exited (0) 6 hours ago                romantic_northcutt
5d17db3bbb20   hello-world   "/hello"      22 hours ago     Exited (0) 22 hours ago               charming_hoover

root@debian11:~# docker commit romantic_northcutt ubuntu_1
sha256:50d66f88b992b65d0a38c4b662fbdcc906477916240a90d214b35a42b939ea5f

root@debian11:~# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
ubuntu_1      latest    50d66f88b992   13 seconds ago   77.8MB
ubuntu        latest    01f29b872827   2 weeks ago      77.8MB
hello-world   latest    9c7a54a9a43c   3 months ago     13.3kB

root@debian11:~#

1.7 - Deleting an Image

Now create a container from the new ubuntu_1 image:

root@debian11:~# docker run -it ubuntu_1

root@86e777ebaf2b:/# ls
bin  boot  dev  etc  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@86e777ebaf2b:/# exit
exit

root@debian11:~# 

Important - Note the absence of the home directory in the 904215fb79b4 container.

Try deleting the ubuntu_1 image:

root@debian11:~# docker rmi ubuntu_1
Error response from daemon: conflict: unable to remove repository reference "ubuntu_1" (must force) - container 86e777ebaf2b is using its referenced image 50d66f88b992

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED              STATUS                          PORTS     NAMES
86e777ebaf2b   ubuntu_1      "/bin/bash"   About a minute ago   Exited (0) About a minute ago             focused_colden
e4caf92a5ceb   ubuntu        "/bin/bash"   7 minutes ago        Exited (0) 7 minutes ago                  affectionate_ishizaka
4377355f88c2   ubuntu        "/bin/bash"   6 hours ago          Exited (0) 6 hours ago                    romantic_northcutt
5d17db3bbb20   hello-world   "/hello"      22 hours ago         Exited (0) 22 hours ago                   charming_hoover

Important - Note that it is not possible to delete the ubuntu_1 image while the 86e777ebaf2b container is active.

Now delete the container identified by the error message (in the case above - focused_colden) as well as the ubuntu_1 image:

root@debian11:~# docker rm focused_colden
focused_colden

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED          STATUS                     PORTS     NAMES
e4caf92a5ceb   ubuntu        "/bin/bash"   10 minutes ago   Exited (0) 9 minutes ago             affectionate_ishizaka
4377355f88c2   ubuntu        "/bin/bash"   6 hours ago      Exited (0) 6 hours ago               romantic_northcutt
5d17db3bbb20   hello-world   "/hello"      22 hours ago     Exited (0) 22 hours ago              charming_hoover

root@debian11:~# docker rmi ubuntu_1
Untagged: ubuntu_1:latest
Deleted: sha256:50d66f88b992b65d0a38c4b662fbdcc906477916240a90d214b35a42b939ea5f
Deleted: sha256:c5fdbe1dd17356fd868456c44949e0ca50c78a610a8917d7ad6ab372aeebce20

root@debian11:~# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
ubuntu        latest    01f29b872827   2 weeks ago    77.8MB
hello-world   latest    9c7a54a9a43c   3 months ago   13.3kB

To be able to delete all containers, list them by their Container ID :

root@debian11:~# docker ps -aq
e4caf92a5ceb
4377355f88c2
5d17db3bbb20

Delete all containers:

root@debian11:~# docker rm `docker ps -aq`
e4caf92a5ceb
4377355f88c2
5d17db3bbb20

root@debian11:~# docker ps -aq

root@debian11:~# 

To delete a container as soon as it finishes running, use the –rm option:

root@debian11:~# docker run -it --rm ubuntu

root@3b3d4d7be82b:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@3b3d4d7be82b:/# exit
exit

root@debian11:~# docker ps -aq

root@debian11:~#

1.8 - Creating a Container with a Specific Name

Now create a container with a specific name:

root@debian11:~# docker run -it --name=ittraining ubuntu

root@d838ea83033e:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

root@d838ea83033e:/# exit
exit

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
d838ea83033e   ubuntu    "/bin/bash"   12 seconds ago   Exited (0) 4 seconds ago             ittraining

To obtain information about a container, use the docker inspect command:

root@debian11:~# docker inspect ittraining
[
    {
        "Id": "d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3",
        "Created": "2023-08-19T11:47:56.464134219Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-08-19T11:47:57.979606971Z",
            "FinishedAt": "2023-08-19T11:48:04.066624168Z"
        },
        "Image": "sha256:01f29b872827fa6f9aed0ea0b2ede53aea4ad9d66c7920e81a8db6d1fd9ab7f9",
        "ResolvConfPath": "/var/lib/docker/containers/d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3/hostname",
        "HostsPath": "/var/lib/docker/containers/d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3/hosts",
        "LogPath": "/var/lib/docker/containers/d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3/d838ea83033e6a5b324676ed6734e7ff9c69084dd453c52eedd367f31bcb83f3-json.log",
        "Name": "/ittraining",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                59,
                210
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/b8f594ac72f3c9a57be0645a8d5686259ff8799d341626458808d999e35fbf8f-init/diff:/var/lib/docker/overlay2/f932b6b3764a556a570060fd607da5e9082eb6d816e3568574a6104ebc80df5e/diff",
                "MergedDir": "/var/lib/docker/overlay2/b8f594ac72f3c9a57be0645a8d5686259ff8799d341626458808d999e35fbf8f/merged",
                "UpperDir": "/var/lib/docker/overlay2/b8f594ac72f3c9a57be0645a8d5686259ff8799d341626458808d999e35fbf8f/diff",
                "WorkDir": "/var/lib/docker/overlay2/b8f594ac72f3c9a57be0645a8d5686259ff8799d341626458808d999e35fbf8f/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d838ea83033e",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "ubuntu",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.opencontainers.image.ref.name": "ubuntu",
                "org.opencontainers.image.version": "22.04"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "8896374679af4eed6bc5825722ef4f1d802910fba2d12cd87c777fad1338ebac",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/8896374679af",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "33b1d61a638b6114462bd420314077791ed32b132a4536ad7725420a58e11d3f",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

1.9 - Executing a Command in a Container

To execute a specific command in a container, pass the command as an argument:

root@debian11:~# docker run --rm ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=9b7b7547c023
HOME=/root

root@debian11:~#

1.10 - Injecting Environment Variables into a Container

To inject one or more environment variables into a container, use a file:

root@debian11:~# vi env.list

root@debian11:~# cat env.list
EDITOR=vim
HOSTNAME=ubuntudocker
root@debian11:~# docker run --rm --env-file=env.list ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ubuntudocker
EDITOR=vim
HOME=/root

root@debian11:~#

1.11 - Modifying the Hostname of a Container

To change the hostname of a container, use the -h option:

root@debian11:~# docker run -it --rm -h ubuntudocker ubuntu

root@ubuntudocker:/# hostname
ubuntudocker

root@ubuntudocker:/# exit
exit

1.12 - Mapping Ports of a Container

Start a nginx container on port localhost 81 :

root@debian11:~# docker run -it -p 81:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
52d2b7f179e3: Pull complete 
fd9f026c6310: Pull complete 
055fa98b4363: Pull complete 
96576293dd29: Pull complete 
a7c4092be904: Pull complete 
e3b6889c8954: Pull complete 
da761d9a302b: Pull complete 
Digest: sha256:104c7c5c54f2685f0f46f3be607ce60da7085da3eaa5ad22d3d9f01594295e9c
Status: Downloaded newer image for nginx:latest

^C

root@debian11:~#

Note that using ^C killed the container process:

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                     PORTS     NAMES
37cb0af1e97f   nginx     "/docker-entrypoint.…"   46 seconds ago   Created                              intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              5 minutes ago    Exited (0) 5 minutes ago             ittraining

1.13 - Starting a Container in Detached mode

Now start the nginx container in detached mode using the -d option:

root@debian11:~# docker run -d -p 81:80 nginx
5c2fe852965f700fff2d11baff034557c4956a7cd5eb54c51967d362415a76b4

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED              STATUS                     PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   8 seconds ago        Up 6 seconds               0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   About a minute ago   Created                                                        intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              5 minutes ago        Exited (0) 5 minutes ago                                       ittraining

1.14 - Accessing Container Services from the Outside

Install the lynx text browser:

root@debian11:~# apt-get install lynx
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libopengl0 linux-headers-5.10.0-15-amd64 linux-headers-5.10.0-15-common
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
  lynx-common
The following NEW packages will be installed:
  lynx lynx-common
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,844 kB of archives.
After this operation, 5,768 kB of additional disk space will be used.
Do you want to continue? [Y/n] y

Check that nginx responds to requests :

root@debian11:~# lynx --dump http://localhost:81
                               Welcome to nginx!

   If you see this page, the nginx web server is successfully installed
   and working. Further configuration is required.

   For online documentation and support please refer to [1]nginx.org.
   Commercial support is available at [2]nginx.com.

   Thank you for using nginx.

References

   1. http://nginx.org/
   2. http://nginx.com/

root@debian11:~#

1.15 - Stopping and Starting a Container

Stop the nginx container:

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS                     PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   2 minutes ago   Up 2 minutes               0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   3 minutes ago   Created                                                        intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              8 minutes ago   Exited (0) 8 minutes ago 
                                      ittraining
root@debian11:~# docker stop 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS                     PORTS     NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   3 minutes ago   Exited (0) 5 seconds ago             priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   4 minutes ago   Created                              intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              8 minutes ago   Exited (0) 8 minutes ago             ittraining

Start the nginx container again:

root@debian11:~# docker start 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS                     PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   3 minutes ago   Up 2 seconds               0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   4 minutes ago   Created                                                        intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              9 minutes ago   Exited (0) 9 minutes ago                                       ittraining

1.16 - Using Signals with a Container

Use a signal to kill the nginx container process:

root@debian11:~# docker kill -s 9 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                       PORTS     NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   5 minutes ago    Exited (137) 5 seconds ago             priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   6 minutes ago    Created                                intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              11 minutes ago   Exited (0) 11 minutes ago              ittraining

Restart the container:

root@debian11:~# docker start 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   6 minutes ago    Up 2 seconds                0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   7 minutes ago    Created                                                         intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              11 minutes ago   Exited (0) 11 minutes ago                                       ittraining

root@debian11:~# docker restart 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   6 minutes ago    Up 2 seconds                0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   7 minutes ago    Created                                                         intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              12 minutes ago   Exited (0) 12 minutes ago                                       ittraining

1.17 - Force Delete a Running Container

Delete a running container:

root@debian11:~# docker rm 5c2f
Error response from daemon: You cannot remove a running container 5c2fe852965f700fff2d11baff034557c4956a7cd5eb54c51967d362415a76b4. Stop the container before attempting removal or force remove

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                               NAMES
5c2fe852965f   nginx     "/docker-entrypoint.…"   7 minutes ago    Up 58 seconds               0.0.0.0:81->80/tcp, :::81->80/tcp   priceless_yonath
37cb0af1e97f   nginx     "/docker-entrypoint.…"   8 minutes ago    Created                                                         intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              13 minutes ago   Exited (0) 12 minutes ago                                       ittraining

root@debian11:~# docker rm -f 5c2f
5c2f

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS     NAMES
37cb0af1e97f   nginx     "/docker-entrypoint.…"   8 minutes ago    Created                               intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              13 minutes ago   Exited (0) 13 minutes ago             ittraining

1.18 - Simple Volume Usage

Create the index.html file and place it in the /root/www directory:

root@debian11:~# mkdir www

root@debian11:~# vi index.html

root@debian11:~# cat index.html
<html>
<body>
<center>nginx site home</center>
</body>
</html>

root@debian11:~# mv index.html www/

root@debian11:~#

Tell the container that its /usr/share/nginx/html/ directory is replaced by the /root/www/ directory on the host machine:

root@debian11:~# docker run -d -p 81:80 -v /root/www:/usr/share/nginx/html:ro nginx
5bec576b4b69b3dbd4cb58305a80d5ac94d42312b486e99dac94f82ba6541e3c

root@debian11:~# lynx --dump http://localhost:81
                            Home of the nginx site

root@debian11:~#  

Important - Note here the use of ro option - read-only.

1.19 - Downloading an image without creating a container

Download the centos image without creating a container:

root@debian11:~# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete 
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

Check the contents of the image by creating a container :

root@debian11:~# docker run -it centos bash

[root@b45b7b136f06 /]# cat /etc/redhat-release
CentOS Linux release 8.4.2105

[root@b45b7b136f06 /]# rpm -qa | more
crypto-policies-20210209-1.gitbfb6bed.el8_3.noarch
python3-pip-wheel-9.0.3-19.el8.noarch
ncurses-base-6.1-7.20180224.el8.noarch
dnf-data-4.4.2-11.el8.noarch
dhcp-common-4.3.6-44.0.1.el8.noarch
centos-gpg-keys-8-2.el8.noarch
centos-linux-repos-8-2.el8.noarch
filesystem-3.8-3.el8.x86_64
pcre2-10.32-2.el8.x86_64
ncurses-libs-6.1-7.20180224.el8.x86_64
glibc-common-2.28-151.el8.x86_64
bash-4.4.19-14.el8.x86_64
zlib-1.2.11-17.el8.x86_64
bzip2-libs-1.0.6-26.el8.x86_64
libgpg-error-1.31-1.el8.x86_64
elfutils-libelf-0.182-3.el8.x86_64
libcom_err-1.45.6-1.el8.x86_64
libxml2-2.9.7-9.el8.x86_64
expat-2.2.5-4.el8.x86_64
libuuid-2.32.1-27.el8.x86_64
chkconfig-1.13-2.el8.x86_64
gmp-6.1.2-10.el8.x86_64
libattr-2.4.48-3.el8.x86_64
coreutils-single-8.30-8.el8.x86_64
sed-4.5-2.el8.x86_64
libcap-ng-0.7.9-5.el8.x86_64
libsmartcols-2.32.1-27.el8.x86_64
lz4-libs-1.8.3-2.el8.x86_64
file-libs-5.33-16.el8_3.1.x86_64
p11-kit-0.23.22-1.el8.x86_64
cracklib-2.9.6-15.el8.x86_64
libunistring-0.9.9-3.el8.x86_64
libassuan-2.5.1-3.el8.x86_64
keyutils-libs-1.5.10-6.el8.x86_64
libnl3-3.5.0-1.el8.x86_64
p11-kit-trust-0.23.22-1.el8.x86_64
pcre-8.42-4.el8.x86_64
systemd-libs-239-45.el8.x86_64
dbus-tools-1.12.8-12.el8.x86_64
libusbx-1.0.23-4.el8.x86_64
ca-certificates-2020.2.41-80.0.el8_2.noarch
libdb-5.3.28-40.el8.x86_64
iproute-5.9.0-4.el8.x86_64
libdb-utils-5.3.28-40.el8.x86_64
tpm2-tss-2.3.2-3.el8.x86_64
xz-5.2.4-3.el8.x86_64
ethtool-5.8-5.el8.x86_64
libsemanage-2.9-6.el8.x86_64
dbus-daemon-1.12.8-12.el8.x86_64
libfdisk-2.32.1-27.el8.x86_64
mpfr-3.1.6-1.el8.x86_64
gnutls-3.6.14-7.el8_3.x86_64
snappy-1.1.8-3.el8.x86_64
libmetalink-0.1.3-7.el8.x86_64
libksba-1.3.5-7.el8.x86_64
ipcalc-0.2.4-4.el8.x86_64
libseccomp-2.5.1-1.el8.x86_64
gawk-4.2.1-2.el8.x86_64
--More--
[q]
[root@b45b7b136f06 /]#

1.20 - Attaching to a running container

Stop the container. Start the container and then attach to the container:

[root@b45b7b136f06 /]# exit
exit

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                               NAMES
b45b7b136f06   centos    "bash"                   3 minutes ago    Exited (0) 8 seconds ago                                        quizzical_cray
5bec576b4b69   nginx     "/docker-entrypoint.…"   4 minutes ago    Up 4 minutes                0.0.0.0:81->80/tcp, :::81->80/tcp   elegant_shockley
37cb0af1e97f   nginx     "/docker-entrypoint.…"   27 minutes ago   Created                                                         intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              32 minutes ago   Exited (0) 31 minutes ago                                       ittraining

root@debian11:~# docker start b45b
b45b

root@debian11:~# docker attach b45b

[root@b45b7b136f06 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

[root@b45b7b136f06 /]#

1.21 - Installing software in the container

Repair CentOS 8 repositories:

[root@b45b7b136f06 /]# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-Linux-*

[root@b45b7b136f06 /]# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-Linux-*

[root@b45b7b136f06 /]# yum upgrade -y
...

Create the file /etc/yum.repos.d/mongodb-org-4.2.repo :

[root@b45b7b136f06 /]# vi /etc/yum.repos.d/mongodb-org-4.2.repo

[root@b45b7b136f06 /]# cat /etc/yum.repos.d/mongodb-org-4.2.repo
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.as[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc 

Install mongo :

[root@b45b7b136f06 /]# yum install -y mongodb-org
...

Start mongod:

[root@b45b7b136f06 /]# mongod --config /etc/mongod.conf &
[1] 440

[root@b45b7b136f06 /]# about to fork child process, waiting until server is ready for connections.
forked process: 442
[Enter] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Press Enter
[root@b45b7b136f06 /]# child process started successfully, parent exiting
[Enter] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Press Enter
[1]+ Done mongod --config /etc/mongod.conf

Check that mongod is started:

[root@b45b7b136f06 /]# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0  12156  3324 pts/0    Ss   12:20   0:00 bash
root         442  0.5  0.6 1525168 111704 ?      Sl   13:53   0:00 mongod --config /etc/mongod.conf
root         475  0.0  0.0  47604  3668 pts/0    R+   13:55   0:00 ps aux

Use the mongo client to connect to the server:

[root@b45b7b136f06 /]# mongo
MongoDB shell version v4.2.24
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b864990d-ab42-45cc-b9e3-0935f566a41a") }
MongoDB server version: 4.2.24
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
Server has startup warnings: 
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] 
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] 
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] 
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2023-08-19T13:53:35.327+0000 I CONTROL [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

Exit mongo and the container :

> exit
bye
[root@b45b7b136f06 /]# exit
exit
root@debian11:~# 

1.22 - Using the docker commit command

Now create a new image from your container:

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS                      PORTS                               NAMES
b45b7b136f06   centos    "bash"                   2 hours ago   Exited (0) 31 seconds ago                                       quizzical_cray
5bec576b4b69   nginx     "/docker-entrypoint.…"   2 hours ago   Up 2 hours                  0.0.0.0:81->80/tcp, :::81->80/tcp   elegant_shockley
37cb0af1e97f   nginx     "/docker-entrypoint.…"   2 hours ago   Created                                                         intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              2 hours ago   Exited (0) 2 hours ago                                          ittraining

root@debian11:~# docker commit b45b ittraining/mongodb
sha256:0ebd6759e69e3c345087dea3c9743a9d0fad81ca750842f1ff0004cbffabd8ae

root@debian11:~#

Delete the container used to create the image:

root@debian11:~# docker rm b45b
b45b

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS                   PORTS                               NAMES
5bec576b4b69   nginx     "/docker-entrypoint.…"   2 hours ago   Up 2 hours               0.0.0.0:81->80/tcp, :::81->80/tcp   elegant_shockley
37cb0af1e97f   nginx     "/docker-entrypoint.…"   2 hours ago   Created                                                      intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              2 hours ago   Exited (0) 2 hours ago                                       ittraining

Use the new image to launch a container named mongo :

root@debian11:~# docker run -it --name mongo ittraining/mongodb

[root@0c597fe7b628 /]# ls  /usr/bin/mongo*
/usr/bin/mongo  /usr/bin/mongod  /usr/bin/mongodump  /usr/bin/mongoexport  /usr/bin/mongofiles  /usr/bin/mongoimport  /usr/bin/mongorestore  /usr/bin/mongos  /usr/bin/mongostat  /usr/bin/mongotop

[root@0c597fe7b628 /]# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0  15100  3704 pts/0    Ss   14:01   0:00 bash
root          18  0.0  0.0  47604  3696 pts/0    R+   14:01   0:00 ps aux

Edit the /etc/bashrc file:

[root@0c597fe7b628 /]# echo "/usr/bin/mongod --config /etc/mongod.conf &" >> /etc/bashrc

[root@0c597fe7b628 /]# tail /etc/bashrc
        fi
    done

    unset i
    unset -f pathmunge
  fi

fi
# vim:ts=4:sw=4
/usr/bin/mongod --config /etc/mongod.conf &

[root@0c597fe7b628 /]# 

Check the list of containers and retrieve the CONTAINER ID of the mongo container:

[root@0c597fe7b628 /]# exit
exit

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE                COMMAND                  CREATED              STATUS                     PORTS                               NAMES
0c597fe7b628   ittraining/mongodb   "bash"                   About a minute ago   Exited (0) 7 seconds ago                                       mongo
5bec576b4b69   nginx                "/docker-entrypoint.…"   2 hours ago          Up 2 hours                 0.0.0.0:81->80/tcp, :::81->80/tcp   elegant_shockley
37cb0af1e97f   nginx                "/docker-entrypoint.…"   2 hours ago          Created                                                        intelligent_fermi
d838ea83033e   ubuntu               "/bin/bash"              2 hours ago          Exited (0) 2 hours ago                                         ittraining

root@debian11:~#

Use the commit command to “save” the change in the image:

root@debian11:~# docker commit 0c59 ittraining/mongodb
sha256:3daa95515db6c3f1bd7e30a29c52d3bd5ea14207c05d9401bc2da91d54adbb3f

Create another container to check that mongod is working:

root@debian11:~# docker rm 0c59
0c59

root@debian11:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS                   PORTS                               NAMES
5bec576b4b69   nginx     "/docker-entrypoint.…"   2 hours ago   Up 2 hours               0.0.0.0:81->80/tcp, :::81->80/tcp   elegant_shockley
37cb0af1e97f   nginx     "/docker-entrypoint.…"   2 hours ago   Created                                                      intelligent_fermi
d838ea83033e   ubuntu    "/bin/bash"              2 hours ago   Exited (0) 2 hours ago                                       ittraining

root@debian11:~# docker run -it --name mongo ittraining/mongodb
about to fork child process, waiting until server is ready for connections.
forked process: 19
[root@4e8fc8b07afe /]# child process started successfully, parent exiting
[Enter] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  Appuyer sur la touche Entrée
[1]+  Done                    /usr/bin/mongod --config /etc/mongod.conf

[root@4e8fc8b07afe /]# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0  14980  3592 pts/0    Ss   14:05   0:00 bash
root          19  3.5  0.6 1534072 105260 ?      Sl   14:05   0:00 /usr/bin/mongod --config /etc/mongod.conf
root          56  0.0  0.0  47604  3672 pts/0    R+   14:05   0:00 ps aux

[root@4e8fc8b07afe /]# 

1.23 - Connecting to the container server from the outside

To be able to connect to mongodb from the host machine, the /etc/mongod.conf file needs to be edited:

[root@4e8fc8b07afe /]# vi /etc/mongod.conf

[root@4e8fc8b07afe /]# cat /etc/mongod.conf | grep bindIp
  bindIp: 0.0.0.0 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

Exit the container, re-create an image, delete the container used and relaunch the container :

[root@4e8fc8b07afe /]# exit
exit

root@debian11:~# docker commit mongo ittraining/mongodb
sha256:eaf8432e4d74fbc4c1f805279fc7d62cb927c5c60010f1ef33f099cc483a9471

root@debian11:~# docker rm mongo
mongo

root@debian11:~# docker run -it --name mongo ittraining/mongodb
about to fork child process, waiting until server is ready for connections.
forked process: 19
[root@e2ace1b2a6a2 /]# child process started successfully, parent exiting
[Enter] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Press Enter
[1]+ Done /usr/bin/mongod --config /etc/mongod.conf

[root@e2ace1b2a6a2 /]# 

On your host machine, configure the mongodb repository:

[root@e2ace1b2a6a2 /]# exit
exit
root@debian11:~#

root@debian11:~# apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
Executing: /tmp/apt-key-gpghome.f5dbDP3oUn/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
gpg: key 68818C72E52529D4: public key "MongoDB 4.0 Release Signing Key <packaging@mongodb.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1

root@debian11:~# echo "deb [trusted=yes] http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list
deb [trusted=yes] http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main

root@debian11:~# apt-get update
...

This time, install only the mongodb client:

root@debian11:~# apt-get install mongodb-org-shell
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libopengl0 linux-headers-5.10.0-15-amd64 linux-headers-5.10.0-15-common
Use 'apt autoremove' to remove them.
The following NEW packages will be installed:
  mongodb-org-shell
0 upgraded, 1 newly installed, 0 to remove and 5 not upgraded.
Need to get 9,970 kB of archives.
After this operation, 40.3 MB of additional disk space will be used.
Get:1 http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0/main amd64 mongodb-org-shell amd64 4.0.28 [9,970 kB]
Fetched 9,970 kB in 1s (10.8 MB/s)             
Selecting previously unselected package mongodb-org-shell.
(Reading database ... 166761 files and directories currently installed.)
Preparing to unpack .../mongodb-org-shell_4.0.28_amd64.deb ...
Unpacking mongodb-org-shell (4.0.28) ...
Setting up mongodb-org-shell (4.0.28) ...
Processing triggers for man-db (2.9.4-2) ...

Note that at this stage the container does not have an IP address because it is not started:

root@debian11:~# docker inspect mongo | grep IP
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

So start the container and look for its IP address :

root@debian11:~# docker start mongo
mongo

root@debian11:~# docker inspect mongo | grep IP
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

root@debian11:~#

Now connect to your mongodb from the host machine :

root@debian11:~# mongo --host 172.17.0.3
MongoDB shell version v4.0.28
connecting to: mongodb://172.17.0.3:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c1fadd17-a76c-4ca2-aa0e-b06498c55ba5") }
MongoDB server version: 4.2.24
WARNING: shell and server versions do not match
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] 
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] 
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] 
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2023-08-19T14:43:49.070+0000 I CONTROL [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

> exit
bye
root@debian11:~#   

Copyright © 2024 Hugh Norris.