Docker basic operation notes

Posted by dsandif on Tue, 04 Jan 2022 01:39:46 +0100

dokcer structure diagram

Docker includes three basic concepts:

  • Image: Docker image is equivalent to a root file system. For example, the official image ubuntu:16.04 contains a complete set of root file system of the smallest system of Ubuntu 16.04.
  • Container: the relationship between an Image and a container is like a class and instance in object-oriented programming. An Image is a static definition and a container is an entity when the Image runs. A container can be created, started, stopped, deleted, suspended, etc.
  • Repository: a repository can be regarded as a code control center for storing images.

Docker uses client server (C/S) architecture mode and remote API s to manage and create docker containers.

Docker containers are created through docker images.

conceptexplain
Docker imagesDocker image is a template for creating docker container, such as Ubuntu system.
Docker containerA container is an application or group of applications that run independently. It is an entity that mirrors the runtime.
Docker clientThe Docker client uses the Docker SDK through the command line or other tools( https://docs.Docker.com/develop/sdk/ )Communicate with Docker's daemon.
Docker hostA physical or virtual machine is used to execute Docker daemons and containers.
Docker RegistryDocker warehouse is used to save images, which can be understood as a code warehouse in code control. Docker Hub( https://hub.docker.com )Provides a large collection of images for use. A Docker Registry can contain multiple repositories; each Repository can contain multiple tags (Tag); each Tag corresponds to an image. Usually, a warehouse will contain images of different versions of the same software, and tags are often used to correspond to each version of the software. We can specify which version of the software is the image in the format of < warehouse name >: < Tag >. If no Tag is given, latest will be used as the default Tag.
Docker MachineDocker Machine is a command line tool to simplify docker installation. Docker can be installed on corresponding platforms through a simple command line, such as VirtualBox, Digital Ocean and Microsoft Azure.

docker installation

# Install docker
yum install docker 
# Start docker
systemctl start docker
# Stop docker
systemctl stop docker
# Restart docker
systemctl restart docker
# Set startup
systemctl enable docker
# View docker status
systemctl status docker
# View the running status of docker content manager
docker stats
# View docker profile
docker info
#More version information
docker version

docker command

docker help command

image --help image help

[root@iZ70eyv5ttqkcsZ /]# docker image --help 

Usage:	docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile	Build mirror
  history     Show the history of an image  	View mirror construction history
  import      Import the contents from a tarball to create a filesystem image	View details
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN	Import mirror
  ls          List images		View mirror list
  prune       Remove unused images			Delete unused mirrors
  pull        Pull an image or a repository from a registry		Pull from warehouse
  push        Push an image or a repository to a registry 		Push from to warehouse
  rm          Remove one or more images			delete mirror
  save        Save one or more images to a tar archive (streamed to STDOUT by default)	Export mirror
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

Run 'docker image COMMAND --help' for more information on a command.

network --help network management

Three times of environmental deployment:

  • Deploy multiple websites on the same server. If one is invaded, all websites will hang up

  • Install multiple virtual machines on the same server, and deploy websites in the virtual machines

  • Same server, multiple containers (isolation by default)

    Break the isolation if you want to test

[root@iZ70eyv5ttqkcsZ /]# docker network --help

Usage:	docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network	Join a container to a network
  create      Create a network 		Create a new network
  disconnect  Disconnect a container from a network	The container exits a network
  inspect     Display detailed information on one or more networks		View network parameters
  ls          List networks		View all
  prune       Remove all unused networks	Delete all unused networks
  rm          Remove one or more networks Delete specified network

Run 'docker network COMMAND --help' for more information on a command.
[root@iZ70eyv5ttqkcsZ /]# docker network create my_net
045a52589a4a65c533c6780cea1e02f59ff086ec931d1e5f5bd5677f7b5880fc
[root@iZ70eyv5ttqkcsZ /]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
925d76f09fd6        bridge              bridge              local
281118b78fa3        host                host                local
045a52589a4a        my_net              bridge              local
55f475a6cc84        none                null                local

volume --help file store

docker's persistence tool saves the data in the container

[root@iZ70eyv5ttqkcsZ /]# docker volume --help

Usage:	docker volume COMMAND

Manage volumes

Commands:
  create      Create a volume   establish
  inspect     Display detailed information on one or more volumes		View parameters
  ls          List volumes	view list
  prune       Remove all unused local volumes
  rm          Remove one or more volumes

Run 'docker volume COMMAND --help' for more information on a command.

docker --help

[root@iZ70eyv5ttqkcsZ /]# docker --help

Usage:	docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon
                           (overrides DOCKER_HOST env var and default context set with
                           "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level
                           ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default
                           "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  engine      Manage the docker engine
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information	Display system information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version  information		docker edition
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.

docker container --help container

[root@iZ70eyv5ttqkcsZ /]# docker container --help

Usage:	docker container COMMAND

Manage containers

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  run         Run a command in a new container
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker container COMMAND --help' for more information on a command.

  • run creates and starts the container from the image
  • stop stops a container
  • kill forcibly end the mirror
  • Restart restart container
  • Logs view container logs

docker image command

docker images displays the local library image

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
redis         latest    7614ae9453d1   3 days ago     113MB
mysql         5.6       dd3b2a5dcb48   3 days ago     303MB

#explain
REPOSITORY	Mirrored warehouse source
TAG			Mirrored label
IMAGE ID	Ongoing id
CREATED		Image creation time
SIZE 		Mirror size

#Optional
-a . --all  	#List all mirrors
-q , --quiet  	#Only the mirror ID is displayed

docker serach search image

You can search image -f by docker serach image name for filtering

[root@iZ70eyv5ttqkcsZ ~]# docker search tomcat
NAME                          DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
tomcat                        Apache Tomcat is an open source implementati...   3202      [OK]       
tomee                         Apache TomEE is an all-Apache Java EE certif...   95        [OK]       

#Optional
--filter=STARS=3000

[root@iZ70eyv5ttqkcsZ ~]# docker search tomcat --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
tomcat    Apache Tomcat is an open source implementati...   3202      [OK]       

docker pull Download Image

[root@iZ70eyv5ttqkcsZ ~]# docker pull tomcat
# docker pull image name [: tag]
Using default tag: latest Not written tag The latest version will be downloaded by default
latest: Pulling from library/tomcat		#Download the core federated file system of docker iamge
0e29546d541c: Pull complete 
9b829c73b52b: Pull complete 
cb5b7ae36172: Pull complete 
6494e4811622: Pull complete 
668f6fcc5fa5: Pull complete 
dc120c3e0290: Pull complete 
8f7c0eebb7b1: Pull complete 
77b694f83996: Pull complete 
0f611256ec3a: Pull complete 
4f25def12f23: Pull complete 
Digest: sha256:9dee185c3b161cdfede1f5e35e8b56ebc9de88ed3a79526939701f3537a52324
Status: Downloaded newer image for tomcat:latest
docker.io/library/tomcat:latest

#Therefore, docker tomcat is equivalent to docker io/library/tomcat:latest

[root@iZ70eyv5ttqkcsZ ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists 
93619dbc5b36: Already exists 
99da31dd6142: Already exists 
626033c43d70: Already exists 
37d5d7efb64e: Already exists 
ac563158d721: Already exists 
d2ba16033dad: Already exists 
0ceb82207cd7: Pull complete 
37f2405cae96: Pull complete 
e2482e017e53: Pull complete 
70deed891d42: Pull complete 
Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

#It can be seen that the files of the two versions are duplicated, so they are reused to save space

docker rmi delete image

docker rmi -f container id 	#Deletes the specified mirror
docker rmi -f container id container id container id	#Delete multiple specified mirrors
docker rmi -f $(docker images -ap) 	#Delete all mirrors

docker container command

docker run container

run command parameters

docker run[Optional parameters] image
	--name	 			#Custom container name
	--rm 				#Automatically delete after
	--net 				#Specify the network that the container joins
	--volume${PWD}:/tmp #Put the current directory in the container
	-it 				#Enter the container interactively
	-d  				#Let the container run in the background
	-p					#Specify container port -p 8080:8080
		(-p ip:Host port:Container port
		-p Host port:Container port		
		-p Container port
		Container port
		)
Image name	
bush  					#Commands executed by the container

example:

Enter the command to create a container

[root@iZ70eyv5ttqkcsZ /]#docker run --name myubuntu --rm --net my_net -it --volume ${PWD}:/tmp ubuntu:15.10

Run a container from the image ubuntu:15.10,

The parameter is – name myubuntu, and the user-defined name myubuntu

– delete container after rm

–net my_net using custom network

– it enters the container

– volume${PWD}:/tmp the current directory and

After creation

The tmp of the container and the directory temp at the time of creation become shared folders

docker ps lists all containers

docker ps command
 parameter
-a 			#List the currently running containers and bring out the containers that have been run in history
[root@iZ70eyv5ttqkcsZ ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED        STATUS                      PORTS     NAMES
d6bff0002ff3   mysql:5.6      "docker-entrypoint.s..."   14 hours ago   Exited (0) 11 hours ago               qmm-mysql
ea28a8983188   redis          "docker-entrypoint.s..."   14 hours ago   Exited (0) 11 hours ago               redis-test
502e81fcd6ef   mysql          "docker-entrypoint.s..."   14 hours ago   Exited (137) 14 hours ago             mysqltest
be5b402aa0ea   ubuntu:15.10   "/bin/bash"              17 hours ago   Exited (0) 14 hours ago               myubuntu

-n=?		#Displays recently created containers
[root@iZ70eyv5ttqkcsZ ~]# docker ps -n=2
CONTAINER ID   IMAGE       COMMAND                  CREATED        STATUS                    PORTS     NAMES
d6bff0002ff3   mysql:5.6   "docker-entrypoint.s..."   14 hours ago   Exited (0) 11 hours ago             qmm-mysql
ea28a8983188   redis       "docker-entrypoint.s..."   14 hours ago   Exited (0) 11 hours ago             redis-test

-q 			#Show only container numbers
[root@iZ70eyv5ttqkcsZ ~]# docker ps -aq
d6bff0002ff3
ea28a8983188
502e81fcd6ef
be5b402aa0ea

Exit exit container

exit #Container stop and exit

Ctrl + P+ Q #The container does not stop exiting

rm delete container

docker rm container id  #Force delete - f
docker rm -f$(docker ps -aq) #Delete all containers
docker rm -a -q | xargs docker rm #Delete all containers via linux pipeline

-f :adopt SIGKILL The signal forces the deletion of a running container.
-l :Remove network connections between containers, not the container itself.
-v :Delete the volume associated with the container.

Start container stop container

docker start container id 	#Start container
docker restart container id #Restart container
docker stop container id	#Stop current container
docker kill container id	#Forcibly end container -s (in operation)

Background start pit

[root@iZ70eyv5ttqkcsZ /]# docker image ls
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
tomcat        latest    fb5657adc892   2 days ago     680MB
redis         latest    7614ae9453d1   3 days ago     113MB
mysql         5.6       dd3b2a5dcb48   4 days ago     303MB
mysql         5.7       c20987f18b13   4 days ago     448MB
mysql         latest    3218b38490ce   4 days ago     516MB
hello-world   latest    feb5d9fea6a5   3 months ago   13.3kB
ubuntu        15.10     9b9cb95443b5   5 years ago    137MB
[root@iZ70eyv5ttqkcsZ /]# docker run -d ubuntu:15.10
88a5e2093d45b5c73fe387efec75435d06a105a4f90524c14f26458fd1a83ee6
[root@iZ70eyv5ttqkcsZ /]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZ70eyv5ttqkcsZ /]# 

#It can be seen that the ubuntu system started by docker run -d stops automatically
#When the docker container runs in the background, there must be a foreground process. When dicker finds that there is no application, it will automatically stop
#After the nginx container stopped, it found that it stopped without providing services

Logs view logs

[root@iZwz99sm8v95sckz8bd2c4Z ~]# docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
  -n, --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)

[root@iZ70eyv5ttqkcsZ /]# docker run -d ubuntu:15.10 /bin/sh -c "while true;do echo asdf;sleep 1;done"
By starting ubyuntu function shell script

Then view the log
docker logs -tf --tail 10 9ea2db1ae202 View 10 container logs
-t time stamp
--tail number # Number of log entries to display

top view container process information

[root@iZ70eyv5ttqkcsZ /]# docker top 9ea2db1ae202
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                20319               20300               0                   11:47               ?                   00:00:00            /bin/sh -c while true;do echo asdf;sleep 1;done
root                20735               20319               0                   11:53               ?                   00:00:00            sleep 1

inspect view image metadata

#command
docker inspect container id

[root@iZ70eyv5ttqkcsZ /]# docker inspect 9ea2db1ae202
[
    {
        "Id": "9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4",
        "Created": "2021-12-25T03:47:28.114441135Z",  #Creation time
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo asdf;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 20319,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-12-25T03:47:28.408944652Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:9b9cb95443b5f846cd3c8cfa3f64e63b6ba68de2618a08875a119c81a8f96698",
        "ResolvConfPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/hostname",
        "HostsPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/hosts",
        "LogPath": "/var/lib/docker/containers/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4/9ea2db1ae202fe5ed6daeaeea6b2f19008fe3431b854dc97234eb877262abbe4-json.log",
        "Name": "/reverent_mestorf",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "host",
            "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",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "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/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e-init/diff:/var/lib/docker/overlay2/5374c6923f0c3e34a2063f69e740d22e5f0dc3c774a85daaea2243bde27f4e30/diff:/var/lib/docker/overlay2/c52b61b87d6f5b6d1db021f5bcefb0fc72244cf6ebd177ab4da31c3039484575/diff:/var/lib/docker/overlay2/89ec0b0a5bdbf0b16e52f600a2635d65bf853f49028600c29c0d9831a97c6b1c/diff:/var/lib/docker/overlay2/ac0af19b0239fea77aa851305752f6892e1e35b06d35eee2ce952d0a58165bd5/diff",
                "MergedDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/merged",
                "UpperDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/diff",
                "WorkDir": "/var/lib/docker/overlay2/ff1a3f18a4ebfaa1917f590f9aef58944996e370a0920297a61b5a24789cc50e/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "9ea2db1ae202",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo asdf;sleep 1;done"
            ],
            "Image": "ubuntu:15.10",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "1e4ab641ef66db61ed8d80ee86403f520e9fed30778bdea5ca90560f2d88aaff",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/1e4ab641ef66",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "582789bb827cf0be983a2c27b1ce81beb938d96bcc87819975699d6f8698f80e",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "b7fadd350b116c439908c7d7e2118478ddaa91d355d090572584e6b5f58137b6",
                    "EndpointID": "582789bb827cf0be983a2c27b1ce81beb938d96bcc87819975699d6f8698f80e",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

exec / attach command to enter the container

#Most containers run in the background. You can enter the container to modify the configuration through the exec command
docker exec -it container id bashShell

#example
#Mode 1
[root@iZ70eyv5ttqkcsZ /]# docker exec -it 9ea2db1ae202 /bin/bash
root@9ea2db1ae202:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
#Mode II
docker attach 9ea2db1ae202

#difference
#exec is to open a new terminal for operation
#attach enters the terminal where the container is executing

ps copies files from the container to the host

docker cp container id:In container path destination host path

#Enter the inside of the container
[root@iZ70eyv5ttqkcsZ home]# docker exec -it 9ea2db1ae202 /bin/bash
root@9ea2db1ae202:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
root@9ea2db1ae202:/# cd tmp/
root@9ea2db1ae202:/tmp# ll
total 8
drwxrwxrwt 2 root root 4096 Jul  6  2016 ./
drwxr-xr-x 1 root root 4096 Dec 25 03:47 ../

#Create a new file test java
root@9ea2db1ae202:/tmp# touch test.java
root@9ea2db1ae202:/tmp# ls
test.java
root@9ea2db1ae202:/tmp# exit
exit
[root@iZ70eyv5ttqkcsZ home]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS     NAMES
9ea2db1ae202   ubuntu:15.10   "/bin/sh -c 'while t..."   30 minutes ago   Up 30 minutes             reverent_mestorf

#Copy after exit
[root@iZ70eyv5ttqkcsZ home]# docker cp 9ea2db1ae202:tmp/test.java /temp  #Copy the files in the container to the host path
[root@iZ70eyv5ttqkcsZ home]# ls
admin
[root@iZ70eyv5ttqkcsZ home]# cd ..
[root@iZ70eyv5ttqkcsZ /]# cd temp/

#Check copy results
[root@iZ70eyv5ttqkcsZ temp]# ls
f  t1.txt  test.java

Detailed explanation of docker image

What is mirroring

Image is a lightweight and executable independent software package, which is used to package the software running environment and the software developed based on the running environment. It contains all the contents required to run a software, including code, runtime (the dependency of a program running or being executed), library, environment variables and configuration files.

Docker image loading principle

The Docker image is actually composed of a layer by layer file system, which is the UnionFS federated file system.

Union fs (Federated file system): Union file system (Union FS) is a layered, lightweight and high-performance file system. It supports the superposition of file system modifications as a single commit. At the same time, different directories can be mounted under the same virtual file system (unit severe directories into a single virtual file system). The union file system is the foundation of Docker image. Images can be inherited through layering. Based on the basic image (without parent image), various specific application images can be made.

Features: multiple file systems can be loaded at the same time, but from the outside, only one file system can be seen. Joint loading will overlay all layers of file systems, so that the final file system will contain all underlying files and directories

bootfs(boot file system) mainly includes bootloader and kernel. Bootloader is mainly used to boot and load the kernel. Bootfs file system will be loaded when Linux starts up. Bootfs is at the bottom of Docker image This - layer is the same as our typical Linux/Unix system, including boot loader and kernel. After the boot is loaded, the whole kernel is in memory. At this time, the right to use the memory E Qbp fs is transferred to the kernel. At this time, the system will also unload bootfs

rootfs (root file system), above bootfs. It contains standard directories and files such as / dev, /proc, /bin, /etc in a typical Linux system. rootfs is a variety of operating system distributions, such as Ubuntu, CentOS and so on.

Hierarchical understanding

[root@iZ70eyv5ttqkcsZ ~]# docker pull redis
Using default tag: latest
Trying to pull repository docker.io/library/redis ... 
latest: Pulling from docker.io/library/redis
a2abf6c4d29d: Pull complete 
c7a4e4382001: Pull complete 
4044b9ba67c9: Pull complete 
c8388a79482f: Pull complete 
413c8bb60be2: Pull complete 
1abfd3011519: Pull complete 
Digest: sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339
Status: Downloaded newer image for docker.io/redis:latest

Layered information of redis image

[root@iZ70eyv5ttqkcsZ ~]# docker image inspect 7614ae9453d1
[
    {
        "Id": "sha256:7614ae9453d1d87e740a2056257a6de7135c84037c367e1fffa92ae922784631",
        "RepoTags": [
            "docker.io/redis:latest"
        ],
        "RepoDigests": [
            "docker.io/redis@sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2021-12-21T12:42:49.755107412Z",
        "Container": "13d25f53410417c5220c8dfe8bd49f06abdbcd69faa62a9b877de02464bb04a3",
        "ContainerConfig": {
            "Hostname": "13d25f534104",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "6379/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "REDIS_VERSION=6.2.6",
                "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz",
                "REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"redis-server\"]"
            ],
            "Image": "sha256:e093f59d716c95cfce82c676f099b960cc700432ab531388fcedf79932fc81ec",
            "Volumes": {
                "/data": {}
            },
            "WorkingDir": "/data",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "DockerVersion": "20.10.7",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "6379/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "REDIS_VERSION=6.2.6",
                "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.6.tar.gz",
                "REDIS_DOWNLOAD_SHA=5b2b8b7a50111ef395bf1c1d5be11e6e167ac018125055daa8b5c2317ae131ab"
            ],
            "Cmd": [
                "redis-server"
            ],
            "Image": "sha256:e093f59d716c95cfce82c676f099b960cc700432ab531388fcedf79932fc81ec",
            "Volumes": {
                "/data": {}
            },
            "WorkingDir": "/data",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 112691373,
        "VirtualSize": 112691373,
        "GraphDriver": {
            "Name": "overlay2",
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/62af77965a3476e4455a63a4a2c035de425c122126416a6d444bc3828b6e1565/diff:/var/lib/docker/overlay2/891aab6af76699a767e75221bde0813ded1b4d7a334ac2f871a054e22d3b6406/diff:/var/lib/docker/overlay2/6546f44f77123619d93872f6d62007c3063c396149e4e934bbe06ae6f934f673/diff:/var/lib/docker/overlay2/f01a1ec92c9bfbce291ebaadc090b089260d1b54f1abab456737b6a766945a53/diff:/var/lib/docker/overlay2/c077d83c4aea5d1eab5598f9abf2e771e757a06553ee4dd730e27b5498662783/diff",
                "MergedDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/merged",
                "UpperDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/diff",
                "WorkDir": "/var/lib/docker/overlay2/67a7e9415012210b243784af52f52a9c7427ed40e55d4b91370138314602f2ab/work"
            }
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f",
                "sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb",
                "sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1",
                "sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372",
                "sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed",
                "sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952"
            ]
        }
    }
]

What are the benefits of this layered approach?

The biggest advantage is resource sharing. If multiple images use the same base image, the host only needs to save one base image. When loading, all use this image, saving space and bandwidth

Example:

All images start from a basic image layer. When modifying or adding new content, a new image layer will be created above the current image layer

In the figure above, first create an image with ubuntu as the first layer image, and then add the python package. On this basis, a second image layer will be created and a third security layer will be added

When additional image layers are added, the image is also a collection of all current images. There are three files in each layer, and the image contains six files in two image layers

Now it is a three - tier image, adding file 7 as the third tier But externally, there are only six documents Because the filer is an updated version of file 5

The mirror layer displayed by the actual outer layer is the result of the merger

Dockers are read-only. After the slave image is started, a new writable layer will be loaded to the top of the image This layer is called the container layer, and everything below it is called the mirror layer

At the same time, we can package the changed operation into a new image

commit image

docker commit -m="Description information submitted" -a"author" container id Target image name:[TAG]

Example: tomcat runs and commit s the image

Webapps.com of tomcat The things in dist directory cp to webapp

Use the commit command to commit to a new image

You can use the new image later

#Enter tomcat to copy

[root@iZ70eyv5ttqkcsZ ~]# docker exec -it mytomcat /bin/bash
root@4fb7a336b403:/usr/local/tomcat# cp -r webapps.dist/* webapps
root@4fb7a336b403:/usr/local/tomcat# ls
BUILDING.txt  CONTRIBUTING.md  LICENSE	NOTICE	README.md  RELEASE-NOTES  RUNNING.txt  bin  conf  lib  logs  native-jni-lib  temp  webapps  webapps.dist  work
root@4fb7a336b403:/usr/local/tomcat# cd webapps
root@4fb7a336b403:/usr/local/tomcat/webapps# ls
ROOT  docs  examples  host-manager  manager

#Then package
[root@iZ70eyv5ttqkcsZ ~]# docker commit -a="yjwtest" -m="add webapp" 4fb7a336b403 tomcattest:01

[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
tomcattest                      01                  27a965b7b00e        9 seconds ago       684 MB
docker.io/tomcat                latest              fb5657adc892        3 days ago          680 MB
docker.io/redis                 latest              7614ae9453d1        4 days ago          113 MB
docker.io/mysql                 latest              3218b38490ce        5 days ago          516 MB
docker.io/hello-world           latest              feb5d9fea6a5        3 months ago        13.3 kB
docker.io/portainer/portainer   latest              580c0e4e98b0        9 months ago        79.1 MB
 I can see that the packaging succeeded

Observing the layers field of the two mirrors, it can be seen that a mirror layer is added

Container data volume

Docker packages the application with the running environment to form a container. If the data generated by the docker container is not generated through docker commit to save the data as part of the image, the data will naturally disappear after the container is deleted. In order to save data, we use volumes in docker.

A volume is a directory or file. It exists in one or more containers and is mounted to the container by Docker. However, the volume does not belong to the union file system. Therefore, it can bypass the union file system and provide some features for continuous storage or sharing of data:.

‚Äč

Container persistence and synchronization, and data sharing between containers

Example

Create a centos system and mount the / home/centostest directory of the host and the home directory of the container

[root@iZ70eyv5ttqkcsZ ~]# docker run -it -v /home/centostest:/home centos /bin/bash

docker inspect container id

   "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/centostest", #Host address
                "Destination": "/home", # Address in container
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],

Test whether the binding is successful

#Host docker container
#Host computer
[root@iZ70eyv5ttqkcsZ home]# cd centostest/
[root@iZ70eyv5ttqkcsZ centostest]# ls
[root@iZ70eyv5ttqkcsZ centostest]# touch 1.txt
[root@iZ70eyv5ttqkcsZ centostest]# ls
1.txt
#docker
[root@00dc126cf532 home]# ls
1.txt

#docker container - host
#container
[root@00dc126cf532 home]# touch test.java
[root@00dc126cf532 home]# ls
1.txt  test.java
#Host computer
[root@iZ70eyv5ttqkcsZ centostest]# ls
1.txt  test.java

Stop the container in time The modified directory can also synchronize data after startup

Example: mysql data and configuration file are mounted to realize container data persistence

  1. Create container
docker run -d -p3306:3306 -v /home/mysql/conf:/etc/mysql/conf -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=1234 --name mysqltest mysql:5.7

-d Background operation
-v You can write more when the volume is mounted
-e Environment configuration
--name rename
 Container name may be duplicate,have access to docker ps -a After viewing,docker rm Delete container,Or choose another name
 "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/mysql/conf",
                "Destination": "/etc/mysql/conf",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/home/mysql/data",
                "Destination": "/var/lib/mysql",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],

  1. Port mapping is performed through 3306:3306 So use the ip: port number to test the link

Test link succeeded

  1. Create a database test1

You can see that the test1w folder appears in the mounted data directory

4. Delete the container and check whether the data exists

[root@iZ70eyv5ttqkcsZ ~]# docker rm -f a3576fbdfab0

[root@iZ70eyv5ttqkcsZ conf]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
a3576fbdfab0        mysql:5.7           "docker-entrypoint..."   11 minutes ago      Up 11 minutes       0.0.0.0:3306->3306/tcp, 33060/tcp   mysqltest
[root@iZ70eyv5ttqkcsZ conf]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Has been deleted

[root@iZ70eyv5ttqkcsZ data]# ls
auto.cnf    ca.pem           client-key.pem  ibdata1      ib_logfile1  mysql               private_key.pem  server-cert.pem  sys
ca-key.pem  client-cert.pem  ib_buffer_pool  ib_logfile0  ibtmp1       performance_schema  public_key.pem   server-key.pem   test1

Check that the data still exists. You can see that the data is persistent

Named mount and anonymous mount

Anonymous and named means that the mount name is not specified

-v / the path in the container is anonymous mount

-v the volume name / path in the container is a named mount

-v / host path: path in container

#Anonymous mount
docker run -d -P --name nginx01 -v /ext/nginx nginx
DRIVER              VOLUME NAME
local               d50fc7dd550f516f0399bc44a7a6bb36f5c8a027d150d20186d4bcb1bf97a770
#Named mount
docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx nginx
DRIVER              VOLUME NAME
local               juming-nginx


#View the specific path through docker volume inspect mount name
[root@iZ70eyv5ttqkcsZ etc]# docker volume inspect juming-nginx
[
    {
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/juming-nginx/_data",#It can be seen that the actual path is in this place. If there is no specified directory, it exists in this directory
        "Name": "juming-nginx",
        "Options": {},
        "Scope": "local"
    }
]

Only the path inside the container is written, and the path outside the container is stored in this directory by default

[root@iZ70eyv5ttqkcsZ etc]# cd /var/lib/docker/volumes
[root@iZ70eyv5ttqkcsZ volumes]# ls
03bb1f56f95be70ae73ce7658b2b465db6357da7d934951fefa7da01a331b63f
374bd2397a0f963947e287c00383dc532a3291661eff5c65634b78d52da65312
56c60c435470192b3aea364948472035bd66437c78b5392f41a7e6dbb6037f7d
90b0ab7e3ee2171f964daa70944f097150505901d580d125c655c2a01a5f5c3a
d50fc7dd550f516f0399bc44a7a6bb36f5c8a027d150d20186d4bcb1bf97a770
juming-nginx
metadata.db

expand:

ro readonly #Read only can only be read from docker, and write can only start from the host
rw readwrite#Writable
docker run -d -P --name nginx02 -v juming-nginx:etc/nginx:ro nginx
docker run -d -P --name nginx02 -v juming-nginx:etc/nginx:rw nginx # Default

Set data volume in Dockerfile

We can use the VOLUME instruction in Dockerfile to add one or more data volumes to the image.

Next, use Dockerfile to build a new image. The contents of dockerfile01 file are anonymously mounted in volume01 and volume02 directories:

FROM centos

VOLUME ["volume01","volume02"]

CMD echo "----end----"
CMD /bin/bash

Build statement

[root@iZ70eyv5ttqkcsZ home]# docker build -f dockfile01 -t centos .   #Pay attention to one point
Sending build context to Docker daemon 219.9 MB
Step 1/4 : FROM centos
 ---> 5d0da3dc9764
Step 2/4 : VOLUME volume01 volume02
 ---> Running in fb1b6162c99a
 ---> 2324d5195be1
Removing intermediate container fb1b6162c99a
Step 3/4 : CMD echo "end------"
 ---> Running in b60ceb27c6cc
 ---> 47ae91d9d1a5
Removing intermediate container b60ceb27c6cc
Step 4/4 : CMD /bin/bash
 ---> Running in c35591f37d19
 ---> b87454c9f973
Removing intermediate container c35591f37d19
Successfully built b87454c9f973


#Generated its own images
[root@iZ70eyv5ttqkcsZ home]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
centos                          latest              b87454c9f973        22 seconds ago      231 MB
tomcattest                      01                  27a965b7b00e        22 hours ago        684 MB
docker.io/tomcat                latest              fb5657adc892        4 days ago          680 MB
docker.io/redis                 latest              7614ae9453d1        5 days ago          113 MB

#You can see the data volume directory of the corresponding host

 "Mounts": [
            {
                "Type": "volume",
                "Name": "fd83740be3beed68e3592749bc30492832ed5d56084faa48d6ba6305814eba6c",  #name
                "Source": "/var/lib/docker/volumes/fd83740be3beed68e3592749bc30492832ed5d56084faa48d6ba6305814eba6c/_data",  #Host computer
                "Destination": "volume01",#Address in container
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            },
            {
                "Type": "volume",
                "Name": "74043b2e4ca2110706c73e76e6d04b49f58d5942a4dfd86ff0e66e4a9c89a94b",
                "Source": "/var/lib/docker/volumes/74043b2e4ca2110706c73e76e6d04b49f58d5942a4dfd86ff0e66e4a9c89a94b/_data",
                "Destination": "volume02",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],

Container data volume

Through the parameter -- volumes from, set container 2 and container 1 to establish the data volume mounting relationship.

docker run -d -p 6603:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7

docker run -d -p 6604:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7

The synchronization of two mysql databases is realized

For the transfer of configuration information between containers, the life cycle of data volume containers lasts until no container is used

Upload image

Upload to Docker Hub

#The previous image named yjwtomcat1 cannot be uploaded
[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
yjwtomcat1                      0                   0ae4a098790e        14 hours ago        692 MB
entorypoint-test                latest              7fe30dd55dc0        16 hours ago        231 MB
cmdtest                         latest              f5a0a65d1e51        16 hours ago        231 MB

#Use docker tag original name and current name to modify the image name
[root@iZ70eyv5ttqkcsZ ~]# docker tag yjwtomcat1:0 cancan1230987/yjwtomcat:1.0

#Modified image name
[root@iZ70eyv5ttqkcsZ ~]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
cancan1230987/yjwtomcat         1.0                 0ae4a098790e        14 hours ago        692 MB
yjwtomcat1                      0                   0ae4a098790e        14 hours ago        692 MB
entorypoint-test                latest              7fe30dd55dc0        16 hours ago        231 MB

#Upload succeeded
[root@iZ70eyv5ttqkcsZ ~]# docker push cancan1230987/yjwtomcat

docker run name

run command quick find

docker run -d -p 8088:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

Watch the crazy God video of station B and learn notes
[crazy God talking about Java] Docker's latest super detailed tutorial is easy to understand

Topics: Operation & Maintenance Docker Container