Docker notes sorting

docker history

In 2010, several young people set up dotcloud in the United States to do some pass cloud services.

lxc related container technology, they container their own technology

Talk about docker

Docker is developed based on GO language! Open source project!

Official website: https://www.docker.com/

Document address: https://docs.docker.com/ Super detailed

Warehouse address: https://hub.docker.com/

What can docker do

Previous virtual technology

Disadvantages of virtual technology

  1. Occupy more resources
  2. Redundant steps
  3. Slow start

Containerization Technology

Containerization technology is not a complete operating system for simulation

The difference between Docker and virtual machine

  • Traditional virtual machines create a complete set of hardware, run a complete set of virtual environment, and run and install software on the operating system
  • The container runs directly in the kernel. The container does not have its own kernel or virtual hardware, so it is lightweight
  • Each container is isolated from each other. Each container has its own file system and does not affect each other

Devops (development, operation and maintenance)

Faster operation and maintenance deployment

Traditional applications: a pile of documents, installation and operation

Docker: packaging image release test, one click operation

More convenient upgrade and capacity expansion

After using docker, publishing applications is like building blocks

The project is packaged as a mirror and can be run directly in other environments

Simpler operation and maintenance

After containerization, the development environment and test environment are highly consistent

More efficient resource utilization

Docker is kernel virtualization. Multiple container instances can be run on one physical machine, and the server performance can be squeezed to the extreme

Installation of Docker

Basic composition of Docker

Images

Docker image is a template through which container services can be created. Tomcat - > Run - > tomcat01 container (providing server). Multiple containers can be created through this image

Container

Docker uses container technology to run applications created through images

Start and delete basic commands

Repository

A place to store images!

Shared warehouse and private warehouse!

Docker hub (foreign by default)

Alibaba cloud... All have these warehouses (configure image acceleration)

Install Docker

Environmental preparation

  1. A little basic knowledge of linux
  2. CentOS 7
  3. Linking remote servers using XShell

Environment view

#System kernel above 3.10
[root@izuf6cn5k7l8xuxojhszqbz ~]# uname -r
3.10.0-862.14.4.el7.x86_64
#System version
[root@izuf6cn5k7l8xuxojhszqbz /]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

install

Help documentation: https://docs.docker.com/engine/install/centos/

# 1. Uninstall the old version
yum remove docker \
          docker-client \
          docker-client-latest \
          docker-common \
          docker-latest \
          docker-latest-logrotate \
          docker-logrotate \
          docker-engine
# 2. Download the required installation package
yum install -y yum-utils

# 3. Set image warehouse
yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo # defaults to foreign ones, which are very slow
    
yum-config-manager 
	--add-repo \ 
	http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo # recommends Alibaba cloud
# Update yum related index
yum makecache faste
# 4. Install Docker related content Docker CE Community Edition ee Enterprise Edition
yum install docker-ce docker-ce-cli containerd.io
# 5. Start docker
sudo systemctl start docker
# 6. Use docker version to check whether the installation is successful

# 7. hello-world
docker run hello-world

# 8. View the downloaded Hello world image
[root@izuf6cn5k7l8xuxojhszqbz /]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
redis               latest              235592615444        4 months ago        104MB
mysql               5.7                 9cfcce23593a        4 months ago        448MB
hello-world         latest              fce289e99eb9        21 months ago       1.84kB
logstash            6.4.0               13b7a09abaf8        2 years ago         670MB
kibana              6.4.0               a7e4cd1a7b45        2 years ago         667MB
elasticsearch       6.4.0               1ac676545731        2 years ago         791MB

Learn about uninstalling docker

# 1. Uninstall dependency
yum remove docker-ce docker-ce-cli containerd.io
# 2. Delete resources
rm -rf /var/lib/docker
#/Default working path of var/lib/docker docker

Alibaba cloud image acceleration

  1. Log in to alicloud and find the container service

  2. Image acceleration address

  3. Configuration use

    sudo mkdir -p /etc/docker
    sudo tee /etc/docker/daemon.json <<-'EOF'
    {
      "registry-mirrors": ["https://0b56c32l.mirror.aliyuncs.com"]
    }
    EOF
    sudo systemctl daemon-reload
    sudo systemctl restart docker
    

Review Hello World

Underlying principle

Docker is a client server system. The daemon of docker runs on the host and is accessed from the client through Socket

DockerServer accepts DockerClient commands

Why does Docker run faster than VM?

  1. Docker has fewer abstraction layers than virtual machines
  2. Docker uses the kernel of the host

Common commands of Docker

Help command

docker version    # Display Docker version information
docker info       # Displays the system information of Docker, including the number of images and containers
docker command --help # Help command

Help document address: https://docs.docker.com/engine/reference/run/

Mirror command

