Docker快速入门

Docker快速入门

1. 安装

# 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 \
    http://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版本
docker version
# 7.hello-world
docker run hello-world
# 8.查看下载的hello-world镜像
docker images
了解卸载docker
# 1.卸载依赖
yum remove docker-ce docker-ce-cli containerd.io
# 2.删除资源
rm -rf /var/lib/docker  #docker默认工作路径
rm -rf /var/lib/containerd

2.阿里云镜像加速

1.登录阿里云

2.镜像加速器

3.配置使用

# 1.第一步
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://po1qcvly.mirror.aliyuncs.com"] #这部分需要自己去注册免费获取
}
EOF
# 具体步骤参考:https://www.bilibili.com/video/BV1og4y1q7M4?p=7
# 2.第二步
sudo systemctl daemon-reload
# 3.第三步
sudo systemctl restart docker

img

2.1 底层原理

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

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

img

2.1 Docker为什么比VM快

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

2、Docker利用的是宿主机的内核,而不需要Guest OS,因此,当新建一个容器时,Docker不需要和虚拟机一样重新加载一个操作系统,避免了引导、加载操作系统内核这个比较费时费资源的过程,当新建一个虚拟机时,虚拟机软件需要加载Guest OS,这个新建过程是分钟级别的,而Docker由于直接利用宿主机的操作系统则省略了这个过程,因此新建一个Docker容器只需要几秒钟。
在这里插入图片描述

所以说,新建一个容器的时候,Docker不需要向虚拟机一样重新加载一个操作系统内核,避免引导,虚拟机是加载Guest OS,分钟级别的而Docker是利用宿主机的操作系统,省略了这个复杂的过程,秒级!

3.Docker常用命令

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

帮助文档地址:https://docs.docker.com/reference/

镜像命令

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

