其他分享
首页 > 其他分享> > docker学习笔记

docker学习笔记

作者:互联网

docker

​ 摘自官方文档 :https://docs.docker.com/engine/install/centos/

​ 参考文档 :https://gitee.com/moxi159753/LearningNotes/tree/master/Docker/Docker容器相关命令

参考视频 :小破站 狂神

1 . 安装

1.1 卸载旧docker 环境

#  yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
#  yum install -y yum-utils
#  yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
    
# yum install docker-ce docker-ce-cli containerd.io
(默认安装最新版本,也可指定版本)



image-20210926161527206

 sudo systemctl start docker
 (大道至简-省略内些有的没的)
 

1.2 配置 阿里云加速

https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors

2.docker 命令

2.1 镜像

# docker version # 查看docker版本信息情况
Client: Docker Engine - Community
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:55:49 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true
#docker info #显示更加详细的信息

# docker images #显示docker 镜像
REPOSITORY   TAG          IMAGE ID       CREATED        SIZE
<none>       <none>       180d16f99785   8 hours ago    40.8MB
<none>       <none>       c2b6e4a76538   10 hours ago   41.9MB
wordpress    latest       15ce81941cbf   2 days ago     618MB
python       3.6-alpine   c5917c34066a   2 weeks ago    40.8MB
python       3.7-alpine   a436fb2c575c   2 weeks ago    41.9MB
mysql        5.7          1d7aba917169   3 weeks ago    448MB

# docker images --help

Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
  -a, --all             Show all images (default hides intermediate images) 显示所有
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show image IDs

 经常使用
 # docker images -qa
180d16f99785
e22dec5ac272
35e39a94ef3e
5f5c155b1ef4

# docker search  mysql #搜索等同于在docker.hub 上搜索

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   11473     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4356      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   848                  [OK]
percona                           Percona Server is a fork of the MySQL relati…   557       [OK]       
phpmyadmin                        phpMyAdmin - A web interface for MySQL and M…   332       [OK]       
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   91                   
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr…   88                   
centurylink/mysql                 Image containing mysql. Optimized to be link…   59                   [OK]
databack/mysql-backup             Back up mysql databases to... anywhere!         51                   
prom/mysqld-exporter                                                              42                   [OK]
deitch/mysql-backup               REPLACED! Please use http://hub.docker.com/r…   41                   [OK]
# docker search --help
Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided  #过滤
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output

#搜索
# docker search  mysql --filter=stars=3000 #搜索  STARS 大于3000的
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   11473     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4356      [OK] 

#拉取,下载
# docker pull mysql #镜像名
Using default tag: latest #版本,标签
latest: Pulling from library/mysql
a330b6cecb98: Already exists #分层 ,联合文件系统
9c8f656c32b8: Already exists 
88e473c3f553: Already exists 
062463ea5d2f: Already exists 
daf7e3bdf4b6: Already exists 
1839c0b7aac9: Already exists 
cf0a0cfee6d0: Already exists 
1b42041bb11e: Pull complete 
10459d86c7e6: Pull complete 
b7199599d5f9: Pull complete 
1d6f51e17d45: Pull complete 
50e0789bacad: Pull complete 
Digest: sha256:99e0989e7e3797cfbdb8d51a19d32c8d286dd8862794d01a547651a896bcf00c #认证
Status: Downloaded newer image for mysql:latest 
docker.io/library/mysql:latest
docker pull  docker.io/library/mysql:latest 等价于  docker pull mysql 

#指定版本下载
docker pull mysql:5.7

