CI/CD—Docker Beginner Learning

1 docker understanding

1 Introduction to Docker

Docker is an open source application container virtualization technology based on the Go language. The main goal of Docker is to build, ship and run any app, anywhere, that is, through the management of the life cycle of application components such as encapsulation, distribution, deployment, and operation, to achieve one-time encapsulation and run everywhere at the application component level (from the official website). The application component here can be a web application, a set of database services, or even an operating system or compiler.

In layman's terms, Docker can be compared to VMware. If you want to run in the production environment, you can directly package the local application and the required environment into a mirror, and run the mirror in Docker, so that you can solve the problem of testing environment and Inconsistencies in the production environment. (The image can be compared to our common ubuntu.iso image file.)

Why is there Docker
to fundamentally solve the problem of inconsistent development and operation and maintenance environments. That is to say, at the time of installation, the original environment is copied exactly, and developers can use Docker to eliminate the problem of "it works normally on my machine" when collaborative coding. When developing an application, package the files required by the application into an image file, and run the image in docker. So as to achieve a mirror image, run everywhere.

Docker uses features in the Linux kernel to simulate multiple virtual environments on an operating system. The applications in these environments all run on the same operating system, share the resources of the operating system, and do not need to install a separate operating system for each application. In this way, different environments will not interfere with each other , and the resource consumption is very small. The number of Docker containers that can run under the same hardware configuration far exceeds the number of traditional virtual machines.

Docker is a very powerful platform that helps developers quickly build, test and deploy containerized applications. At the same time, Docker can also ensure the portability and operation stability of the application, and can also improve the performance of the server. Therefore, the use of Docker technology is very promising, it can make software development and deployment more flexible, efficient and secure.

Compare the difference between Docker and virtual machine technology:

  • A traditional virtual machine virtualizes a piece of hardware, runs a complete operating system, and then installs and runs software on this system.
  • The application in the container runs directly in the kernel of the host machine. The container does not have its own kernel or virtual hardware, so it is portable.
  • Each container is isolated from each other, and each container has its own file system, which does not affect each other.

2 Docker installation

insert image description here
Image (image)
A Docker image is a read-only template that can be used to create a Docker container. Images can contain operating systems, applications, dependent libraries, configuration files, and more.

Container (container)
A Docker container is a running instance of a Docker image, which can be understood as a lightweight virtual machine.

Repository (repository)
Docker warehouse is used to store and manage Docker images, similar to code warehouse. Docker officially provides the Docker Hub repository, where Docker images can be stored and shared. Users can also build their own private warehouses to store and manage their own Docker images.

To sum up, Docker images are the basis for creating Docker containers, Docker containers are running instances of Docker images, and Docker warehouses are where Docker images are stored and managed. By using Docker images, containers, and warehouses, the rapid deployment, operation, and management of applications can be realized, and the portability and scalability of applications can be improved.

# 1.卸载旧版本
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
                  
# 2.需要的安装包
yum install -y yum-utils

# 3.设置镜像的仓库
# 3.1.默认是国外的,不推荐
yum-config-manager \ 
	--add-repo \ 	
	https://download.docker.com/linux/centos/docker-ce.repo
# 3.2.推荐使用国内的	(这里手敲代码然后复制网站)
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 4.更新yum软件包索引 
yum makecache fast

# 5.安装docker docker-ce 社区版 ee 是企业版
yum install docker-ce docker-ce-cli containerd.io

# 6、启动docker
systemctl start docker

# 7、使用 docker version 查看是否安装成功
docker version

docker run hello-world
insert image description here
docker images
insert image description here
uninstall docker

# 1.卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
# 2.删除资源
rm -rf /var/lib/docker
# /var/lib/docker docker的默认工作路径

3 Alibaba Cloud Image Acceleration

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

4 Review the flowchart of hello-world leading to docker run

insert image description here
insert image description here

5 underlying principles