[root@izuf6cn5k7l8xuxojhszqbz ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
redis               latest              235592615444        4 months ago        104MB
mysql               5.7                 9cfcce23593a        4 months ago        448MB
hello-world         latest              fce289e99eb9        21 months ago       1.84kB
logstash            6.4.0               13b7a09abaf8        2 years ago         670MB
kibana              6.4.0               a7e4cd1a7b45        2 years ago         667MB
elasticsearch       6.4.0               1ac676545731        2 years ago         791MB

# explain
REPOSITORY Mirror warehouse source
TAG        Mirror label
IMAGE ID   image ID
CREATE	   Image creation time
SIZE       Mirror size

# Optional direction
Options:
  -a, --all             # List all mirrors
  -q, --quiet           # Show only mirror ID

docker search search image

[root@izuf6cn5k7l8xuxojhszqbz ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation...   10075               [OK]                
mariadb                           MariaDB is a community-developed fork of MyS...   3694                [OK]                
mysql/mysql-server                Optimized MySQL Server Docker images. Create...   736                                     [OK]
percona                           Percona Server is a fork of the MySQL relati...   511                 [OK]                

# Optional
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation...   10075               [OK]                
mariadb                           MariaDB is a community-developed fork of MyS...   3694                [OK]                
mysql/mysql-server                Optimized MySQL Server Docker images. Create...   736                                     [OK]
percona                           Percona Server is a fork of the MySQL relati...   511                 [OK]                

[root@izuf6cn5k7l8xuxojhszqbz ~]# docker search mysql --filter=stars=5000
NAME                DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql               MySQL is a widely used, open-source relation...   10075               [OK]                

docker pull Download Image

# docker pull image name [: tag]
docker pull mysql
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker pull mysql
Using default tag: latest   # If you do not write tag, the default is latest 
latest: Pulling from library/mysql
bb79b6b2107f: Pull complete # Layered download, the core of docker images, federated file system  
49e22f6fb9f7: Pull complete 
842b1255668c: Pull complete 
9f48d1f43000: Pull complete 
c693f0615bce: Pull complete 
8a621b9dbed2: Pull complete 
0807d32aef13: Pull complete 
9eb4355ba450: Pull complete 
6879faad3b6c: Pull complete 
164ef92f3887: Pull complete 
6e4a6e666228: Pull complete 
d45dea7731ad: Pull complete 
Digest: sha256:86b7c83e24c824163927db1016d5ab153a9a04358951be8b236171286e3289a4 #autograph
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # Real address

Delete image docker rmi

docker rmi -f 8e85dd5c3255            # Delete the specified image
docker rmi -f container ID container ID container ID container ID# Delete multiple mirrors
docker rmi -f ${docker images -aq}     # Delete all mirrors

Container command

Note: you can only create a container by creating a new image. For Linux, download a CentOS to learn

docker pull centos

Create a new container and start

docker run [Optional parameters] image
# Parameter description
--name	# Specify container name 
-it		# Use the interactive method to view the content in the background
-d		# Background operation
-p		# Specify port 8080:8080
	-p  Host port:Container port(Mapping of the most commonly used host port and container port)
	-p  ip:Host port:Container port
	-p  Container port
	    Container port
-P		# Randomly assigned ports

# Test, start and enter the container
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -it kibana:6.4.0 /bin/bash
bash-4.2$ [root@izuf6cn5k7l8xuxojhszqbz /]# 
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -it centos /bin/bash
# Check the CentOS in the container. Many functions of the basic version are not perfect
[root@a87299a142d9 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
 # Return the host from the container
[root@a87299a142d9 /]# exit
exit
[root@izuf6cn5k7l8xuxojhszqbz /]# ls
bin   dev                   get-docker.sh  ifstat-1.1.tar.gz  lost+found  mydata  root  srv  usr
boot  dubbo-governance.log  home           lib                media       opt     run   sys  var
d     etc                   ifstat-1.1     lib64              mnt         proc    sbin  tmp  zookeeper.out
[root@izuf6cn5k7l8xuxojhszqbz /]# 

# View image metadata
[root@izuf6cn5k7l8xuxojhszqbz /]# docker inspect b96481cf196e
[
    {
        "Id": "b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386",
        "Created": "2020-10-20T01:00:24.252614556Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 12492,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-10-20T02:00:50.534736639Z",
            "FinishedAt": "2020-10-20T02:00:50.11175616Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386/hostname",
        "HostsPath": "/var/lib/docker/containers/b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386/hosts",
        "LogPath": "/var/lib/docker/containers/b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386/b96481cf196efa193fd2981636b7d1a71ea7a7379ce46b5b603b6520c05c1386-json.log",
        "Name": "/xenodochial_cerf",
        "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,
            "Capabilities": null,
            "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/0ee9111d7dc3c174492b9aa2f3254982ed4b5f42ce5afb7d95cde986ef4472d5-init/diff:/var/lib/docker/overlay2/e88cb8fc7bd56dd63cbb631a8babb55716e65fb3705e0e5c2e0d5da2e6e7737b/diff",
                "MergedDir": "/var/lib/docker/overlay2/0ee9111d7dc3c174492b9aa2f3254982ed4b5f42ce5afb7d95cde986ef4472d5/merged",
                "UpperDir": "/var/lib/docker/overlay2/0ee9111d7dc3c174492b9aa2f3254982ed4b5f42ce5afb7d95cde986ef4472d5/diff",
                "WorkDir": "/var/lib/docker/overlay2/0ee9111d7dc3c174492b9aa2f3254982ed4b5f42ce5afb7d95cde986ef4472d5/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "b96481cf196e",
            "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": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200809",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "2e09d9086aeb52e6a6d5a7ada9b6c8531c0f7b322ccf6532cf169d3ba9756eab",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/2e09d9086aeb",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "63ef5e1ec21bc8973355b716d8dfa42e192efc0f1750ef18947b4f9d1410e512",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "adb8cb6caa43e42b2f3963607bf576207abb4a6a2b76c43f3907503f17dbdad9",
                    "EndpointID": "63ef5e1ec21bc8973355b716d8dfa42e192efc0f1750ef18947b4f9d1410e512",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:04",
                    "DriverOpts": null
                }
            }
        }
    }
]
[root@izuf6cn5k7l8xuxojhszqbz /]#

Exit container

exit 			# Exit and stop the container
ctrl + P + Q    # Exit without stopping the container

List all Docker running containers

docker ps
# parameter
 No parameters	  # Lists currently running containers
-a 		# List currently running containers + historically running containers
-n=?	# Displays recently created containers
-q		# Displays only the number of the container

Delete container

docker rm container ID					# Delete the container, but cannot delete the running container. If rm -f is forcibly deleted
docker rm -f ${docker ps -qa}	 # Delete all containers
docker ps -qa | xargs docker rm  # Delete all containers

Start and stop containers

docker start container ID		# Start container
docker restart container ID		# Restart container
docker stop container ID		# Stop container
docker kill container ID		# Force stop of current container

Common other commands

Docker process related commands

systemctl start docker		# Start Docker container
systemctl stop docker		# Stop Docker container
systemctl restart docker	# Restart Docker container
systemctl status docker		# View Docker container status
systemctl enable docker		# Set Docker to start automatically
docker top  container ID           # View container process information
[root@izuf6cn5k7l8xuxojhszqbz /]# docker top 0a01905d64f5 
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                16217               16201               0                   12:21               pts/0               00:00:00            /bin/bash
[root@izuf6cn5k7l8xuxojhszqbz /]# 

Background start command

# docker run -d image name

# Problem docker ps found that CentOS stopped running

# There must be a foreground process for docker to run in the background. If docker finds no application, it will stop automatically
# nginx will stop running when it finds that it does not provide services, that is, there is no program

