小言_互联网的博客

手把手·从零开始撸Docker 系列一

235人阅读  评论(0)

手把手·从零开始撸Docker 系列一

笔记整理来源 B站UP主 狂神说Java

弱小和无知不是生存的障碍,傲慢才是。

Docker 学习

  • Docker 概述
  • Docker安装
  • Docker命令
    • 镜像命令
    • 容器命令
    • 操作命令
  • Docker镜像
  • 容器数据卷
  • DockerFile
  • Docker网络原理
  • IDEA整合Docker(单机Docker)
  • Docker Compose
  • Docker Swarm
  • CI\CD Jenkins

Docker概述

Docker为什么出现?

一款产品: 开发–上线 两套环境!应用环境,应用配置!

开发 — 运维。 问题:我在我的电脑上可以允许!版本更新,导致服务不可用!对于运维来说考验十分大?

环境配置是十分的麻烦,每一个及其都要部署环境(集群Redis、ES、Hadoop…) !费事费力。

发布一个项目( jar + (Redis MySQL JDK ES) ),项目能不能带上环境安装打包!

之前在服务器配置一个应用的环境 Redis MySQL JDK ES Hadoop 配置超麻烦了,不能够跨平台。

开发环境Windows,最后发布到Linux!

传统:开发jar,运维来做!

现在:开发打包部署上线,一套流程做完!

安卓流程:java — apk —发布(应用商店)一 张三使用apk一安装即可用!

docker流程: java-jar(环境) — 打包项目帯上环境(镜像) — ( Docker仓库:商店)-----

Docker给以上的问题,提出了解决方案!

Docker的思想就来自于集装箱!

JRE – 多个应用(端口冲突) – 原来都是交叉的!
隔离:Docker核心思想!打包装箱!每个箱子是互相隔离的。

Docker通过隔离机制,可以将服务器利用到极致!

本质:所有的技术都是因为出现了一些问题,我们需要去解决,才去学习!

Docker历史

2010年,几个的年轻人,就在美国成立了一家公司 dotcloud

做一些pass的云计算服务!LXC(Linux Container容器)有关的容器技术!

Linux Container容器是一种内核虚拟化技术,可以提供轻量级的虚拟化,以便隔离进程和资源。

他们将自己的技术(容器化技术)命名就是 Docker
Docker刚刚延生的时候,没有引起行业的注意!dotCloud,就活不下去!

开源

2013年,Docker开源!

越来越多的人发现docker的优点!火了。Docker每个月都会更新一个版本!

2014年4月9日,Docker1.0发布!

docker为什么这么火?十分的轻巧!

在容器技术出来之前,我们都是使用虚拟机技术!

虚拟机:在window中装一个VMware,通过这个软件我们可以虚拟出来一台或者多台电脑!笨重!

虚拟机也属于虚拟化技术,Docker容器技术,也是一种虚拟化技术!

vm : linux centos 原生镜像(一个电脑!) 隔离、需要开启多个虚拟机! 几个G 几分钟
docker: 隔离,镜像(最核心的环境 4m + jdk + mysql)十分的小巧,运行镜像就可以了!小巧! 几个M 秒级启动!

聊聊Docker

Docker基于Go语言开发的!开源项目!

docker官网:https://www.docker.com/

文档:https://docs.docker.com/ Docker的文档是超级详细的!

仓库:https://hub.docker.com/

Docker能干嘛

之前的虚拟机技术!

虚拟机技术缺点

1、 资源占用十分多

把所有APP可能用到的库都放到 lib 里面,只要运行一个APP就会带上所有的库

2、 冗余步骤多

3、 启动很慢!

容器化技术

容器化技术不是模拟一个完整的操作系统

把每个APP可能用到的库和APP单独放到一起,极大的节省了资源占用

比较Docker和虚拟机技术的不同:

  • 传统虚拟机,虚拟出一条硬件,运行一个完整的操作系统,然后在这个系统上安装和运行软件
  • 容器内的应用直接运行在宿主机的内容,容器是没有自己的内核的,也没有虚拟我们的硬件,所以就轻便了
  • 每个容器间是互相隔离,每个容器内都有一个属于自己的文件系统,互不影响

DevOps(开发、运维)

应用更快速的交付和部署

传统:一对帮助文档,安装程序。

Docker:打包镜像发布测试一键运行。

更便捷的升级和扩缩容

使用了 Docker之后,我们部署应用就和搭积木一样
项目打包为一个镜像,扩展服务器A!服务器B