How does Docker work?

  • Docker is a system of Client-Server structure, and Docker's daemon process runs on the host. Access from client side via Socket.
  • Docker-Server will execute this command after receiving the command from Docker-Client.

insert image description here
Why is Docker faster than VM?
insert image description here

Docker has fewer abstraction layers than virtual machines: since docker does not require Hypervisor to virtualize hardware resources, programs running on docker containers directly use the hardware resources of actual physical machines. Therefore, docker will have obvious advantages in efficiency in terms of CPU and memory utilization.

When creating a new container, docker does not need to reload an operating system kernel like a virtual machine, avoiding booting and loading the operating system kernel. The virtual machine loads Guset OS at the level of minutes, while docker uses the operating system of the host machine, omitting this complicated process at the level of seconds, so it only takes a few seconds to create a new docker container.

2 docker common command learning

1 Common commands of Docker

Help command:

docker version	# 显示docker的版本信息。
docker info		# 显示docker的系统信息,包括镜像和容器的数量
docker --help	# 帮助命令

Mirror command:

docker images # 查看所有本地主机上的镜像 可以使用docker image ls代替
docker search # 搜索镜像 
docker pull   下载镜像  docker image pull 
docker rmi 	 删除镜像  docker image rm

docker images View all images on the local host:

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   6 months ago   13.3kB

# 解释 
REPOSITORY 		# 镜像的仓库源 
TAG 			# 镜像的标签 
IMAGE ID 		# 镜像的id 
CREATED 		# 镜像的创建时间 
SIZE 			# 镜像的大小

# 可选项 Options:
	-a, --all      # 列出所有的镜像
	-q, --quiet    # 只显示镜像的id

docker search search image:

[root@iZf8z4ii45kfjc41qrt363Z /]# docker search mysql
NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                            MySQL is a widely used, open-source relation…   12298     [OK]       
mariadb                          MariaDB Server is a high performing open sou…   4730      [OK]       

# 可选项
--filter=STARS=3000 搜索出来的镜像就是STARS大于3000的

insert image description here
docker pull download image:

# 下载镜像 docker pull 镜像名[:tag]		(tag是版本)
[root@iZf8z4ii45kfjc41qrt363Z /]# docker pull mysql
Using default tag: latest	# 如果不写tag,默认就是latest最新版
latest: Pulling from library/mysql
72a69066d2fe: Pull complete  # 分层下载:docker image 的核心---联合文件系统
93619dbc5b36: Pull complete 
99da31dd6142: Pull complete 
626033c43d70: Pull complete 
37d5d7efb64e: Pull complete 
ac563158d721: Pull complete 
d2ba16033dad: Pull complete 
688ba7d5c01a: Pull complete 
00e060b6d11d: Pull complete 
1c04857f594f: Pull complete 
4d7cfa90e6ea: Pull complete 
e0431212d27d: Pull complete 
Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709		# 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest	# 真实地址
# 两条命令等价
docker pull mysql
docker.io/library/mysql:latest
# 指定版本下载
docker pull mysql:5.7

insert image description here

docker rmi delete image:

docker rmi -f 镜像id                # 删除指定的镜像
docker rmi -f 镜像id 镜像id 镜像id  # 删除多个镜像
docker rmi -f $(docker images -aq) # 删除全部镜像

insert image description here

Container command:
Description: We can create a container only when we have a mirror, linux, download a centos mirror to test and learn

docker pull centos

Create a new container and start it:

docker run [可选参数] image

# 参数说明
--name = "Name"    容器名字  tomcat01,tomcat02,用来区分容器
-d                 后台方式运行
-it                使用交互方式运行,进入容器查看内容
-p                 指定容器的端口 -p 8080:8080
    -p ip:主机端口:容器端口
    -p 主机端口:容器端口(常用)
    -p 容器端口
    容器端口