View log command

docker logs -f -t --tail nubmer container ID
# Show log
- ft 		  # Show log
--tail number # Show logs and rows
[root@izuf6cn5k7l8xuxojhszqbz /]# docker logs -f -t --tail 10 d50135d540e2

Enter the currently running container

# Usually, the container runs in the background. It is often necessary to enter the container and modify some configurations
# Mode 1
docker exec -it container ID
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                               NAMES
bc3159d51302        kibana:6.4.0          "/bin/bash"              34 minutes ago      Up 34 minutes       5601/tcp                            romantic_euclid
abe8d2653a16        elasticsearch:6.4.0   "/usr/local/bin/dock..."   35 minutes ago      Up 35 minutes       9200/tcp, 9300/tcp                  elastic_ellis
89059be6a599        logstash:6.4.0        "/usr/local/bin/dock..."   36 minutes ago      Up 36 minutes       5044/tcp, 9600/tcp                  nostalgic_einstein
059363cf2047        0346349a1a64          "/bin/bash"              46 minutes ago      Up 46 minutes       80/tcp, 443/tcp                     nginx
edb16178fcae        centos                "/bin/bash"              About an hour ago   Up About an hour                                        nostalgic_allen
a956dc76e579        redis                 "docker-entrypoint.s..."   3 months ago        Up About an hour    0.0.0.0:6379->6379/tcp              redis
635d1b7ad286        mysql:5.7             "docker-entrypoint.s..."   3 months ago        Up About an hour    0.0.0.0:3306->3306/tcp, 33060/tcp   mysql
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it 635d1b7ad286 /bin/bash
root@635d1b7ad286:/#

# Mode 2
docker attach container ID # Enter container
[root@izuf6cn5k7l8xuxojhszqbz /]# docker attach 635d1b7ad286
[root@izuf6cn5k7l8xuxojhszqbz /]# ...

# The difference between the two methods
docker exec -it container ID # Enter the container and open a new terminal
docker attach container ID   # Entering the executing terminal will not start a new process

Copy files from container to host

docker cp
# Enter the docker container
[root@izuf6cn5k7l8xuxojhszqbz /]# docker exec -it edb16178fcae /bin/bash
[root@edb16178fcae /]# cd /home
[root@edb16178fcae home]# ls
# Create home file in container
[root@edb16178fcae home]# touch test.java
# Exit container
[root@edb16178fcae home]# exit
exit
[root@izuf6cn5k7l8xuxojhszqbz /]# ls
bin   d    dubbo-governance.log  get-docker.sh  ifstat-1.1         lib    lost+found  mnt     opt   root  sbin  sys  usr  zookeeper.out
boot  dev  etc                   home           ifstat-1.1.tar.gz  lib64  media       mydata  proc  run   srv   tmp  var
# Copy the files created in docker to the host directory
[root@izuf6cn5k7l8xuxojhszqbz /]# docker cp edb16178fcae:/home/test.java /home
[root@izuf6cn5k7l8xuxojhszqbz /]# cd home
[root@izuf6cn5k7l8xuxojhszqbz home]# ls
admin  es  FastDFS  hadoop  mysql  oracle  test.java
[root@izuf6cn5k7l8xuxojhszqbz home]#

# Copying is a manual process. In the future, the technical field of - v volume can be used to associate the container directory with the host directory / home /home

summary

Practice

Docker installation Ninx

# docker search nginx		# Search image
# docker pull nginx:1.1.0	# Download the specified version image
# View mirror
[root@izuf6cn5k7l8xuxojhszqbz /]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              0d120b6ccaa8        2 months ago        215MB
redis               latest              235592615444        4 months ago        104MB
mysql               5.7                 9cfcce23593a        4 months ago        448MB
rabbitmq            3.7.15-management   f05c3eb3cf91        15 months ago       179MB
hello-world         latest              fce289e99eb9        21 months ago       1.84kB
mongo               3.2                 fb885d89ea5c        23 months ago       300MB
logstash            6.4.0               13b7a09abaf8        2 years ago         670MB
kibana              6.4.0               a7e4cd1a7b45        2 years ago         667MB
elasticsearch       6.4.0               1ac676545731        2 years ago         791MB
nginx               1.10                0346349a1a64        3 years ago         182MB
# Parameter interpretation
# -d   		 Background operation
# --name 	 Name the container
# -p 		 Host port: container port
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -d --name ngnix01 -p 3344:80 nginx:1.10
fe9479484c55a8aa62719a65cf146c14ce9bfadf5e20090afcb8e38703ac2bec
[root@izuf6cn5k7l8xuxojhszqbz /]# curl localhost:3344

# Enter container
[root@izuf6cn5k7l8xuxojhszqbz /]# docker exec -it ngnix01 /bin/bash
root@fe9479484c55:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz /usr/share/man/man3/nginx.3pm.gz
root@fe9479484c55:/# cd /etc/nginx
root@fe9479484c55:/etc/nginx# ls
conf.d	fastcgi_params	koi-utf  koi-win  mime.types  modules  nginx.conf  scgi_params	uwsgi_params  win-utf
root@fe9479484c55:/etc/nginx# 

Docker installing Tomcat

# Docker pull Tomcat: Download Image Tomcat 9.0
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -d --name tomcat9 -p 3355:8080 tomcat:9.0
[root@izuf6cn5k7l8xuxojhszqbz /]# docker exec -it tomcat9 /bin/bash
root@5f17e0823840:/usr/local/tomcat# ls
BUILDING.txt	 LICENSE  README.md	 RUNNING.txt  conf  logs	    temp     webapps.dist
CONTRIBUTING.md  NOTICE   RELEASE-NOTES  bin	      lib   native-jni-lib  webapps  work
root@5f17e0823840:/usr/local/tomcat# cd webapps
root@5f17e0823840:/usr/local/tomcat/webapps# ls
root@5f17e0823840:/usr/local/tomcat/webapps#

Docker installation Es+kibana

# Multiple ES exposed ports
# ES consumes a lot of memory
# Generally, the directory of ES should be stored and mounted in a safe directory
# --net somenetwork network configuration
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag
# View docker stats
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPS="-Xms64m -Xms512m" elasticsearch:tag

