参考视频:

【狂神说Java】Docker最新超详细版教程通俗易懂_哔哩哔哩_bilibili笔记资料交流都在我们的平台:www.kuangstudy.com秦疆老师Java全栈系列课程之Docker讲解从Docker历史,概念,到命令的详解从使用到深入原理和网络,大量的实战,带你彻底掌握Docker!给你带来最全面的Docker讲解,学Docker,这一套课就够了!狂神说Java系列,努力打造通俗易懂的教程QQ交流群 : 664386224https://www.bilibili.com/video/BV1og4y1q7M4?p=11


1、后台启动容器

#命令 docker run -d 镜像名

docker run -d centos

#问题1:  docker ps,发现centos停止了
#问题2: docker容器使用后台运行,就必须要有一个前台进程,docker没有发现应用就会自动停止。
#问题3:  nginx容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了。

2、查看日志 

docker logs | Docker Documentationdocker logs: The `docker logs` command batch-retrieves logs present at the time of execution. > **Note** > > This command is only functional for containers that are started with the...https://docs.docker.com/engine/reference/commandline/logs/

docker logs [参数] 容器id 

#部分参数
名称         简写	  默认	   描述
--details		               显示提供给日志的额外详细信息
--follow,     -f		       关注日志输出
--since		                   显示自时间戳(例如 2013-01-02T13:23:37Z)或相对时间(例如 42m 42 分钟)以来的日志
--tail,       -n	  all	   从日志末尾显示的行数
--timestamps, -t		       显示时间戳
--until		                   API 1.35+
                               在时间戳(例如 2013-01-02T13:23:37Z)或相对时间(例如 42m 42 分钟)之前显示日志

这里可以启动一个容器,并且输出语句来进行查看。

docker run -d --name="guoergouCentOS" /bin/bash -c "while true,echo guoergounb!";sleep 1;done"  #每秒重复打印guoergounb

 通过日志命令可以看到其打印内容。

docker logs -f -t --tail 10 containerId #查询容器的日志,每次打印十行


3、查看进程的PID

docker top containerId
#可以看到该容器中的进程信息。
# docker top d2f
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                9300                9281                0                   14:48               ?                   00:00:00            /bin/bash -c while true;do echo guoergou; sleep 1; done
root                9341                9300                0                   14:48               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

 


4、查看镜像元数据

docker inspect containerId
#查看容器信息

输出结果能够得到如下内容