更简单的系统运维
在容器化之后,我们的开发,测试环境都是高度一致的

更高效的计算资源利用

Docker是内核级别的虚拟化,可以在一个物理机上可以运行很多的容器实例!服务器的性能可以被压榨到极致。Docker安装

Docker的基本组成

镜像(image):

docker镜像就好比是一个目标,可以通过这个目标来创建容器服务,tomcat镜像 ==> run ==> 容器(提供服务器),通过这个镜像可以创建多个容器(最终服务运行或者项目运行就是在容器中的)。

容器(container):

Docker利用容器技术,独立运行一个或者一组应用,通过镜像来创建的.
启动,停止,删除,基本命令
目前就可以把这个容器理解为就是一个简易的 Linux系统。

仓库(repository):

仓库就是存放镜像的地方!
仓库分为公有仓库和私有仓库。(很类似git)
Docker Hub是国外的。
阿里云…都有容器服务器(配置镜像加速!)

安装Docker

环境准备

Linux要求内核3.0以上

[root@VM-8-17-centos /]# uname -r
3.10.0-1160.11.1.el7.x86_64
[root@VM-8-17-centos /]# 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"

安装

帮助文档:https://docs.docker.com/engine/install/

#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.设置镜像的仓库
yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
#默认是从国外的,不推荐
#推荐使用国内的
yum-config-manager \
    --add-repo \
    https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
#更新yum软件包索引
yum makecache fast
#4.安装docker相关的 docker-ce 社区版 而ee是企业版
yum install docker-ce docker-ce-cli containerd.io
#5、启动docker
systemctl start docker
#6. 使用docker version查看是否按照成功
docker version
#7. 测试
docker run hello-world
#7. 测试
[root@VM-8-17-centos /]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete 
Digest: sha256:5122f6204b6a3596e048758cabba3c46b1c937a46b5be6225b835d091b90e46c
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/
#8.查看一下下载的镜像
[root@VM-8-17-centos /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d1165f221234   2 months ago   13.3kB

了解:卸载docker

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

阿里云镜像加速

1、登录阿里云找到容器服务

2、找到镜像加速器

3、配置使用

sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json <<-'EOF'
{
   
  "registry-mirrors": ["https://lzrwc96m.mirror.aliyuncs.com"]
}
EOF

sudo systemctl daemon-reload

sudo systemctl restart docker

回顾HelloWorld流程

docker run 流程图

底层原理

Docker是怎么工作的

Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机上。通过Socket从客户端访问!

Docker-Server接收到Docker-Client的指令,就会执行这个命令!

为什么Docker比Vm快
1、docker有着比虚拟机更少的抽象层。由于docker不需要Hypervisor实现硬件资源虚拟化,运行在docker容器上的程序直接使用的都是实际物理机的硬件资源。因此在CPU、内存利用率上docker将会在效率上有明显优势。
2、docker利用的是宿主机的内核,而不需要Guest OS。

GuestOS: VM(虚拟机)里的的系统(OS);

HostOS:物理机里的系统(OS);

因此,当新建一个 容器时,docker不需要和虚拟机一样重新加载一个操作系统内核。仍而避免引导、加载操作系统内核返个比较费时费资源的过程,当新建一个虚拟机时,虚拟机软件需要加载GuestOS,返个新建过程是分钟级别的。而docker由于直接利用宿主机的操作系统,则省略了这个复杂的过程,因此新建一个docker容器只需要几秒钟。

Docker的常用命令

帮助命令

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

帮助文档的地址:https://docs.docker.com/engine/reference/commandline/build/

镜像命令

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

docker images 查看所有本地的主机上的镜像

[root@VM-8-17-centos /]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    c0cdc95609f1   12 days ago   556MB

# 解释
#REPOSITORY			# 镜像的仓库源
#TAG				# 镜像的标签
#IMAGE ID			# 镜像的id
#CREATED			# 镜像的创建时间
#SIZE				# 镜像的大小
# 可选项
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 #使用Go模板输出漂亮的镜像
      --no-trunc        Don't truncate output #不截断输出
  -q, --quiet           Only show image IDs #只列出镜像IDs
  
[root@VM-8-17-centos /]# docker images -aq #显示所有镜像的id
c0cdc95609f1

docker search 搜索镜像

[root@VM-8-17-centos /]# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10916     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4122      [OK]       
...
...

# --filter=STARS=3000 #搜索出来的镜像就是STARS大于3000的
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
      
[root@VM-8-17-centos /]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10916     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4122      [OK]       

docker image pull 下载镜像

# 下载镜像 docker pull 镜像名[:tag]
[root@VM-8-17-centos /]# docker pull tomcat:8
8: Pulling from library/tomcat #如果不写tag,默认就是latest
d960726af2be: Pull complete    #分层下载: docker image 的核心 联合文件系统
e8d62473a22d: Pull complete 
8962bc0fad55: Pull complete 
65d943ee54c1: Pull complete 
da20b77f10ac: Pull complete 
fb6a778e6477: Pull complete 
ae7884f0e61b: Pull complete 
5a229cc6592e: Pull complete 
1c2d6d25c04a: Pull complete 
39b99cdc3584: Pull complete 
Digest: sha256:2f98644d7951b04870bde8f1565225f72d84cc895c38a483630730a1e9d363de
Status: Downloaded newer image for tomcat:8
docker.io/library/tomcat:8 #真实地址

#等价于
docker pull tomcat:8
docker pull docker.io/library/tomcat:8

分层可以理解为:当下次再下载另一个版本时,如果已经下载过的东西就不会再次下载了

docker rmi 删除镜像

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

容器命令

docker run 镜像id 新建容器并启动

docker ps 列出所有运行的容器 docker container list

docker rm 容器id 删除指定容器

docker start 容器id #启动容器

docker restart 容器id #重启容器

docker stop 容器id #停止当前正在运行的容器

docker kill 容器id #强制停止当前容器

说明:我们有了镜像才可以创建容器,Linux,下载centos镜像来学习

[root@VM-8-17-centos /]# docker container

Usage:  docker container COMMAND

Manage containers

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

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

新建容器并启动

docker run [可选参数] image | docker container run [可选参数] image 
#参书说明
--name="Name"		容器名字 tomcat01 tomcat02 用来区分容器
-d					后台方式运行
-it 				使用交互方式运行,进入容器查看内容
-p					指定容器的端口 -p 8080(宿主机):8080(容器)
		-p ip:主机端口:容器端口
		-p 主机端口:容器端口(常用)
		-p 容器端口
		容器端口
-P(大写) 				随机指定端口

# 测试、启动并进入容器
[root@VM-8-17-centos /]# docker run -it centos /bin/bash
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
7a0437f04f83: Pull complete 
Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
Status: Downloaded newer image for centos:latest
[root@fdae7762b280 /]# ls
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr
[root@fdae7762b280 /]# exit #从容器退回主机
exit

列出所有运行的容器

#docker ps命令 #列出当前正在运行的容器
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 created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs
  -s, --size            Display total file sizes
  
[root@VM-8-17-centos /]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@VM-8-17-centos /]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED         STATUS                     PORTS     NAMES
fdae7762b280   centos         "/bin/bash"   6 minutes ago   Exited (0) 2 minutes ago             busy_chaum
c1f0326decec   d1165f221234   "/hello"      2 hours ago     Exited (0) 2 hours ago               crazy_nightingale
[root@VM-8-17-centos /]# docker ps -aq
fdae7762b280
c1f0326decec