visualization

  • Portal (use this first)

    docker run -d -p 8088:9000 \
    --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
    
  • Rancher(CI/CD reuse)

docker image

commit image

docker commit Submit the container as a new copy
# The principle of the command is similar to that of git
docker commit -m="Submit description information" -a="author" container ID Target image:[TAG]
docker commit -a="steven" -m="add webapps app" 5f17e0823840 tomcat02:1.0.0

Container data volume

Data volume usage

Method 1: use the command to mount - v

docker run -d -it -v Host Directory:Container directory -p Host port:Container port --name Container name
[root@izuf6cn5k7l8xuxojhszqbz home]# docker run -it -v /home/ceshi:/home centos /bin/bash

Test file synchronization

Benefit modification only needs to be modified in the host, and the container will be automatically synchronized

Install MySQL

# Get image
[root@izuf6cn5k7l8xuxojhszqbz /]# docker pull mysql:5.7
# The running container needs to be mounted!#To install and start MySQL, you need to set a password. Pay attention to it
# Start MySQL
-d Background operation
-p Port mapping
-v Data volume mount
-e Environment configuration
--name Container name
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -d -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=09091995aq --name mysql5.7 mysql:5.7

# After successful startup, test with Navicat link

# Create a database locally and view the mapping path

Named and anonymous mount

# Anonymous mount
# -v view path in container
docker run -d --name nginx01 -v /etc/nginx nginx
# View volume
[root@izuf6cn5k7l8xuxojhszqbz /]# docker volume ls
DRIVER              VOLUME NAME
local               843c675d3d847a6c57927c79a5886559482bf4916118f91627bfa35ebbbec45b
# This is anonymous mount -v, which only writes the path in the container, not the host path

# Named mount
[root@izuf6cn5k7l8xuxojhszqbz /]# docker run -d --name nginx1.10 -p 3344:80 -v juming_nginx:/etc/nginx nginx:1.10
1c70f133efdc35f9ce52ddafc7e128d88e833290e3815e2c8f1e5c2699319eb7
[root@izuf6cn5k7l8xuxojhszqbz /]# docker volume ls
DRIVER              VOLUME NAME
local               juming_nginx

If no directory is specified, all dockers are placed in: / var / lib / docker / volumes / xxx by default/_ Data directory

# Named mount, anonymous mount, specified directory mount
-v In container path		  # Anonymous mount
-v Container name:/Path in container # Named mount
-v Host path::/Path in container # Specified path mount

expand

# Control read and write permissions through -v paths in the container
# ro readonly read only
# rw readwrite
docker run -d --name nginx1.10 -p 3344:80 -v juming_nginx:/etc/nginx:ro nginx:1.10
docker run -d --name nginx1.10 -p 3344:80 -v juming_nginx:/etc/nginx:rw nginx:1.10

# ro can only modify the configuration through the host, which cannot be changed in the container

First acquaintance with DockerFile

DockerFile build Docker image file! Command script experience

# Create a DockerFile file with any name. It is recommended to use dockefile
# Content instruction (uppercase) parameter in file
FROM centos
VOLUME ['volume01','volume02']

CMD echo '-----------end-------------'
CMD /bin/bash
# Each command here is a layer of docker image

Start your own image

Viewing the volume hanging on the path: docker inspect container ID

Data volume container

Multiple MySQL synchronization data

docker run -it --name Container name --volumes-from Parent container name image name:Version number
docker run -it --name docker02 --volumes-from docker01 stevenyin/centos:1.10

DockerFile

DockerFile introduction

DockerFile is a file used to build a docker image! Command parameter script

Construction steps

  1. Write dockerfile script file
  2. Use docker build -f dockerfile path - t image name (stevenyin/centos:1.1.0)
  3. Run image docker run
  4. Publish image docker push(DockerHub, Alibaba cloud image warehouse)

Check out what the authorities do

DockerFile construction process

Basic knowledge

  1. Each reserved keyword (instruction) must be capitalized
  2. From top to bottom
  3. #Representative notes
  4. Each instruction builds a mirror layer

Dockerfile is development oriented. When you publish a project in the future, you need to write a dockerfile file to mirror it

step

  1. DockerFile: build file, define steps, equivalent to source code
  2. DockerImages: build and generate images through DockerFile, and finally release and run products
  3. DockerContainer: a container is an environment for running images

DockerFile instruction

FROM			# The basic image is built from here
MAINNTAINER		# Who wrote the image, author + email
RUN				# Image building is a command that needs to be run
ADD				# tomcat image. tomcat is a compressed package. Add content
WORKDIR			# Mirror working directory
VOLUME			# Directory mount
EXPOSE			# Burst port
CMD				# Specify the command to be run when the container starts. Only the last command will take effect and can be replaced
ENTRYPOINT		# Specify the command to be run when the container starts, and you can append the command
ONBUILD			# When running an inherited DockerFile, ONBUILD will be triggered
COPY			# Similar to ADD, copy the file to the container
ENV				# Setting environment variables

Building centos

# 1. Write configuration file dockerfile
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# vim mydockerfile-centos
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# cat mydockerfile-centos 
FROM centos
MAINTAINER steven<yinhaoye@qq.com>
ENV MYPATH /usr/local
WORKDIR $MYPATH
RUN yum -y install vim
RUN yum -y install net-tools
EXPOSE 80
CMD $MYPATH
CMD echo "------end------"
CMD /bin/bash
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# 
# 2. Build image through file
# Command docker build -f dockerfile -t image: [tag]
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker build -f /home/dockerfile/mydockerfile-centos -t stevenyin/centos:1.11 .
Successfully built 502fedcf049b
Successfully tagged stevenyin/centos:1.11

View docker build image history