# docker pull mysql:5.7 #下载mysql5.7 ,联合文件系统,不同版本的重复部分,不用反复下载,节省空间 
5.7: Pulling from library/mysql
Digest: sha256:d9b934cdf6826629f8d02ea01f28b2c4ddb1ae27c32664b14867324b3e5e1291
Status: Image is up to date for mysql:5.7
docker.io/library/mysql:5.7
#下载mysql 5,6 
docker pull mysql:5.6
5.6: Pulling from library/mysql
442547fc262c: Pull complete 
2bf716144687: Pull complete 
e8b3b16588b1: Pull complete 
c89f7ee6da81: Pull complete 
091490fb32f5: Pull complete 
6eeb696bc30f: Pull complete 
8a92263747b2: Pull complete 
07097cad43f1: Pull complete 
e09f00a44ec7: Pull complete 
18f954e29df7: Pull complete 
b46b7702c2b2: Pull complete 
Digest: sha256:35aa66157963240633625d6490d940069a1311fdfc022bf32116cbf95b90b541
Status: Downloaded newer image for mysql:5.6
docker.io/library/mysql:5.6

#删除镜像
# docker rmi --help

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Options:
  -f, --force      Force removal of the image #强制删除
      --no-prune   Do not delete untagged parents
# docker rmi -f 镜像id
# docker rmi -f $(docker images -qa) #删除所有镜像
# docker rmi -f 180d16f99785 c2b6e4a76538 #删除多个
Deleted: sha256:180d16f9978527ee330dcd191581b3bc0e1ac08362299b3c5f475564996fa0ca
Deleted: sha256:e22dec5ac272ac45744da322717a09cdebf713aa8e07080354205444a5ec3dcc
Deleted: sha256:3577d174f7dde7dd6fcba0a9b82a50a65ba71ed7303d7a90f7ef658daf95b3c1
Deleted: sha256:c2b6e4a765382cbd3afe7d35b1091ca7a7c6effb43118dc2ccc92abf2c875548
Deleted: sha256:5f5c155b1ef4cef83b9489886b9545e400f4f986079c1a05b9153d0b295f0471
Deleted: sha256:35e39a94ef3e2b2f5bbb1085f7da08104c66d517b5a435c1de0052c42151284e

2.2 容器

容器是基于镜像的(个人理解 相当于虚拟机的iso,容器相当于你的虚拟机)

运行容器

# docker run --help

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

Run a command in a new container

Options:
--name string                    Assign a name to the container #容器名称
-d, --detach                         Run container in background and print container ID #在后台运行容器
-it  #交互式 运行 ,进入容器内查看
-p(小写) 指定容器运行端口
-P(大写) 随机端口运行容器

例子 : 以交互式进入容器 centos
# docker run -it centos  /bin/bash 

退出并停止 exit

退出不停止 Ctrl +P +Q 不停止容器,挂后台

 docker ps --help

Usage:  docker ps [OPTIONS]

List containers

Options:
  -a, --all             Show all containers (default shows just running) 显示所有 默认只显示运行中的
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest crea
  ted container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs 只显示容器编号
  -s, --size            Display total file sizes

删除容器

# docker ps 
CONTAINER ID   IMAGE              COMMAND                  CREATED          STATUS         PORTS                                   NAMES
cf462879f874   centos             "/bin/bash"              11 seconds ago   Up 9 seconds                                           great_shannon
08b19ce6c65d   wordpress:latest   "docker-entrypoint.s…"   6 hours ago      Up 6 hours     0.0.0.0:8000->80/tcp, :::8000->80/tcp   my_wordpress_wordpress_1
58476d54c560   mysql:5.7          "docker-entrypoint.s…"   6 hours ago      Up 6 hours     3306/tcp, 33060/tcp                     my_wordpress_db_1
[root@docker1 ~]# docker rm cf462879f874
Error response from daemon: You cannot remove a running container cf462879f874c61f0ab3e3715dbdd0978eb4dff631ab5a8c3365c1adfb44f2e0. Stop the container before attempting removal or force remove
[root@docker1 ~]# docker rm -f cf462879f874 #删除运行中的容器
#docker rm 容器id
#docker rm -f 容器id
#docker rm $(docker ps -qa) #删除所有容器
docker start 容器id
docker restart 容器id
docker stop 容器id
docker kill 容器id 


其他常用命令

例子 :问题描述