退出容器

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

启动和停止容器的操作

docker start 容器id	#启动容器
docker restart 容器id	#重启容器
docker stop 容器id	#停止当前正在运行的容器
docker kill 容器id	#强制停止当前容器

常用其他命令

后台启动命令

# 命令 docker run -d 镜像名
[root@VM-8-17-centos ~]# docker run -d centos
c58156be129ed181d372d7bfe333b0f6e538cb2fb85f1fdc7327ccb6a4651640
[root@VM-8-17-centos ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
# 问题docker ps. 发现centos 停止了
# 常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志

[root@VM-8-17-centos ~]# 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) #在时间戳(例如2013-01-02T13:23:37)或相对(例如42m之前)显示日志,持续42分钟
                       
[root@VM-8-17-centos ~]# docker run -d centos /bin/sh -c "while true;do echo maxiaoyu;sleep 1;done"
f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce

#显示日志
-tf		#显示日志信息(一直更新)
--tail number #需要显示日志条数
docker logs -t --tail n 容器id #查看n行日志
docker logs -ft 容器id #跟着日志

查看容器中进程信息 ps

# 命令 docker top 容器id
[root@VM-8-17-centos ~]# docker top f0f20d7d9d27
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                29894               29874               0                   13:41               ?                   00:00:00            /bin/sh -c while true;do echo maxiaoyu;sleep 1;done
root                32207               29894               0                   13:50               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像的元数据

# 命令
docker inspect 容器id

#测试
[root@VM-8-17-centos ~]# docker inspect f0f20d7d9d27
[
    {
   
        "Id": "f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce",
        "Created": "2021-05-25T05:41:38.483280823Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo maxiaoyu;sleep 1;done"
        ],
        "State": {
   
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 29894,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-05-25T05:41:38.770472817Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce/hostname",
        "HostsPath": "/var/lib/docker/containers/f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce/hosts",
        "LogPath": "/var/lib/docker/containers/f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce/f0f20d7d9d271e7b2edc179d3bc278ba6ccc52073322ff318a20f577331da7ce-json.log",
        "Name": "/zen_wescoff",
        "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/606421f0d07cd56e52e275d445e54af9456bffcdbef8ca7f319c03f5b0c5c2a8-init/diff:/var/lib/docker/overlay2/25ee405ef883cf17fb4378a9eeea8c6827361460ecd7288b3e6e5968dc798c61/diff",
                "MergedDir": "/var/lib/docker/overlay2/606421f0d07cd56e52e275d445e54af9456bffcdbef8ca7f319c03f5b0c5c2a8/merged",
                "UpperDir": "/var/lib/docker/overlay2/606421f0d07cd56e52e275d445e54af9456bffcdbef8ca7f319c03f5b0c5c2a8/diff",
                "WorkDir": "/var/lib/docker/overlay2/606421f0d07cd56e52e275d445e54af9456bffcdbef8ca7f319c03f5b0c5c2a8/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
   
            "Hostname": "f0f20d7d9d27",
            "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 maxiaoyu;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
   
                "org.label-schema.build-date": "20201204",
                "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": "2539165113f67e66400d1aa23abe788a2fe8775f44d51977e93fcc0bcc72ee1d",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
   },
            "SandboxKey": "/var/run/docker/netns/2539165113f6",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "fab4e20802d2e228aa6842e283182c2580c7fbf65a21376cc249e9270b1f81fa",
            "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": "dfc5b803553f527e1a3e831ee1a7c5daa44f57af3dfc61b05a11173685ebd705",
                    "EndpointID": "fab4e20802d2e228aa6842e283182c2580c7fbf65a21376cc249e9270b1f81fa",
                    "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
                }
            }
        }
    }
]