# View docker image construction history
# docker history image ID
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker history  502fedcf049b
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
502fedcf049b        12 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin...   0B                  
a77ba559c57e        12 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo...   0B                  
32e6bf5b4d27        12 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "$MYP...   0B                  
5c37e637387e        12 minutes ago      /bin/sh -c #(nop)  EXPOSE 80                    0B                  
b80d50163d6d        12 minutes ago      /bin/sh -c yum -y install net-tools             22.8MB              
c682c6f2c7e5        12 minutes ago      /bin/sh -c yum -y install vim                   57.2MB              
a7a7c274e0db        13 minutes ago      /bin/sh -c #(nop) WORKDIR /usr/local            0B                  
2cd2577889b9        13 minutes ago      /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B                  
4c14c20e220e        13 minutes ago      /bin/sh -c #(nop)  MAINTAINER steven<yinhaoy...   0B                  
0d120b6ccaa8        2 months ago        /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
<missing>           2 months ago        /bin/sh -c #(nop)  LABEL org.label-schema.sc...   0B                  
<missing>           2 months ago        /bin/sh -c #(nop) ADD file:538afc0c5c964ce0d...   215MB               
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# 

Difference between CMD and ENTRYPOINT

CMD				# Specify the command to be run when the container starts. Only the last command will take effect and can be replaced
ENTRYPOINT		# Specify the command to be run when the container starts, and you can append the command

CMD test

# 1. Write dockerfile mydockerfile CMD
FROM centos
CMD ["ls","-a"]
# 2. Build image
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker build -f mydockerfile-cmd -t stevenyin/cmd:1.10 .
# run and find that ls -a takes effect
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker run stevenyin/cmd:1.10
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
opt
root
run
sbin
srv
sys
tmp
usr
var
# 3. Want to add the command - L LS - al
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker run stevenyin/cmd:1.10 -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"-l\": executable file not found in $PATH": unknown.
# In the case of CMD, -l replaces CMD ["ls","-a"] -l is not a command, so an error is reported

ENTRYPOINT test

# 1. Write DockerFile file
FROM centos
ENTRYPOINT ["ls","-a"]
# 2. Build image
docker build -f mydockerfile-entrypoint -t stevenyin/entrypoint:1.10 .
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker run stevenyin/entrypoint:1.10
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# docker run stevenyin/entrypoint:1.10 -l
total 56
drwxr-xr-x   1 root root 4096 Oct 25 02:22 .
drwxr-xr-x   1 root root 4096 Oct 25 02:22 ..
-rwxr-xr-x   1 root root    0 Oct 25 02:22 .dockerenv
lrwxrwxrwx   1 root root    7 May 11  2019 bin -> usr/bin
drwxr-xr-x   5 root root  340 Oct 25 02:22 dev
drwxr-xr-x   1 root root 4096 Oct 25 02:22 etc
drwxr-xr-x   2 root root 4096 May 11  2019 home
lrwxrwxrwx   1 root root    7 May 11  2019 lib -> usr/lib
lrwxrwxrwx   1 root root    9 May 11  2019 lib64 -> usr/lib64
drwx------   2 root root 4096 Aug  9 21:40 lost+found
drwxr-xr-x   2 root root 4096 May 11  2019 media
drwxr-xr-x   2 root root 4096 May 11  2019 mnt
drwxr-xr-x   2 root root 4096 May 11  2019 opt
dr-xr-xr-x 120 root root    0 Oct 25 02:22 proc
dr-xr-x---   2 root root 4096 Aug  9 21:40 root
drwxr-xr-x  11 root root 4096 Aug  9 21:40 run
lrwxrwxrwx   1 root root    8 May 11  2019 sbin -> usr/sbin
drwxr-xr-x   2 root root 4096 May 11  2019 srv
dr-xr-xr-x  13 root root    0 Oct 24 02:53 sys
drwxrwxrwt   7 root root 4096 Aug  9 21:40 tmp
drwxr-xr-x  12 root root 4096 Aug  9 21:40 usr
drwxr-xr-x  20 root root 4096 Aug  9 21:40 var
[root@izuf6cn5k7l8xuxojhszqbz dockerfile]# 

Publish image

DockerHub

  1. Registered account number: https://hub.docker.com/

  2. Login account

    [root@izuf6cn5k7l8xuxojhszqbz software]# docker login --help
    
    Usage:	docker login [OPTIONS] [SERVER]
    
    Log in to a Docker registry.
    If no server is specified, the default is defined by the daemon.
    
    Options:
      -p, --password string   Password
          --password-stdin    Take the password from stdin
      -u, --username string   Username
    [root@izuf6cn5k7l8xuxojhszqbz software]# 
    [root@izuf6cn5k7l8xuxojhszqbz software]# docker login -u stevenyin
    Password: 
    WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
    Configure a credential helper to remove this warning. See
    https://docs.docker.com/engine/reference/commandline/login/#credentials-store
    
    Login Succeeded
    [root@izuf6cn5k7l8xuxojhszqbz software]# 
    
  3. After logging in, you can submit the image, which is a docker push

[root@izuf6cn5k7l8xuxojhszqbz software]# docker push stevenyin/centos:1.11
The push refers to repository [docker.io/stevenyin/centos]
5bf7e4a8471d: Pushed 
bf760cbda826: Pushed 
291f6e44771a: Layer already exists 
digest1.11: digest: sha256:530a45736f79e50515baa5591fc76635184dd783089ec3e1ebb21c261137d8db size: 953
# Add tag: docker tag stevenyin/centos:1.12 for image

Publish to alicloud image service

  1. Log in to Alibaba cloud
  2. Container mirroring service found
  3. Create namespace

  1. Create container image

  1. Specific steps for pushing images

    1. Log in to alicloud Docker Registry
    $ sudo docker login --username=yinghaoye123aq registry.cn-shanghai.aliyuncs.com
     The user name used for login is the full name of Alibaba cloud account, and the password is the password set when opening the service.
    
    You can modify the credential password on the access credential page.
    
    2. from Registry Pull image from
    $ sudo docker pull registry.cn-shanghai.aliyuncs.com/aliyun-stevenyin/stevenyin:[Mirror version number]
    3. Push mirror to Registry
    $ sudo docker login --username=yinghaoye123aq registry.cn-shanghai.aliyuncs.com
    $ sudo docker tag [ImageId] registry.cn-shanghai.aliyuncs.com/aliyun-stevenyin/stevenyin:[Mirror version number]
    $ sudo docker push registry.cn-shanghai.aliyuncs.com/aliyun-stevenyin/stevenyin:[Mirror version number]
    Replace the image in the example according to the actual image information[ImageId]and[Mirror version number]Parameters.
    
    4. Select the appropriate mirror warehouse address
     from ECS When pushing an image, you can choose to use the intranet address of the image warehouse. The push speed will be improved and your public network traffic will not be lost.
    
    If you are using a machine located in VPC Network, please use registry-vpc.cn-shanghai.aliyuncs.com As Registry Domain name login.
    5. Example
     use"docker tag"Command renames the image and pushes it to via the VPC address Registry. 
    
    $ sudo docker images
    REPOSITORY                                                         TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
    registry.aliyuncs.com/acs/agent                                    0.7-dfb6816         37bb9c63c8b2        7 days ago          37.89 MB
    $ sudo docker tag 37bb9c63c8b2 registry-vpc.cn-shanghai.aliyuncs.com/acs/agent:0.7-dfb6816
     use "docker push" The command pushes the mirror to the remote.
    
    $ sudo docker push registry-vpc.cn-shanghai.aliyuncs.com/acs/agent:0.7-dfb6816
    