[root@VM-0-6-centos ~]# docker inspect d2f801
[
    {
        "Id": "d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae",
        "Created": "2022-03-15T06:48:22.903469141Z",
        "Path": "/bin/bash",
        "Args": [
            "-c",
            "while true;do echo guoergou; sleep 1; done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 9300,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-03-15T06:48:23.229866241Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae/hostname",
        "HostsPath": "/var/lib/docker/containers/d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae/hosts",
        "LogPath": "/var/lib/docker/containers/d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae/d2f801c339c85f32aa9038a8c297b0aaae0f7209149ae0e65a1e425f07f456ae-json.log",
        "Name": "/myShellCentOS",
        "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/1cf54445fd1ff678d1c39bfb9a6d4da5357e68aa27204e83d167868a1bdbb1f2-init/diff:/var/lib/docker/overlay2/39aec0e6d276578243fc647b44260880e6bb8ef62c73dc6b38c8e871977e3dc3/diff",
                "MergedDir": "/var/lib/docker/overlay2/1cf54445fd1ff678d1c39bfb9a6d4da5357e68aa27204e83d167868a1bdbb1f2/merged",
                "UpperDir": "/var/lib/docker/overlay2/1cf54445fd1ff678d1c39bfb9a6d4da5357e68aa27204e83d167868a1bdbb1f2/diff",
                "WorkDir": "/var/lib/docker/overlay2/1cf54445fd1ff678d1c39bfb9a6d4da5357e68aa27204e83d167868a1bdbb1f2/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d2f801c339c8",
            "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 guoergou; 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": "ff84d0aa3558f194eeeca3dfcc296878585550925d73a16acd8b88bde5e7d6e9",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/ff84d0aa3558",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "aa165ef660334b8f21f4d2452c206e4b29b8588e7d842ae170e7e56e779e5dc4",
            "Gateway": "172.18.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.18.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:12:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "2a4947f8e9074f2052f736873949c647254f7689f60bbf5ec280e1c129ea1855",
                    "EndpointID": "aa165ef660334b8f21f4d2452c206e4b29b8588e7d842ae170e7e56e779e5dc4",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
 


5、进入容器命令以及拷贝命令 

#我们容器几乎都是后台运行,我们如何进入?
#命令1 开启一个新的终端进入操作
docker exec -it containerID bashShell

 

#命令2 直接进入容器正在执行的通道
docker attach containerID 


6、从容器拷贝文件到主机

#命令
docker cp 容器Id:容器路径   目的主机路径

比如,我在容器中新建了一个guoergou.txt的文件,我要移到当前主机中。

1、新建容器并创建文件

 docker run -it --name='guoergouCentOS' centos  /bin/bash
[root@556b22621773 usr]# cd /home/
[root@556b22621773 home]# ls
[root@556b22621773 home]# touch guoergou.txt
[root@556b22621773 home]# ls
guoergou.txt
[root@556b22621773 home]# vi guoergou.txt


2、进行文件拷贝,从容器退出来后

#命令 在主机上进行操作
docker cp containerId:/path/file /path/
#比如,我创建好的guoergou.txt在容器id为556b22621773中的/home目录下
#那么拷贝出来就是
docker cp 556b2:/home/guoergou.txt /home

由此拷贝出来是成功的。

目前拷贝是一个手动的过程,未来使用 -v 卷的技术,实现自动同步。 


 7、主机内容拷贝到容器当中

#命令 也就是和容器拷贝出主机的顺序颠倒一下
docker cp 目录 containerId:目录

比如主机的guodagou.txt拷贝到容器当中。

#命令
docker cp /home/guodagou.txt containerId:/home/

 进入容器中查看

 这样完成了手动拷贝到容器当中


8、小结

 小结内容来源:下载 - KuangStudyKuangStudy是一个致力于为每个想学习知识的人提供一个少走弯路的平台,包含优质体系课程、文章博客、专栏书写、技术论坛、资源下载等产品服务,提供有用、优质、完整内容的自学交流社区.https://www.kuangstudy.com/download

  attach      Attach local standard input, output, and error streams to a running container
  #当前shell下 attach连接指定运行的镜像
  build       Build an image from a Dockerfile # 通过Dockerfile定制镜像
  commit      Create a new image from a container's changes #提交当前容器为新的镜像
  cp          Copy files/folders between a container and the local filesystem #拷贝文件
  create      Create a new container #创建一个新的容器
  diff        Inspect changes to files or directories on a container's filesystem #查看docker容器的变化
  events      Get real time events from the server # 从服务获取容器实时时间
  exec        Run a command in a running container # 在运行中的容器上运行命令
  export      Export a container's filesystem as a tar archive #导出容器文件系统作为一个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包中导入内容创建一个文件系统镜像
  info        Display system-wide information # 显示全系统信息
  inspect     Return low-level information on Docker objects #查看容器详细信息
  kill        Kill one or more running containers # kill指定docker容器
  load        Load an image from a tar archive or STDIN #从一个tar包或标准输入中加载一个镜像[对应save]
  login       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 one or more containers # 暂停容器
  port        List port mappings or a specific mapping for the container # 查看映射端口对应容器的源端口
  ps          List containers # 列出容器列表
  pull        Pull an image or a repository from a registry # 拉取指定镜像或者库镜像
  push        Push an image or a repository to a registry # 推送指定镜像或者库镜像 
  rename      Rename a container # 重命名容器
  restart     Restart one or more containers # 重启动容器
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default) # 保存镜像为一个tar包
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE # 给源中镜像打标签
  top         Display the running processes of a container 
  unpause     Unpause all processes within one or more containers # 取消暂停
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes #截取容器停止时的推出状态值

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