-d 后台启动后,发现容器自动关闭了。如下

root@docker1 ~]# docker run -d centos /bin/bash
404109eb8ce037d4bd35a2d780eaa069d6e70c48d161a327f165eec4f47a5059
[root@docker1 ~]# docker ps -a 
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
404109eb8ce0   centos    "/bin/bash"   8 seconds ago   Exited (0) 7 seconds ago             cranky_liskov
[root@docker1 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

注释:必须有一个前台进程,或对外提供服务的应用,不然就会自动关闭

docker 打印日志

#启动一个 centos镜像 ,并循环打印 liuzhoahuan、
docker run -d centos /bin/bash -c "while true;do echo liuzhaohuan ;sleep 2; done " 
# docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

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

# docker logs -ft  --tail 10  207b6d7b7d9c
2021-09-26T21:38:36.946822679Z liuzhaohuan
2021-09-26T21:38:38.963377475Z liuzhaohuan
2021-09-26T21:38:40.991883014Z liuzhaohuan
2021-09-26T21:38:43.004861104Z liuzhaohuan
2021-09-26T21:38:45.011425672Z liuzhaohuan
2021-09-26T21:38:47.025711199Z liuzhaohuan
2021-09-26T21:38:49.043931713Z liuzhaohuan
2021-09-26T21:38:51.056923576Z liuzhaohuan
2021-09-26T21:38:53.079467694Z liuzhaohuan

查看进程信息

[root@docker1 ~]# docker top 207b6d7b7d9cUID                 PID                 PPID                C                   STIME               TTY                 TIME                CMDroot                95068               95051               0                   05:28               ?                   00:00:00            /bin/bash -c while true;do echo liuzhaohuan ;sleep 2; doneroot                96874               95068               0                   05:40               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2

查看镜像源数据

[root@docker1 ~]# docker inspect --helpUsage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]Return low-level information on Docker objectsOptions:  -f, --format string   Format the output using the given Go template  -s, --size            Display total file sizes if the type is container      --type string     Return JSON for specified type      # docker inpect 容器id# docker inspect 207b6d7b7d9c[    {        "Id": "207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc",        "Created": "2021-09-26T21:28:25.697179821Z",        "Path": "/bin/bash",        "Args": [            "-c",            "while true;do echo liuzhaohuan ;sleep 2; done "        ],        "State": {            "Status": "running",            "Running": true,            "Paused": false,            "Restarting": false,            "OOMKilled": false,            "Dead": false,            "Pid": 95068,            "ExitCode": 0,            "Error": "",            "StartedAt": "2021-09-26T21:28:26.442154117Z",            "FinishedAt": "0001-01-01T00:00:00Z"        },        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",        "ResolvConfPath": "/var/lib/docker/containers/207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc/resolv.conf",        "HostnamePath": "/var/lib/docker/containers/207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc/hostname",        "HostsPath": "/var/lib/docker/containers/207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc/hosts",        "LogPath": "/var/lib/docker/containers/207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc/207b6d7b7d9c2391e60caace3e10a609bd70b05af7e955e263c59dbd91f745bc-json.log",        "Name": "/optimistic_vaughan",        "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/ab5f50e1e850ed7a56395c7fa34ba201f7c0b7803c3bb8ce61ba4ab6f2459683-init/diff:/var/lib/docker/overlay2/cd0d8f2a4c5d07c6cebd229c4963a0fb3333737b2d060627f610adffbcfd982a/diff",                "MergedDir": "/var/lib/docker/overlay2/ab5f50e1e850ed7a56395c7fa34ba201f7c0b7803c3bb8ce61ba4ab6f2459683/merged",                "UpperDir": "/var/lib/docker/overlay2/ab5f50e1e850ed7a56395c7fa34ba201f7c0b7803c3bb8ce61ba4ab6f2459683/diff",                "WorkDir": "/var/lib/docker/overlay2/ab5f50e1e850ed7a56395c7fa34ba201f7c0b7803c3bb8ce61ba4ab6f2459683/work"            },            "Name": "overlay2"        },        "Mounts": [],        "Config": {            "Hostname": "207b6d7b7d9c",            "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/bash",                "-c",                "while true;do echo liuzhaohuan ;sleep 2; 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": "be1cd7610168d4f6f67f24f3ece98141e04da8e58645552b87755f0a3b79e527",            "HairpinMode": false,            "LinkLocalIPv6Address": "",            "LinkLocalIPv6PrefixLen": 0,            "Ports": {},            "SandboxKey": "/var/run/docker/netns/be1cd7610168",            "SecondaryIPAddresses": null,            "SecondaryIPv6Addresses": null,            "EndpointID": "2c0d9606ae0a5fb9d718b2e513b1fd73ff4c184707430c53842c0daf41c48a12",            "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": "a97709189c8a94862a76905fa727b2510e6bf62e8ae61f7575f7b87dec18c035",                    "EndpointID": "2c0d9606ae0a5fb9d718b2e513b1fd73ff4c184707430c53842c0daf41c48a12",                    "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                }            }        }    }]

进入当前运行的容器

 命令1  docker exec   root@docker1 ~]# docker exec -it 207b6d7b7d9c /bin/bash[root@207b6d7b7d9c /]# lsbin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var命令2  docker attach[root@docker1 ~]# docker attach b3bfff78cb06d5liuzhaohuanliuzhaohuanliuzhaohuanliuzhaohuanliuzhaohuan区别 :docker exec #进入容器,打开一个新的终端docker attach #进入正在执行的终端