进入当前正在运行的容器

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

# 命令 
docker exec -it 容器id bashshell

#测试
[root@VM-8-17-centos ~]# docker exec -it f0f20d7d9d27 /bin/bash
[root@f0f20d7d9d27 /]# 
# 方式二
docker attach 容器id
#测试
docker attach f0f20d7d9d27
maxiaoyu
maxiaoyu
...
...

区别
#docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
#docker attach # 进入容器正在执行的终端

从容器内拷贝到主机上

docker cp 容器id:容器内路径   主机目的路径
#进入docker容器内部
[root@VM-8-17-centos ~]# docker exec -it f0f20d7d9d27 /bin/bash
[root@f0f20d7d9d27 /]# ls
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr
#新建一个文件
[root@f0f20d7d9d27 /]# echo "hello" > java.java
[root@f0f20d7d9d27 /]# cat java.java
hello
[root@f0f20d7d9d27 /]# exit
exit
[root@VM-8-17-centos ~]# docker cp f0f20d7d9d27:/java.java /
[root@VM-8-17-centos ~]# cd /
[root@VM-8-17-centos /]# ls
bin   config  dev  home       lib    lost+found  mnt  patch  root  sbin  sys  usr  www
boot  data    etc  java.java  lib64  media       opt  proc   run   srv   tmp  var

小结:

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 #
logout      Log out from a Docker registry
logs        Fetch the logs of a container
pause       Pause all processes within one or more containers
port        List port mappings or a specific mapping for the container
ps          List containers
pull        Pull an image or a repository from a registry
push        Push an image or a repository to a registry
rename      Rename a container
restart     Restart one or more containers
rm          Remove one or more containers
rmi         Remove one or more images
run         Run a command in a new container
save        Save one or more images to a tar archive (streamed to STDOUT by default)
search      Search the Docker Hub for images
start       Start one or more stopped containers
stats       Display a live stream of container(s) resource usage statistics
stop        Stop one or more running containers
tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top         Display the running processes of a container
unpause     Unpause all processes within one or more containers
update      Update configuration of one or more containers
version     Show the Docker version information
wait        Block until one or more containers stop, then print their exit codes

哇,这么多你都看下来了,给个三连再走呗😊~


转载:https://blog.csdn.net/Cool_breeze_/article/details/117259319
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场