Docker network

Understand Docker0

# [root@izuf6cn5k7l8xuxojhszqbz ~]# docker run -d -p 3355:8080 --name tomcat9 tomcat:9.0
# Check the network address ip addr in the container. After startup, you will find 261: eth0@if262 IP address
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9 ip addr 
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
261: eth0@if262: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
[root@izuf6cn5k7l8xuxojhszqbz ~]# 

# Can linux ping the container
[root@izuf6cn5k7l8xuxojhszqbz ~]# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.086 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.070 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.060 ms

principle

  1. Every time a docker container is started, docker will assign an IP to the docker container. As long as docker is installed, the network card of docker0 bridging mode will be generated. The technology used is evth pair technology!

  1. Start a container again and find another pair of network cards

# The network cards brought by the container are one-to-one
# Evth pair is a pair of virtual network device interfaces. They appear in pairs. One end is connected to the protocol and the other end is connected to each other
  1. The two containers can be ping ed
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9 ping 172.17.0.3
# Containers can be ping ed

network model

When the network is not specified, it is routed by docker0, and docker will assign an available IP by default

Docker uses the bridge in liunx, and the host is the bridge in docker, docker0

–link

# You cannot ping another container through the service name, but only through IP
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9.1 ping tomcat9
ping: tomcat9: Name or service not known
[root@izuf6cn5k7l8xuxojhszqbz ~]# 
# Through -- link, you can connect containers through the container name

[root@izuf6cn5k7l8xuxojhszqbz ~]# docker run -d -P --name tomcat9.2 --link tomcat9 tomcat:9.0
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9.2 ping tomcat9
PING tomcat9 (172.17.0.2) 56(84) bytes of data.
64 bytes from tomcat9 (172.17.0.2): icmp_seq=1 ttl=64 time=0.095 ms
64 bytes from tomcat9 (172.17.0.2): icmp_seq=2 ttl=64 time=0.066 ms
64 bytes from tomcat9 (172.17.0.2): icmp_seq=3 ttl=64 time=0.064 ms

Explore inspect

tomcat9. Tom2 is configured locally

# Configure it in hosts and stay away from finding it here
[root@izuf6cn5k7l8xuxojhszqbz /]# docker exec -it tomcat9.2 cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.2	tomcat9 a3d12cff39da
172.17.0.4	7f5cb56cad3f
[root@izuf6cn5k7l8xuxojhszqbz /]#

Essence exploration: – link is to add the mapping of 172.17.0.2 tomcat9 a3d12cff39da in the hosts file

Limitation: docker0 does not support access to container names

Custom network

View network

Network mode

Bridge: bridge network docker (by default, there is also a bridge mode for self creation)

none: no network configuration

Host: share network with host

Container: the container can be connected (less used, not recommended)

test

# Start directly -- net bridge is docker0 by default
docker run -d -P --name tomcat9 --net bridge tomcat:9.0

# docker0 cannot be accessed through the domain name, but can be connected through -- link

# Custom network
--driver bridge Bridging mode
--subnet 192.168.0.0/16 Subnet address
--gateway 192.168.0.1 gateway
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
36c4197f8b73de837495b148d4b95a2f03c6747608733a2b5d506b98c653f034
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
1edaf6a32eb9        bridge              bridge              local
18b32561b08d        host                host                local
abdd0e9a3c22        mydata_default      bridge              local
36c4197f8b73        mynet               bridge              local
a7f1b5a0ad78        none                null                local
[root@izuf6cn5k7l8xuxojhszqbz ~]#