从容器中copy 文件到主机

# docker exec -it b3bfff78cb06 /bin/bash [root@b3bfff78cb06 /]# ls bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var[root@b3bfff78cb06 /]# cd /home/[root@b3bfff78cb06 home]# ls[root@b3bfff78cb06 home]# touch test.sh[root@b3bfff78cb06 home]#  exitexit[root@docker1 ~]# docker cp b3bfff78cb06:/home/test.sh /home/[root@docker1 ~]# ll /home/总用量 0drwx------. 3 1000 1000 127 9月   4 01:26 deployer-rw-r--r--. 1 root root   0 9月  27 06:08 test.sh#cp  容器中的test.sh 到本机的home下

image-20210928145221711

命令小结

attach    Attach to a running container                                  #当前shell下attach连接指定运行镜像build     Build an image from a Dockerfile                               #通过Dockerfile定制镜像commit    Create a new image from a containers changes                   #提交当前容器为新的镜像cp          Copy files/folders from a container to a HOSTDIR or to STDOUT  #从容器中拷贝指定文件或者目录到宿主机中create    Create a new container                                         #创建一个新的容器,同run 但不启动容器diff      Inspect changes on a containers filesystem                     #查看docker容器变化events    Get real time events from the server                           #从docker服务获取容器实时事件exec      Run a command in a running container                           #在已存在的容器上运行命令export    Export a containers filesystem as a tar archive                #导出容器的内容流作为一个tar归档文件(对应import)history   Show the history of an image                                   #展示一个镜像形成历史images    List images                                                    #列出系统当前镜像import    Import the contents from a tarball to create a filesystem image  #从tar包中的内容创建一个新的文件系统映像(对应export)info      Display system-wide information                                #显示系统相关信息inspect   Return low-level information on a container or image           #查看容器详细信息kill      Kill a running container                                       #kill指定docker容器load      Load an image from a tar archive or STDIN                      #从一个tar包中加载一个镜像(对应save)login     Register or log in to a Docker registry                        #注册或者登陆一个docker源服务器logout    Log out from a Docker registry                                 #从当前Docker registry退出logs      Fetch the logs of a container                                  #输出当前容器日志信息pause     Pause all processes within a container                         #暂停容器port      List port mappings or a specific mapping for the CONTAINER     #查看映射端口对应的容器内部源端口ps        List containers                                                #列出容器列表pull      Pull an image or a repository from a registry                  #从docker镜像源服务器拉取指定镜像或者库镜像push      Push an image or a repository to a registry                    #推送指定镜像或者库镜像至docker源服务器rename    Rename a container                                             #重命名容器restart   Restart a running container             lian                       #重启运行的容器rm        Remove one or more containers                                  #移除一个或者多个容器rmi       Remove one or more images                                      #移除一个或多个镜像(无容器使用该镜像才可以删除,否则需要删除相关容器才可以继续或者-f强制删除)run       Run a command in a new container                               #创建一个新的容器并运行一个命令save      Save an image(s) to a tar archive                              #保存一个镜像为一个tar包(对应load)search    Search the Docker Hub for images                               #在docker hub中搜索镜像start     Start one or more stopped containers                           #启动容器stats     Display a live stream of container(s) resource usage statistics  #统计容器使用资源stop      Stop a running container                                       #停止容器tag       Tag an image into a repository                                 #给源中镜像打标签top       Display the running processes of a container                   #查看容器中运行的进程信息unpause   Unpause all processes within a container                       #取消暂停容器version   Show the Docker version information                            #查看容器版本号wait      Block until a container stops, then print its exit code        #截取容器停止时的退出状态值lian