-P                 随机指定端口
# 测试,启动并进入容器
docker 容器是由 docker 镜像创建的运行实例
[root@iZf8z4ii45kfjc41qrt363Z /]# docker run -it centos /bin/bash
[root@0e1dfb1233d0 /]# ls	# 查看容器内的centos,基础版本,很多命令都是不完善的!
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
# 从容器中退回主机
[root@0e1dfb1233d0 /]# exit
exit
[root@iZf8z4ii45kfjc41qrt363Z /]# ls
bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  patch  proc  root  run  sbin  srv  sys  tmp  usr  var  www

List all running containers:

# docker ps 命令
       # 列出当前正在运行的容器
  -a   # 列出当前正在运行的容器+带出历史运行过的容器
  -n=? # 显示最近创建的容器	?代表个数
  -q   # 只显示容器的编号

insert image description here
Exit the container:

exit            # 直接容器停止并退出
Ctrl + P + Q    # 容器不停止退出

insert image description here

Delete container:

docker rm 容器id                  # 删除指定容器,不能删除正在运行的容器,如果要强制删除 rm -f	(f是force)
docker rm -f $(docker ps -aq)    # 删除所有的容器
docker ps -aq|xargs docker rm    # 删除所有的容器

insert image description here

Operations to start and stop containers:

  • run is to create and start a container (run is equivalent to creating and running), start is to start a stopped container (start only runs)
docker start 容器id        # 启动容器
docker restart 容器id      # 重启容器
docker stop 容器id         # 停止当前正在运行的容器
docker kill 容器id         # 强制停止当前容器

insert image description here

2 Other common commands

Start the container in the background:

# 命令 docker run -d 镜像名
docker run -d centos

# 问题docker ps, 发现 centos 停止了

# 常见的坑, docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
# 如nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

View logs:

# 自己编写一段shell脚本
[root@iZf8z4ii45kfjc41qrt363Z /]# docker run -d centos /bin/sh -c "while true; do echo kuangshen;sleep 1;done"

# 显示日志
-t                # 显示日志加时间
-f				  # 保留打印窗口,持续打印
--tail number     # 要显示的最后的日志条数

[root@iZf8z4ii45kfjc41qrt363Z /]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
babf34105183   centos    "/bin/sh -c 'while t…"   20 seconds ago   Up 19 seconds             strange_blackburn

[root@iZf8z4ii45kfjc41qrt363Z /]# docker logs -tf --tail 10 babf34105183

insert image description here
After the test, remember to enter docker stop id to stop the program

Check the process information ps in the container:

# 命令 docker top 容器id
[root@iZf8z4ii45kfjc41qrt363Z /]# docker top 6eb73bae2d0b
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                9659                9639                0                   17:03               ?                   00:00:00            /bin/sh -c while true; do echo kuangshen;sleep 1;done
root                9908                9659                0                   17:05               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

View image source data:

# 命令 docker inspect 容器id
[root@iZf8z4ii45kfjc41qrt363Z /]# docker inspect 6eb73bae2d0b
[
    {
    
    
        "Id": "6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361",
        "Created": "2022-03-24T09:03:47.369280208Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true; do echo kuangshen;sleep 1;done"
        ],
        "State": {
    
    
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 9659,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-03-24T09:03:47.61951026Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361/hostname",
        "HostsPath": "/var/lib/docker/containers/6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361/hosts",
        "LogPath": "/var/lib/docker/containers/6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361/6eb73bae2d0ba7ebb21d1c33074236f9c850c77f964eda699d6338ec2a47a361-json.log",
        "Name": "/keen_neumann",
        "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/881b23da0c743bec39df6695b3f1691213412169e5dd677123f77c9920465c98-init/diff:/var/lib/docker/overlay2/d6b2cfa67a8bba2aed03ec55e57f82ea531461979f05ad93498aef4a20cf046e/diff",
                "MergedDir": "/var/lib/docker/overlay2/881b23da0c743bec39df6695b3f1691213412169e5dd677123f77c9920465c98/merged",
                "UpperDir": "/var/lib/docker/overlay2/881b23da0c743bec39df6695b3f1691213412169e5dd677123f77c9920465c98/diff",
                "WorkDir": "/var/lib/docker/overlay2/881b23da0c743bec39df6695b3f1691213412169e5dd677123f77c9920465c98/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
    
    
            "Hostname": "6eb73bae2d0b",
            "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 kuangshen;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
    
    
                "org.label-schema.build-date": "20210915",
                "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": "c3eeb47321de559d83851e35eee18915a2cff7f5c33ca36d200e4a9c25bafe4b",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
    
    },
            "SandboxKey": "/var/run/docker/netns/c3eeb47321de",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "89db5e9e1749f5c1097bea5edf127dccec3338bad26f0123aa18a144c6c30bd0",
            "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": "aed4526fdfd2fad1b4c6b8e1aafb1b44713eed863d0d40deb4461782e6ed35ff",
                    "EndpointID": "89db5e9e1749f5c1097bea5edf127dccec3338bad26f0123aa18a144c6c30bd0",
                    "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
                }
            }
        }
    }
]