# Use custom network launch container
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker run -d -P --name tomcat9.1 --net mynet tomcat:9.0
658aab97504ae8ee63204c78bd431fc37b41677c51121fa96c2041961d912a80
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker run -d -P --name tomcat9.2 --net mynet tomcat:9.0
97216395cd5188beab139a3f957019d42aa1b9da91a26d6b3cfd907fabc6b78f
# View custom network
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "36c4197f8b73de837495b148d4b95a2f03c6747608733a2b5d506b98c653f034",
        "Created": "2020-10-25T21:45:21.745587216+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/16",
                    "Gateway": "192.168.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "658aab97504ae8ee63204c78bd431fc37b41677c51121fa96c2041961d912a80": {
                "Name": "tomcat9.1",
                "EndpointID": "168eb519cd776907149fd9d97121e0a068f2ea28a6b81e86cbac04b742d82721",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "97216395cd5188beab139a3f957019d42aa1b9da91a26d6b3cfd907fabc6b78f": {
                "Name": "tomcat9.2",
                "EndpointID": "00b1cc23a06c62087e7606b8b5286807ce0b7c3aca7d43a26cb8362147d10416",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
[root@izuf6cn5k7l8xuxojhszqbz ~]# 
# Again, you can access it through the container name without -- link
[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9.1 ping tomcat9.2
PING tomcat9.2 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat9.2.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.065 ms
64 bytes from tomcat9.2.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.070 ms
64 bytes from tomcat9.2.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.066 ms
[root@izuf6cn5k7l8xuxojhszqbz ~]# 

Network connectivity

 # Network Unicom docker network connect network name container name
 docker network connect mynet tomcat9.2.2
 # China Unicom will tomcat9 1.1 put it under mynet network
 # One container, two IP S

[root@izuf6cn5k7l8xuxojhszqbz ~]# docker exec -it tomcat9.1 ping tomcat9.1.1
PING tomcat9.1.1 (192.168.0.4) 56(84) bytes of data.
64 bytes from tomcat9.1.1.mynet (192.168.0.4): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from tomcat9.1.1.mynet (192.168.0.4): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from tomcat9.1.1.mynet (192.168.0.4): icmp_seq=3 ttl=64 time=0.082 ms
[root@izuf6cn5k7l8xuxojhszqbz ~]# 

Actual deployment of Redis cluster

for port in $(seq 1 6);\
do \
mkdir -p /mydata/redis/node-${port}/conf
touch /mydata/redis/node-${port}/conf/redis.conf
cat << EOF >/mydata/redis/node-${port}/conf/redis.conf
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.30.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379 
appendonly yes
EOF
done
# Start reids container
docker run -p 6371:6379 -p 16371:16379 --name redis-1 \
-v /mydata/redis/node-1/data:/data \
-v /mydata/redis/node-1/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6372:6379 -p 16372:16379 --name redis-2 \
-v /mydata/redis/node-2/data:/data \
-v /mydata/redis/node-2/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.12 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6373:6379 -p 16373:16379 --name redis-3 \
-v /mydata/redis/node-3/data:/data \
-v /mydata/redis/node-3/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.13 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6374:6379 -p 16374:16379 --name redis-4 \
-v /mydata/redis/node-4/data:/data \
-v /mydata/redis/node-4/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.14 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6375:6379 -p 16375:16379 --name redis-5 \
-v /mydata/redis/node-5/data:/data \
-v /mydata/redis/node-5/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.15 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

docker run -p 6376:6379 -p 16376:16379 --name redis-6 \
-v /mydata/redis/node-6/data:/data \
-v /mydata/redis/node-6/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.30.0.16 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf

# Create cluster
[root@izuf6cn5k7l8xuxojhszqbz /]# docker exec -it redis-1 /bin/sh
/data # redis-cli --cluster create 172.30.0.11:6379 172.30.0.12:6379 172.30.0.13:6379 172.30.0.14:6379 172.30.0.15:6379 172.30.0.16:6379 --c
luster-replicas 1
>>> Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 172.30.0.15:6379 to 172.30.0.11:6379
Adding replica 172.30.0.16:6379 to 172.30.0.12:6379
Adding replica 172.30.0.14:6379 to 172.30.0.13:6379
M: 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 172.30.0.11:6379
   slots:[0-5460] (5461 slots) master
M: 039ee87ac86de914417233448396a3c089669a2b 172.30.0.12:6379
   slots:[5461-10922] (5462 slots) master
M: f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6 172.30.0.13:6379
   slots:[10923-16383] (5461 slots) master
S: 534e73cf9cd34bac9d43fce82cdb2e1be90d9fdf 172.30.0.14:6379
   replicates f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6
S: 20fe1f4923f790377cbaffaf99f9d45558bbd017 172.30.0.15:6379
   replicates 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd
S: a7562cb7fa1cda8321295b12e3ffc3d844665cce 172.30.0.16:6379
   replicates 039ee87ac86de914417233448396a3c089669a2b
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join
..
>>> Performing Cluster Check (using node 172.30.0.11:6379)
M: 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 172.30.0.11:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
S: 20fe1f4923f790377cbaffaf99f9d45558bbd017 172.30.0.15:6379
   slots: (0 slots) slave
   replicates 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd
S: 534e73cf9cd34bac9d43fce82cdb2e1be90d9fdf 172.30.0.14:6379
   slots: (0 slots) slave
   replicates f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6
M: 039ee87ac86de914417233448396a3c089669a2b 172.30.0.12:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
M: f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6 172.30.0.13:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: a7562cb7fa1cda8321295b12e3ffc3d844665cce 172.30.0.16:6379
   slots: (0 slots) slave
   replicates 039ee87ac86de914417233448396a3c089669a2b
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
/data # 

# Test cluster
/data # redis-cli -c
127.0.0.1:6379> cluster info
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:480
cluster_stats_messages_pong_sent:475
cluster_stats_messages_sent:955
cluster_stats_messages_ping_received:470
cluster_stats_messages_pong_received:480
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:955
127.0.0.1:6379> cluster nodes
20fe1f4923f790377cbaffaf99f9d45558bbd017 172.30.0.15:6379@16379 slave 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 0 1603708641983 5 connected
534e73cf9cd34bac9d43fce82cdb2e1be90d9fdf 172.30.0.14:6379@16379 slave f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6 0 1603708641000 4 connected
96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 172.30.0.11:6379@16379 myself,master - 0 1603708640000 1 connected 0-5460
039ee87ac86de914417233448396a3c089669a2b 172.30.0.12:6379@16379 master - 0 1603708640580 2 connected 5461-10922
f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6 172.30.0.13:6379@16379 master - 0 1603708640000 3 connected 10923-16383
a7562cb7fa1cda8321295b12e3ffc3d844665cce 172.30.0.16:6379@16379 slave 039ee87ac86de914417233448396a3c089669a2b 0 1603708640000 6 connected
127.0.0.1:6379> set a b
-> Redirected to slot [15495] located at 172.30.0.13:6379
OK
172.30.0.13:6379> get a
^C
/data # redis-cli -c
127.0.0.1:6379> get a
-> Redirected to slot [15495] located at 172.30.0.14:6379
"b"
172.30.0.14:6379> cluster nodes
534e73cf9cd34bac9d43fce82cdb2e1be90d9fdf 172.30.0.14:6379@16379 myself,master - 0 1603708963000 7 connected 10923-16383
a7562cb7fa1cda8321295b12e3ffc3d844665cce 172.30.0.16:6379@16379 slave 039ee87ac86de914417233448396a3c089669a2b 0 1603708964000 2 connected
039ee87ac86de914417233448396a3c089669a2b 172.30.0.12:6379@16379 master - 0 1603708964000 2 connected 5461-10922
f9de7fd7bf12f7a10ac24155b6b4d8fef6d61ad6 172.30.0.13:6379@16379 master,fail - 1603708902628 1603708901000 3 connected
96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 172.30.0.11:6379@16379 master - 0 1603708965564 1 connected 0-5460
20fe1f4923f790377cbaffaf99f9d45558bbd017 172.30.0.15:6379@16379 slave 96d6e1f4ad84f8c9101401bea7408f97e6c56bcd 0 1603708964563 1 connected
172.30.0.14:6379> 


docker cluster setup completed!

Install ZooKeeper

1, Stand alone construction

  1. Download Image

    [root@izuf6cn5k7l8xuxojhszqbz ~]# docker pull zookeeper:3.5
    
  2. Create data mount directory

    /mydata/zookeeper/conf
    /mydata/zookeeper/data
    /mydata/zookeeper/datalog

  3. Run zookeeper

    docker run -d --name zookeeper3.5 \
    --restart always \
    -p 2181:2181 -p 2888:2888 -p 3888:3888 \
    -v /mydata/zookeeper/conf:/conf \
    -v /mydata/zookeeper/data:/data \
    -v /mydata/zookeeper/datalog:/datalog \
    zookeeper:3.5
    
  4. Enter zookeeper container

    [root@izuf6cn5k7l8xuxojhszqbz zookeeper]# docker exec -it  zookeeper3.5 /bin/bash
    root@1d0a2f5178b8:/apache-zookeeper-3.5.8-bin/bin# ls
    README.txt    zkCli.cmd  zkEnv.cmd  zkServer-initialize.sh  zkServer.sh		 zkTxnLogToolkit.sh
    zkCleanup.sh  zkCli.sh	 zkEnv.sh   zkServer.cmd	    zkTxnLogToolkit.cmd
    root@1d0a2f5178b8:/apache-zookeeper-3.5.8-bin/bin# ./zkCli.sh
    Connecting to localhost:2181
    log4j:WARN No appenders could be found for logger (org.apache.zookeeper.ZooKeeper).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    Welcome to ZooKeeper!
    JLine support is enabled
    
    WATCHER::
    
    WatchedEvent state:SyncConnected type:None path:null
    [zk: localhost:2181(CONNECTED) 0] create /test test
    Created /test
    [zk: localhost:2181(CONNECTED) 1] get /test
    test
    [zk: localhost:2181(CONNECTED) 2]
    

2, Cluster construction

  1. Create a zookeeper cluster folder under / mydata /

    mkdir zookeeper-cluster
    
  2. Create three zookeeper0x folders under / mydata / zookeeper cluster

    mkdir zookeeper01
    mkdir zookeeper02
    mkdir zookeeper03
    
  3. Each zookeeper0x is created as follows

    mkdir conf data datalog
    
    1. Create docker compose.com in / mydata / zookeeper cluster directory YML file and write
    touch docker-compose.yml  //create a file
    vim docker-compose.yml   //Enter vim compiler
    

    Write docker compose YML file

    version: '3'#Fixed version number
    services:
        zoo1:
            image: zookeeper #Mirror used
            restart: always #Automatic restart after downtime
            hostname: zoo1 #The host (parent container) name that hosts the zookeeper container can be omitted
            container_name: zoo1 #Container name
            privileged: true #Using this parameter, the root in the container has the real root right. The container started by privileged can see many devices on the host and execute mount. It even allows you to start the docker container in the docker container.
            ports: #Port mapping for hosts and containers
                - "2181:2181" 
            volumes:  #Create the mount directory of the zookeeper container on the host
                - /mydata/zookeeper-cluster/zookeeper01/data:/data #data
                - /mydata/zookeeper-cluster/zookeeper01/datalog:/datalog #journal
                - /mydata/zookeeper-cluster/zookeeper01/conf:/conf #configuration file
            environment: #zookeeper3.4 and zookeeper 3.5 stay docker This is the difference in setting up clusters in the environment #zoo1 is the container name and also the host name, which means using the intranet communication of the container (1) zookeeper 3 Zoom specified in 5_ "; 2181" is added after the ip address and port number of the servers parameter. (2)ZOO_ When servers specifies the ip address, the local ip address is written as 0.0.0.0.
                ZOO_MY_ID: 1
                ZOO_SERVERS: server.1=0.0.0.0:2888:3888;2181 server.2=zoo2:2888:3888;2181 server.3=zoo3:2888:3888;2181
        zoo2:
            image: zookeeper
            restart: always
            hostname: zoo2
            container_name: zoo2
            privileged: true
            ports:
                - "2182:2181"
            volumes:
               - /mydata/zookeeper-cluster/zookeeper02/data:/data
               - /mydata/zookeeper-cluster/zookeeper02/datalog:/datalog
               - /mydata/zookeeper-cluster/zookeeper02/conf:/conf
            environment:
                ZOO_MY_ID: 2
                ZOO_SERVERS: server.1=zoo1:2888:3888;2181 server.2=0.0.0.0:2888:3888;2181 server.3=zoo3:2888:3888;2181
        zoo3:
            image: zookeeper
            restart: always 
            hostname: zoo3
            container_name: zoo3
            privileged: true
            ports: 
                - "2183:2181"
            volumes:
               - /mydata/zookeeper-cluster/zookeeper03/data:/data
               - /mydata/zookeeper-cluster/zookeeper03/datalog:/datalog
               - /mydata/zookeeper-cluster/zookeeper03/conf:/conf
            environment:
                ZOO_MY_ID: 3
                ZOO_SERVERS: server.1=zoo1:2888:3888;2181 server.2=zoo2:2888:3888;2181 server.3=0.0.0.0:2888:3888;2181
    
    
    1. Run docker compose YML file
    docker-compose up -d
    
    1. Stop cluster
    docker-compose down
    
    1. View the created zookeeper cluster
    docker ps
     Or in docker-compose.yml File directory input
    docker-compose ps
    

Docker Compose

brief introduction

Docker Compose defines, runs and manages containers

A docker-compose.yml looks like this:

version: "3.8"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
      - logvolume01:/var/log
    links:
      - redis
  redis:
    image: redis
volumes:
  logvolume01: {}

Compose concept

  1. service, container, application (web, Redis, MySQL...)
  2. Project, a set of associated containers

install

  1. Run and install Compose
curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

  1. Give docker compose executable permission
sudo chmod +x /usr/local/bin/docker-compose

  1. Quick start: https://docs.docker.com/compose/gettingstarted/

Tags: Docker

Posted by erax on Thu, 14 Apr 2022 05:07:45 +0930