练习

[root@docker1 ~]# docker pull nginx:alpinealpine: Pulling from library/nginxDigest: sha256:686aac2769fd6e7bab67663fd38750c135b72d993d0bb0a942ab02ef647fc9c3Status: Downloaded newer image for nginx:alpinedocker.io/library/nginx:alpine[root@docker1 ~]# docker imagesREPOSITORY   TAG             IMAGE ID       CREATED       SIZEwordpress    latest          15ce81941cbf   2 days ago    618MBcentos       latest          5d0da3dc9764   11 days ago   231MBnginx        1.21.3-alpine   513f9a9d8748   2 weeks ago   22.9MBnginx        alpine          513f9a9d8748   2 weeks ago   22.9MBpython       3.6-alpine      c5917c34066a   2 weeks ago   40.8MBpython       3.7-alpine      a436fb2c575c   2 weeks ago   41.9MBmysql        5.6             e05271ec102f   3 weeks ago   303MBmysql        5.7             1d7aba917169   3 weeks ago   448MBmysql        latest          0716d6ebcc1a   3 weeks ago   514MB[root@docker1 ~]# docker run -d --name nginx_test -d -p 8081:80  nginx:alpine523d624becd2f12fdf09bdb251e9e8432e888485e1f07565cb87fccdae5c59a8[root@docker1 ~]# docker ps CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                                   NAMES523d624becd2   nginx:alpine   "/docker-entrypoint.…"   5 seconds ago   Up 3 seconds   0.0.0.0:8081->80/tcp, :::8081->80/tcp   nginx_test[root@docker1 ~]# docker exec -it nginx_test /bin/sh/ # lsbin                   docker-entrypoint.sh  lib                   opt                   run                   sys                   vardev                   etc                   media                 proc                  sbin                  tmpdocker-entrypoint.d   home                  mnt                   root                  srv                   usrroot@docker1 ~]# docker logs -tf --tail -n nginx_test 2021-09-26T22:48:55.227874151Z /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration2021-09-26T22:48:55.227900261Z /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/2021-09-26T22:48:55.227904484Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh2021-09-26T22:48:55.239914116Z 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf2021-09-26T22:48:55.266143450Z 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf2021-09-26T22:48:55.267840321Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh2021-09-26T22:48:55.271826520Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh2021-09-26T22:48:55.283142852Z /docker-entrypoint.sh: Configuration complete; ready for start up2021-09-26T22:48:55.295822317Z 2021/09/26 22:48:55 [notice] 1#1: using the "epoll" event method2021-09-26T22:48:55.295852773Z 2021/09/26 22:48:55 [notice] 1#1: nginx/1.21.32021-09-26T22:48:55.295857349Z 2021/09/26 22:48:55 [notice] 1#1: built by gcc 10.3.1 20210424 (Alpine 10.3.1_git20210424) 2021-09-26T22:48:55.295860139Z 2021/09/26 22:48:55 [notice] 1#1: OS: Linux 3.10.0-862.el7.x86_642021-09-26T22:48:55.295863552Z 2021/09/26 22:48:55 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:10485762021-09-26T22:48:55.295867295Z 2021/09/26 22:48:55 [notice] 1#1: start worker processes2021-09-26T22:48:55.295871030Z 2021/09/26 22:48:55 [notice] 1#1: start worker process 32