Enter the currently running container:

# 我们的容器通常都是使用后台方式运行的,若要进入容器,需要修改一些配置

# 命令
docker exec -it 容器id baseShell

# 测试
[root@iZf8z4ii45kfjc41qrt363Z /]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
6eb73bae2d0b   centos    "/bin/sh -c 'while t…"   6 minutes ago   Up 6 minutes             keen_neumann
[root@iZf8z4ii45kfjc41qrt363Z /]# docker exec -it 6eb73bae2d0b /bin/bash
[root@6eb73bae2d0b /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@6eb73bae2d0b /]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 09:03 ?        00:00:00 /bin/sh -c while true; do echo kuangshen;sleep 1;done
root       396     0  0 09:10 pts/0    00:00:00 /bin/bash
root       419     1  0 09:10 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root       420   396  0 09:10 pts/0    00:00:00 ps -ef

# 方式二
docker attach 容器id

# 测试
[root@iZf8z4ii45kfjc41qrt363Z /]# docker attach 6eb73bae2d0b
kuangshen
kuangshen
正在执行当前的代码...

# docker exec        # 进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach      # 进入容器正在执行的终端,不会启动新的进程

Copy from the container to the host:

# 命令
docker cp [r] 容器id :容器内路径 目的地主机路径
# 参数r : 递归拷贝
# 测试

# 查看当前主机目录下的文件
[root@iZf8z4ii45kfjc41qrt363Z home]# ls
kuangshen  kuangshen.java  kuangstudy2  redis  test1  www
[root@iZf8z4ii45kfjc41qrt363Z home]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS              PORTS     NAMES
0b03b728988b   centos    "/bin/bash"   About a minute ago   Up About a minute             magical_rubin

# 进入docker容器内部
[root@iZf8z4ii45kfjc41qrt363Z home]# docker attach 0b03b728988b
[root@0b03b728988b /]# cd /home     
[root@0b03b728988b home]# ls

# 在容器内新建一个文件
[root@0b03b728988b home]# touch test.java
[root@0b03b728988b home]# exit
exit
[root@iZf8z4ii45kfjc41qrt363Z home]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZf8z4ii45kfjc41qrt363Z home]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                        PORTS     NAMES
0b03b728988b   centos    "/bin/bash"              2 minutes ago    Exited (0) 10 seconds ago               magical_rubin

# 将这个文件拷贝出来到主机上
[root@iZf8z4ii45kfjc41qrt363Z home]# docker cp 0b03b728988b:/home/test.java /home
[root@iZf8z4ii45kfjc41qrt363Z home]# ls
kuangshen  kuangshen.java  kuangstudy2  redis  test1  test.java  www

# 拷贝是一个手动过程,未来我们使用 -v 卷的技术,可以实现打通

The difference between exec and attach:
After using exec to enter the container, it is to open a new terminal and operate in it. After exiting the container, the container is still running.
Using attach is to operate directly in the terminal where the current container is executing. After exiting the container, the container stops