[root@localhost /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d1165f221234   4 months ago   13.3kB
#解释
REPOSITORY        镜像的仓库源
TAG                镜像的标签
IMAGE ID         镜像的id
CREATED            镜像的创建时间
SIZE            镜像的大小
  -a, --all     列出所有的镜像
  -q, --quiet   只显示镜像的Id

docker search 搜索镜像

#搜索mysql镜像
docker search mysql
#可选项,通过搜藏来过滤
--filter =stars=3000    #搜索出来的镜像就是stars大于3000

docker pull 下载镜像

#下载镜像
docker pull 镜像名[:tag]版本默认最新版
[root@localhost /]# docker pull mysql
Using default tag: latest              #如果不写tag 默认就是latest
latest: Pulling from library/mysql
b4d181a07f80: Pull complete         #分层下载,docker iamge的核心 联合文件系统
a462b60610f5: Pull complete 
578fafb77ab8: Pull complete 
524046006037: Pull complete 
d0cbe54c8855: Pull complete 
aa18e05cc46d: Pull complete 
32ca814c833f: Pull complete 
9ecc8abdb7f5: Pull complete 
ad042b682e0f: Pull complete 
71d327c6bb78: Pull complete 
165d1d10a3fa: Pull complete 
2f40c47d0626: Pull complete 
Digest: sha256:52b8406e4c32b8cf0557f1b74517e14c5393aff5cf0384eff62d9e81f4985d4b#签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest #真实地址
#等价于
docker pull mysql  ===   docker pull docker.io/library/mysql:latest
#指定版本下载
[root@localhost /]# docker pull mysql:5.7
5.7: Pulling from library/mysql
b4d181a07f80: Already exists 
a462b60610f5: Already exists 
578fafb77ab8: Already exists 
524046006037: Already exists 
d0cbe54c8855: Already exists 
aa18e05cc46d: Already exists 
32ca814c833f: Already exists 
52645b4af634: Pull complete 
bca6a5b14385: Pull complete 
309f36297c75: Pull complete 
7d75cacde0f8: Pull complete 
Digest: sha256:1a2f9cd257e75cc80e9118b303d1648366bc2049101449bf2c8d82b022ea86b7
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi 删除镜像

#删除指定ID镜像
docker rmi -f 镜像ID 
#删除指定ID镜像 (多个)
docker rmi -f 镜像ID 镜像ID 镜像ID 镜像ID
#递归删除所有镜像
docker rmi -f $(docker images -aq)  意思是全部镜像的id
容器命令

说明:我们有了镜像才可以创建容器 linux 下载一个centos镜像来测试学习

docker pull centos

新建容器并启动

docker run [可选参数] image
#参数说明
--name=“Name”  容器名称 tomcat01
-d               后台方式运行
-it            使用交互方式运行,进入容器查看内容
-p               指定容器的端口 -p 8080:8080
     -p ip:主机端口:容器端口
     -p 主机端口:容器端口(常用)
     -p 容器端口
-P             随机指定端口
#测试 进入容器
[root@localhost /]# docker run -it centos /bin/bash   启动以交互方式运行后面是操作控制台 一般Linux的在这个路径
#查看容器内的centos基础版本很多命令都是不完善的   (centos里面创建centos并进入)
[root@1797b984e8ee /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
#从容器中退回到主机
[root@1797b984e8ee /] exit # exit
[root@localhost /]# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

列出所有的运行的容器

#列出当前在运行的容器   (下面表示没有)
[root@localhost /]# docker ps   
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

docker ps [可选参数] # 列出当前正在运行的容器
#参数
-a    # 列出当前正在运行的容器 随便带出历史的内容
-n=?  # 显示最近创建的容器  ?后面是显示的个数
-q    # 只显示容器的编号

#查看曾经运行过的容器
docker ps -a

CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                     PORTS     NAMES
e270f5d60b2c   centos         "/bin/bash --name=ba…"   5 minutes ago   Exited (2) 5 minutes ago             recursing_gagarin
b80479a9e9b3   centos         "/bin/bash"              9 minutes ago   Exited (0) 7 minutes ago             strange_jemison
fb14b327581a   d1165f221234   "/hello"                 8 hours ago     Exited (0) 8 hours ago               eager_varahamihira

退出容器

exit 或 ctrl+d #直接退出容器,容器停止
Ctrl + P + Q #退出容器,容器继续运行

删除容器

docker rm #容器id       删除指定容器
docker rm -f $(docker ps -aq) #删除所有容器
docker ps -a -q|xargs docker rm #删除所有容器

启动和停止容器操作

docker start 容器id    #启动容器
docker restart 容器id  #重启动容器
docker stop 容器id     #停止当前正在运行动容器
docker kill 容器id     #强制停止当前容器
常用其他命令
#通过命令 docker run -d 镜像名 
[root@bogon /]# docker run -d centos  
#问题 docker ps 时候发现 centos停止了 
#常见的坑,docker 容器后台运行,就必须要有一个前台进程 docker发现没有命令就会停止#nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志

docker logs -f -t --tail 10  #容器id  #没有日志 
# 自己编写一段shell脚本[root@bogon /]# docker run -d centos /bin/sh -c "while true;do echo Sxr;sleep 1;done"[root@bogon /]# docker psPORTS          NAMESd5d5d925582f   centos #显示日志-tf           #显示日志 f带上时间--tail number #要显示的日志条数[root@bogon /]# docker logs -f -t --tail 10 d5d5d925582f [root@bogon /]# docker logs -tf --tail 10 d5d5d925582f

查看容器中的进程信息ps

top命令  
[root@bogon /]# docker top 容器id

UID        PID       PPID       C       STIME     TTY     TIME        CMD
root      1090855    1090833    0       00:39     pts/0   00:00:00    /bin/bash

查看镜像的源数据

[root@bogon /]# docker inspect 容器id

[
    {
        "Id": "1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192",
        "Created": "2021-07-17T16:03:57.640434781Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 1090855,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-07-17T16:39:40.932642816Z",
            "FinishedAt": "2021-07-17T16:07:20.922955Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192/hostname",
        "HostsPath": "/var/lib/docker/containers/1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192/hosts",
        "LogPath": "/var/lib/docker/containers/1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192/1cb906b671dae96960645d4acb2e6a3ae55b21dea041e245f3f0ab90f81a7192-json.log",
        "Name": "/modest_elgamal",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "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/d3a4ae6a8ec6203b0793e03b1179eb3f84d805b2728649f956bcaa3bef8e99d9-init/diff:/var/lib/docker/overlay2/7d95193935ad42cbb55109d434f8752da4d31419c0f91f225577b019e276fc0d/diff",
                "MergedDir": "/var/lib/docker/overlay2/d3a4ae6a8ec6203b0793e03b1179eb3f84d805b2728649f956bcaa3bef8e99d9/merged",
                "UpperDir": "/var/lib/docker/overlay2/d3a4ae6a8ec6203b0793e03b1179eb3f84d805b2728649f956bcaa3bef8e99d9/diff",
                "WorkDir": "/var/lib/docker/overlay2/d3a4ae6a8ec6203b0793e03b1179eb3f84d805b2728649f956bcaa3bef8e99d9/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "1cb906b671da",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "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": "f98705f7bca7c3f55f5458e63675e3d7005636305a088318fb0736ed6f4daa58",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/f98705f7bca7",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "5373279a2f2ee8a86814c4201d5bba29250598954a4548c51dbbe9ae174cfaf4",
            "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": "cca050cabcffb8c7734716aaff152a8d819692549fa7d4f6d8bc8c5429cb7cdb",
                    "EndpointID": "5373279a2f2ee8a86814c4201d5bba29250598954a4548c51dbbe9ae174cfaf4",
                    "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 /bin/bash 
# bashshell 操作 linux或者别的操作命令
#测试
[root@bogon /]# docker exec -it d5afb8e77654 /bin/bash
[root@d5afb8e77654 /]# ls
bin  etc   lib      lost+found  mnt  proc  run   srv  tmp  vardev  home  lib64  media       opt  root  sbin  sys  usr
[root@d5afb8e77654 /]# ps -ef
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 16:39 pts/0    00:00:00 /bin/bash
root          15       0  0 16:47 pts/1    00:00:00 /bin/bash
root          29      15  0 16:47 pts/1    00:00:00 ps -ef

#方式二
[root@bogon /]# docker attach  容器id      #进入正在执行当前代码...,

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

从容器内拷贝文件到主机上

docker cp 容器id:容器内路径 目的的主机路径
[root@bogon /home]# docker cp 容器id:/容器路径 /主机路径
#测试
[root@bogon /home]# docker cp 24fe5f78c8af:/home/test.java /home/ 
#先在容器内创建文件或目录
[root@24fe5f78c8af home]# touch test.java
[root@24fe5f78c8af home]# lstest.javaCtrl+p+q
[root@bogon /home]# docker cp 24fe5f78c8af:/home/test.java /home/
[root@bogon /home]# ls

Sxr.java  test.java  www  yacon

[root@bogon /home]#  rm -rf Sxr.java 
[root@bogon /home]# ls
test.java  www  yacon

#拷贝是一个手动过程未来使用 -v 数据卷的技术,可以实现数据同步

4.小结

attach    Attach to a running container                   #当前shel7 下attach连接指定运行镜像
build     Build an image from a Dockerfile                #通过Dockerfile定制镜像
commit    create a new image from a container changes     #提交当前容器为新的镜像
cp        copy files /folders from the containers filesystem to the host path 
#从容器中拷贝指定文件或者目录到宿主机中
create    Create a new container                          #创建一个新的容器,同run,但不启动容器
diff      Inspect changes on a container's filesystem     #查看docker容器变化
events    Get real time events from the server            #从docker服务获取容器实时事件
exec      Run a command in an existing container          #在已存在的容器上运行命令
export    Stream the contents of a container as a tar archive
#导出容器的内容流作为一个 tar归档文件[对应import ]
history   show the history of an image                    #展示一个镜像形成历史
images    List images                                     #列出系统当前镜像
import    create a new filesystem image from the contents of a tarbal1 
# 从tar包中的内容创建一个新的文件系统映像[对应export]
info      Display system-wide information                 #显示系统相关信息
inspect   Return low-1evel information on a container     #查看容器详细信息
Kill      Kill a running container                        # ki11指定docker容器
1oad      Load an image from a tar archive                #从一个tar包中加载一个镜像[对应save]
login     Register or Login to the docker registry server #注册或者登陆一个docker源服务器
logout    Log out from a Docker registry server           #从当前Docker registry退出
logs      Fetch the logs of a container                   #输出当前容器日志信息
port      Lookup the public-facing port which is NAT-ed to PRIVATE_PORT― 
#查看映射端口对应的容器内部源端
pause     Pause a1l processes within a container          #暂停容器
ps        List containers                                 #列出容器列表
pull      Pull an image or a repository from the docker registry server 
# 从docker镜像源服务器拉取指定镜像或者库镜像
push      Push an image or a repository to the docker registry server 
#推送指定镜像或者库镜像至docker源服务器
restart   Restart a running container                     #重启运行的容器
rm        Remove one or more containers                   #移除一个或者多个容器
rmi       Remove one or more i mages  
#移除一个或多个镜像[无容器使用该镜像才可删除,否则需删除相关器才可继续或 -f 强制删除]
run       Run a command in a new container                #创建一个新的容器并运行一个命令
save      Save an image to a tar archive                  #保存一个镜像为一个tar包[对应load]
search    Search for an image on the Docker Hub           #在docker hub中搜索镜像
start     Start a stopped containers                      #启动容器
stop      Stop a running containers                       #停止容器
tag       Tag an image into a repository                  #给源中镜像打标签
top       Lookup the running processes of a container     #查看容器中运行的进程信息
unpause   Unpause a paused container                      #取消暂停容器
version   Show the docker vers ion informati on           #查看docker版本号
wait      Block qnti1 a container stops, then print its exit code
#截取容器停止时的退出状态值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值