查看docker 运行 性能状态

[root@docker1 ~]# docker stats CONTAINER ID   NAME         CPU %     MEM USAGE(docker使用) / LIMIT(服务器内存)       MEM %     NET I/O           BLOCK I/O         PIDS523d624becd2   nginx_test   0.00%     1.598MiB / 1.779GiB   0.09%     7.73kB / 2.72kB   5.91MB / 25.6kB   2

示例 :安装es

[root@docker1 ~]# docker network create somenetwork[root@docker1 ~]# docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node"  -e ES_JAVA_OPTS="-Xms256m -Xmx512m" elasticsearch:7.8.1#安装 es 并指定版本为7.8.1 并限制java使用内存大小

数据卷

[root@docker1 mysql]#  docker run --name some-mysql4 -v /home/mysql:/var/lib/mysql  -e MYSQL_ROOT_PASSWORD=my-secret-pw -it mysql:5.7 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci#挂载docker,容器内/var/lib/mysql地址,外部地址为/home/mysql[root@docker1 mysql]# docker inspect some-mysql4 "Mounts": [            {                "Type": "bind",                "Source": "/home/mysql", #宿主机地址                "Destination": "/var/lib/mysql", #容器内地址                "Mode": "",                "RW": true,                "Propagation": "rprivate"            }

具名挂载与匿名挂载

[root@docker1 volumes]#  docker run --name some-mysql6 -v mysql_data:/var/lib/mysql -p 3308:3306  -e MYSQL_ROOT_PASSWORD=my-secret-pw -d  mysql:5.7 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci52774485468b5f8bf8c75afe6ab9b578da110b0720f490c79c2dcff42ef74ad2[root@docker1 volumes]# docker volume  lsDRIVER    VOLUME NAMElocal     4de1327c367c3f96dcb0ba420c3ccaef12a55f918069478f86ac515958a9c355local     11d8b896b37310f3caf274c12a569fcfb249fa30c78561427a61b1ced136828alocal     ad484c8cda7a18378653adb5050fa8ed47e417cb0993aba662ec000e88828e53local     c2f94362caca9880150795ac6f71ba3fff433e19174f20730b590a08e50a90b8local     cb43f69c47d5ca8f0f481014975547a52b585a0d06cc14a08ad1d3906004cc56local     my_wordpress_db_datalocal     my_wordpress_wordpress_datalocal     mysql_data#具名挂载 docker run -v 卷名:容器内路径 #宿主机路径 :[root@docker1 _data]# pwd/var/lib/docker/volumes/mysql_data/_data#匿名挂载:(不推荐)docker run -v 容器内路径 [root@docker1 volumes]#  docker run --name some-mysql5 -v  /var/lib/mysql -p 3307:3306  -e MYSQL_ROOT_PASSWORD=my-secret-pw -d  mysql:5.7 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ciee50e507d8b4b918218ea1c696ac4a6a0993d2c8eee4141eb7a5488af2da3235[root@docker1 volumes]# docker volume lsDRIVER    VOLUME NAMElocal     4de1327c367c3f96dcb0ba420c3ccaef12a55f918069478f86ac515958a9c355local     11d8b896b37310f3caf274c12a569fcfb249fa30c78561427a61b1ced136828alocal     ad484c8cda7a18378653adb5050fa8ed47e417cb0993aba662ec000e88828e53local     c2f94362caca9880150795ac6f71ba3fff433e19174f20730b590a08e50a90b8local     cb43f69c47d5ca8f0f481014975547a52b585a0d06cc14a08ad1d3906004cc56权限设置 :docker run -d -P --name nginx05 -v juming:/etc/nginx:ro nginxdocker run -d -P --name nginx05 -v juming:/etc/nginx:rw nginx# ro 只要看到ro就说明这个路径只能通过宿主机来操作,容器内部是无法操作!