3 Docker install Nginx

# 1. 搜索镜像 search 建议大家去docker搜索,可以看到帮助文档
# 2. 下载镜像 pull
# 3. 运行测试
[root@iZf8z4ii45kfjc41qrt363Z home]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
nginx        latest    605c77e624dd   2 months ago   141MB
centos       latest    5d0da3dc9764   6 months ago   231MB

# -d 后台运行
# --name 给容器命名
# -p 宿主机,容器内部端口
[root@iZf8z4ii45kfjc41qrt363Z home]# docker run -d --name nginx01 -p 3344:80 nginx
76982652da3b9a3b1e51b304050b558818ec2461c83ed6280874dc48b872ab5e
[root@iZf8z4ii45kfjc41qrt363Z home]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                  NAMES
76982652da3b   nginx     "/docker-entrypoint.…"   5 seconds ago   Up 4 seconds   0.0.0.0:3344->80/tcp   nginx01

[root@iZf8z4ii45kfjc41qrt363Z home]# curl localhost:3344

-p: Port 80 in the container is bound to port 3344 of the host (convenient for access by machines other than the host).
Diagram of port exposure: If the firewall is turned off, it is equivalent to exposing all interfaces to the outside
insert image description here
insert image description here
. After passing the test, enter the container:

[root@iZf8z4ii45kfjc41qrt363Z home]# docker exec -it nginx01 /bin/bash
root@76982652da3b:/# whereis nginx
nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
root@76982652da3b:/# cd /etc/nginx
root@76982652da3b:/etc/nginx# ls
conf.d	fastcgi_params	mime.types  modules  nginx.conf  scgi_params  uwsgi_params

If you exit the container, the port will be closed and cannot be accessed
insert image description here
. Thinking questions:

Do we need to enter the container every time we change the nginx configuration file? That would be very troublesome. So I thought: Can we provide a mapping path outside the container, so that the file name can be modified outside the container, and the inside of the container can be automatically modified. So there is the -v data volume technology!

4 Docker install Tomcat

# 官方的使用 
docker run -it --rm tomcat:9.0 
# 之前的启动都是在后台运行,停止了容器,容器还是可以查到 
# docker run -it --rm image 一般是用来测试,用完就删除(暂时不建议)

insert image description here

# 下载 
docker pull tomcat 

# 启动运行
docker run -d -p 3355:8080 --name tomcat01 tomcat

# 测试访问没有问题 

I can get in but there is no page to display. It means that the connection is successful, but the front-end page is missing

insert image description here

# 进入容器
docker exec -it tomcat01 /bin/bash

# 发现问题:1、linux命令少了	 2.webapps文件夹为空
# 原因:阿里云镜像(阉割版),它为保证最小镜像,将不必要的都剔除了→保证最小可运行环境!

# 发现 webapps.dist 下有完整的文件,将其复制到 webapps下
root@962b84bda08f:/usr/local/tomcat/webapps# ls	# 可见webapps文件夹为空
root@962b84bda08f:/usr/local/tomcat/webapps# cd ..
root@962b84bda08f:/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@962b84bda08f:/usr/local/tomcat# cd webapps.dist
root@962b84bda08f:/usr/local/tomcat/webapps.dist# ls
ROOT  docs  examples  host-manager  manager
root@962b84bda08f:/usr/local/tomcat/webapps.dist# cd ..
root@962b84bda08f:/usr/local/tomcat# cp -r webapps.dist/* webapps		# 复制webapps.dist下的所有文件
root@962b84bda08f:/usr/local/tomcat# cd webapps
root@962b84bda08f:/usr/local/tomcat/webapps# ls	# 复制成功!进入 webapps 文件夹,此时已有文件
ROOT  docs  examples  host-manager  manager

Refresh the page, and it can be displayed normally at this time
insert image description here
. Thinking questions:

We will deploy the project in the future. Is it very troublesome if we have to enter the container every time? If only a mapping path can be provided outside the container, when we modify the webapps, we only need to place the project outside, and then it can be automatically synchronized to the inside!