Docker File 构建镜像

[root@docker1 docker]# docker run -it  --name centos01  liuzhaohuan/centos:1.0 /bin/bash [root@5f74de7e0785 /]##centos 02 共用centos1 的数据卷,并创建一个文件root@docker1 docker]# docker run -it --name centos02 --volumes-from centos01 liuzhaohuan/centos:1.0 [root@2907c5b123cd /]# lsbin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var  volume01	volume02[root@2907c5b123cd /]# lsbin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var  volume01	volume02[root@2907c5b123cd /]# cd volume01/[root@2907c5b123cd volume01]# ls[root@2907c5b123cd volume01]# touch 1.txt [root@2907c5b123cd volume01]# exitexit#进入centos01[root@docker1 docker]# docker exec -it 5f74de7e0785 /bin/bash[root@5f74de7e0785 /]# lsbin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var  volume01	volume02[root@5f74de7e0785 /]# cd volume01/[root@5f74de7e0785 volume01]# ls1.txt@共享成功#--volumes-from centos01  共享centos01的数据卷

做什么

Dockerfile 练习

[root@docker1 div_centos]# cat Dockerfile-centos ARG CODE_VERSION=7FROM centos:${CODE_VERSION}MAINTAINER liu<rookie_lhh@163.com>ENV MYPATH /usr/localWORKDIR $MYPATH RUN yum -y install vim RUN yum -y install net-toolsEXPOSE 80CMD echo $MYPATHCMD echo "--------------end--------"CMD /bin/bash#自定义生成centos[root@docker1 div_centos]# docker build -f Dockerfile-centos -t mycentos:0.1 .[root@docker1 div_centos]# docker images REPOSITORY            TAG                IMAGE ID       CREATED         SIZEmycentos              0.1                8173cc319ff2   4 hours ago     536MB验证[root@docker1 div_centos]# docker run -it mycentos:0.1[root@f0cbea44b061 local]# vim 1.txt[root@f0cbea44b061 local]# netstat -natActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address           Foreign Address         State[root@f0cbea44b061 local]# pwd/usr/localdocker上传只阿里云镜像站#登录[root@docker1 docker]# docker login --username=rookie_lhh registry.cn-beijing.aliyuncs.comPassword: WARNING! Your password will be stored unencrypted in /root/.docker/config.json.Configure a credential helper to remove this warning. Seehttps://docs.docker.com/engine/reference/commandline/login/#credentials-store#新建标签     [iamgesID]       [镜像源地址]                                     [tag名称]docker tag  38c74030c15a registry.cn-beijing.aliyuncs.com/divdocker/dockertest:0.11fs#上传[root@docker1 docker]# docker push registry.cn-beijing.aliyuncs.com/divdocker/dockertest:0.11fs

练习源码部署tomcat

[root@docker1 docker]# tree div_tomcat/div_tomcat/├── apache-tomcat-8.0.43.tar.gz├── Dockerfile_tomcat├── jdk-8u171-linux-x64.tar.gz└── README
[root@docker1 docker]# cat div_tomcat/Dockerfile_tomcat ARG CODE_VERSION=7FROM centos:$CODE_VERSIONMAINTAINER liu<rookie_lhh@163.com>ENV MYPATH /usr/localWORKDIR $MYPATHRUN echo pwdCOPY README ./READMEADD apache-tomcat-8.0.43.tar.gz  ./RUN ln -s apache-tomcat-8.0.43 /usr/local/tomcat8ADD   jdk-8u171-linux-x64.tar.gz ./RUN yum -y install vimENV JAVA_HOME /usr/local/jdk1.8.0_171ENV CLASSPATH $JAVA_HOME/libENV CATALINA_HOME /usr/local/apache-tomcat-8.0.43ENV PATH $PATH:$JAVA_HOME/bin;$CATALINA_HOME/libEXPOSE 8080CMD /usr/local/apache-tomcat-8.0.43/bin/startup.sh && tail -F /usr/local/apache-tomcat-8.0.43/logs/catalina.out

构建运行

[root@docker1 div_tomcat]# docker build -f Dockerfile_tomcat -t mytomcat:2.0 .Successfully built 4df7175c8d40Successfully tagged mytomcat:2.0root@docker1 div_tomcat]# docker run -d --name tomcat2 -p 8098:8080 mytomcat:2.01369821ab0ae8dd7476af5da65eba001d109075a5514adbcf7d836812699ef8c

华为 jdk 镜像站

https://repo.huaweicloud.com/java/jdk/8u171-b11/

1 form 镜像来源

2 作者 maintainet

copy 复制文件

解压缩 add

run 运行系统命令

env 变量 env mypath

workdir 工作目录

env

expose 端口

cmd 命令

3.docker-compose

2.1 执行过程

image-20210927103739038

网络

docker network ls  #查看当前docker 网络NETWORK ID     NAME                  DRIVER    SCOPE01d0b9a26b2b   bridge                bridge    locald245c7bb447b   composetest_default   bridge    local6d22898c7762   host                  host      localee63e33e1f38   none                  null      local2.1.1 同网络下使用域名 访问项目,ip变化,不影响程序

2.2 常用命令

lsapp.py  docker-compose.yml  Dockerfile  requirements.txt #启动[root@ruibaitest composetest]# docker-compose up  #在compose路径下[root@ruibaitest composetest]# docker-compose up -d  #在compose路径下,后台启动#停止[root@ruibaitest composetest]# docker-compose down  #在compose路径下

docker网络

自定义网络

[root@docker1 div_tomcat]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet820fc5efc9417d562007470e37f9b8b0a56ed2d2500b30bbd61ebe30b6324453[root@docker1 div_tomcat]# docker network inspect mynet[    {        "Name": "mynet",        "Id": "820fc5efc9417d562007470e37f9b8b0a56ed2d2500b30bbd61ebe30b6324453",        "Created": "2021-10-08T21:53:17.089048876+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": {},        "Options": {},        "Labels": {}    }][root@docker1 div_tomcat]# docker run -d -p8099:8080  --name tomcat-net-02 --net mynet mytomcat:1.0[root@docker1 div_tomcat]# docker run -d -p8098:8080  --name tomcat-net-01 --net mynet mytomcat:2.0[root@docker1 div_tomcat]# docker run -d -p8097:8080  --name tomcat-net-04 --net mynet mytomcat:1.0[root@docker1 div_tomcat]# docker exec -it mytomcat-net-04 /bin/bash[root@c3f57de17b4e local]# ping tomcat-net-02PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data.64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.077 ms#可以使用镜像名相互ping通

3 .Docker小结

  1. Docker镜像 run => 容器
  2. DockerFlie 构建镜像 (服务打包)
  3. docker-compose 启动项目 (编排,多个微服务)
  4. docker 网络

4 .yaml 配置

# 3层!version: ''  #版本 service: #服务  服务1: web  #服务器配置  image  build  network   ...  服务2 : db  服务3 : redis   #其他配置 网络/卷 。全局规则  volumes :  network :  configs :
docker-compose up --build 

netstat -n | awk '/^tcp/ {S[$NF]++} END {for(a in S) print a, S[a]}'

标签:容器,docker1,--,笔记,学习,mysql,docker,root
来源: https://www.cnblogs.com/rookie-lhh/p/15465818.html