5 Docker Deployment Department es+kibana

# es 暴露的端口很多! 
# es 十分耗内存 
# es 的数据一般需要放置到安全目录!挂载 
# --net somenetwork 是 网络配置

# 下载启动elasticsearch(Docker一步搞定) 
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2

# 启动了 Linux就卡住了	docker stats 查看 cpu的状态

# es 是十分耗内存的,有1.x个G。我的服务器是2核2G的,比狂神当时的好一点

# 测试一下es是否成功启动了
[root@iZf8z4ii45kfjc41qrt363Z home]# curl localhost:9200
{
    
    
  "name" : "f6909ff78411",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "lx6V_BNwSfGjCVX47xdrMQ",
  "version" : {
    
    
    "number" : "7.6.2",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
    "build_date" : "2020-03-26T06:34:37.794943Z",
    "build_snapshot" : false,
    "lucene_version" : "8.4.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

docker stats	# 查看 cpu 的状态

insert image description here

# 赶紧关闭,增加内存的限制,修改配置文件。通过 -e 进行环境配置修改
docker run -d --name elasticsearch02 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2

docker stats	# 再次查看 cpu 的状态。这时就好了很多

insert image description here
At this time, the connection can still be successful, see below:

[root@iZf8z4ii45kfjc41qrt363Z home]# curl localhost:9200
{
    
    
  "name" : "92b610e42bcd",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "UePTTR9TQyqnFf8H5lQdKw",
  "version" : {
    
    
    "number" : "7.6.2",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
    "build_date" : "2020-03-26T06:34:37.794943Z",
    "build_snapshot" : false,
    "lucene_version" : "8.4.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

Homework: Use kibana to connect to es? Think about how the network can be connected.
insert image description here

6 Docker Visualization

  • portainer (use this first)
  • Rancher (CI/CD reuse)

What is a portainer?
Docker GUI management tool! Provide a background panel for us to operate!

# 运行如下命令即可 打开可视化服务
docker run -d -p 8088:9000 \--restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

http://192.168.21.13:8088/#/init/admin

admin asdfghjkl

After success, set the password and select local to configure.
insert image description here
After entering the interface
insert image description here
, click local to view the current container and image status
insert image description here

3 Docker image explanation

A mirror is a lightweight, executable independent software package, used to package the software operating environment and software developed based on the operating environment. It contains everything needed to run a certain software, including code, runtime libraries, and environment variables. and configuration files.

All applications and environments are directly packaged into docker images and can be run directly.

How to get a mirror image:

  • Download from remote repository
  • copied by others
  • Make a mirror DockerFile yourself

Docker image loading principle

UnionFs (Union File System):
When we download, we see layer-by-layer downloads. This way every modification can be recorded.

UnionFs (Union File System): The Union File System (UnionFs) is a layered, lightweight and high-performance file system. It supports the modification of the file system as a submission to superimpose layers. At the same time, different The directories are mounted under the same virtual file system ( unite several directories into a single virtual filesystem). The Union filesystem is the basis for Docker images. Images can be inherited through layers. Based on the base image (without a parent image), various specific application images can be made.

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

Docker image loading principle:
The docker image is actually composed of layer-by-layer file systems, and this layer of file systems is UnionFS.

bootfs (boot file system) mainly includes bootloader and Kernel. The bootloader is mainly used to guide and load the kernel. When Linux is first started, the bootfs file system will be added. The bottom layer of the Docker image is boots. This layer is the same as our typical Linux/Unix system, including the boot loader and kernel. After the boot is loaded, the entire kernel is in the memory. At this time, the right to use the memory has been transferred from the bootfs to the kernel. At this time, the system will also unload the bootfs.

bootfs is public, because all images must be loaded

rootfs (root file system), on top of bootfs. Contains /dev, /proc, /bin in a typical Linux system. Standard directories and files such as /etc. rootfs is a variety of different operating system distributions, such as Ubuntu, Centos, Little Red Riding Hood and so on.

So a container is a small Linux system, because the folders they contain are similar

insert image description here
Usually, the CentOS we install into the virtual machine is several G, why is it only 200M here for Docker?
insert image description here
For a streamlined OS, the rootfs can be very small. It only needs to include the most basic commands, tools and program libraries. Because the underlying layer directly uses the Host's kernel, you only need to provide the rootfs. It can be seen that for different Linux distributions, the boots are basically the same, but the rootfs will be different, so different distributions can share the bootfs.

Virtual machines are at the minute level, and containers are at the second level!

Layered understanding:
download a mirror, pay attention to the downloaded log output, you can see that it is downloaded layer by layer. The
first layer shows Already exists, which already exists, which is the basic layer

insert image description here
Thinking: Why does the Docker image adopt this layered structure?

The biggest benefit is resource sharing! For example, if multiple images are built from the same Base image, then the host only needs to keep one base image on disk, and only one base image needs to be loaded in memory, so that all containers can be served , and each layer of the image can be shared.

You can use the command to view the image layering method docker image inspect 镜像名.

insert image description here
understand:

All Docker images start with a base image layer, and when modifications or additions are made, a new image layer will be created on top of the current image layer.

To give a simple example, if a new image is created based on Ubuntu Linux16.04, this is the first layer of the new image; if a Python package is added to the image, a second image layer will be created on top of the base image layer ; If you continue to add a security patch, a third mirror layer will be created. The image currently contains 3 mirror layers, as shown in the figure below (this is just a very simple example for demonstration).

insert image description here
It is important to understand that while adding additional image layers, the image always remains a combination of all current images. A simple example is shown in the figure below, each image layer contains 3 files, and the image contains 6 files from two image layers.

insert image description here
The mirror layer in the above picture is slightly different from the previous picture, the main purpose is to facilitate the display of files

The figure below shows a slightly complicated three-layer image. From the outside, the entire image has only 6 files. This is because file 7 in the uppermost layer is an updated version of file 5. In this case, the file in the upper image
insert image description here
layer The file overwrites the file in the underlying image layer. This causes the updated version of the file to be added to the image as a new image layer.

Features:
Docker images are all read-only, and when the container starts, a new writable layer is loaded on top of the image!
This layer is what we usually call the container layer, and everything under the container is called the mirror layer!
insert image description here
Only read-only files are pulled, and the image starts to run after run. We usually operate the image in docker, and the level of operation at this time is the container layer.

commit mirror

docker commit 提交容器成为一个新的副本 

# 命令和git原理类似 
docker commit -m="提交的描述信息" -a="作者" 容器id 目标镜像名:[TAG]	# tag 表示版本

Combat test:

# 2、成功后新建一个会话,运行 tomcat
docker exec -it 容器id /bin/bash

# 3、发现这个默认的tomcat 是没有webapps应用,官方的镜像默认webapps下面是没有文件的!
# 4、拷贝文件进去
cp -r webapps.dist/* webapps
# 可以看到拷贝成功了,基本的文件有了
root@fe0570359ee5:/usr/local/tomcat# cd webapps
root@fe0570359ee5:/usr/local/tomcat/webapps# ls
ROOT  docs  examples  host-manager  manager

# 5、将操作过的容器通过commit提交为一个镜像!我们以后就使用我们修改过的镜像即可,这就是我们自己修改完后的镜像。 
# 格式
docker commit -m="描述信息" -a="作者" 容器id 目标镜像名:[TAG] 
# 实际操作	这里的镜像名为:tomcat02;		版本为:1.0
docker commit -a="kuangshen" -m="add webapps app" 容器id tomcat02:1.0

insert image description here
If you want to save the state of the current container, you can submit it through commit and get a mirror image, just like a snapshot when using a virtual machine.
Getting started successfully! ! !
Getting started successfully! ! !
Getting started successfully! ! !

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/132102679