docer笔记3

docker笔记3


容器基本命令

下载镜像

docker pull cento

新建容器并启动

docker run [可选参数] image

# 参数说明
--name=“Name”   容器名字    tomcat01    tomcat02    用来区分容器
-d      		后台方式运行
-it     		使用交互方式运行,进入容器查看内容
-p      		指定容器的端口     -p 8080:8080
    -p  ip:主机端口:容器端口
    -p  主机端口:容器端口(常用)
    -p  容器端口
    容器端口
-P      		随机指定端口
 
# 测试,启动并进入容器
[root@localhost ~]# docker run -it centos /bin/bash
[root@31225df28944 /]# ls	 # 查看容器内的centos,基础版本,很多命令是不完善的
bin  etc   lib	  lost+found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr

# 从容器中退回主机
[root@31225df28944 /]# exit
exit
[root@localhost ~]# ls
anaconda-ks.cfg       公共  视频  文档  音乐
initial-setup-ks.cfg  模板  图片  下载  桌面

列出所有运行的容器

# docker ps 命令        # 列出当前正在运行的容器
-a      # 列出正在运行的容器包括历史容器
-n=?    # 显示最近创建的容器
-q      # 只显示当前容器的编号
 
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED         STATUS                     PORTS     NAMES
31225df28944   centos        "/bin/bash"   8 minutes ago   Exited (0) 3 minutes ago             blissful_leavitt
7be2b60ed0c5   hello-world   "/hello"      9 days ago      Exited (0) 9 days ago                agitated_goodall

[root@localhost ~]# docker ps -a -n=1
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
31225df28944   centos    "/bin/bash"   11 minutes ago   Exited (0) 6 minutes ago             blissful_leavitt

[root@localhost ~]# docker ps -aq
31225df28944
7be2b60ed0c5

在这里插入图片描述删除容器

docker rm  容器id                    # 删除指定容器,不能删除正在运行的容器,如果要强制删除  rm -f
docker rm -f 容器id                  # 强制删除指定容器
docker rm -f $(docker ps -aq)       # 删除所有容器
docker ps -a -q|xargs docker rm -f  # 删除所有容器(通过管道符)

启动或停止容器的操作

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

# 测试
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
2f0fad47b419   centos    "/bin/bash"   12 minutes ago   Up 12 minutes             vigorous_curie

# 停止当前正在运行的 centos
[root@localhost ~]# docker stop 2f0fad47b419
2f0fad47b419

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# 启动 centos容器
[root@localhost ~]# docker start 2f0fad47b419
2f0fad47b419

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS         PORTS     NAMES
2f0fad47b419   centos    "/bin/bash"   15 minutes ago   Up 7 seconds             vigorous_curie
# 测试成功

常用命令

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

前台进程与后台进程

在 Docker 的上下文中,当我们启动数据库服务器或其他任何服务(如 Web 服务器)作为后台进程时,实际上是启动了一个包含前台进程的容器。这个前台进程负责执行服务的核心功能,如监听特定的端口、处理请求等。

前台进程:在 Docker 容器中,前台进程是容器启动时运行的主进程。它是容器内部的核心服务,负责执行容器的主要功能。

后台运行:当我们使用 docker run -d 命令启动容器时,容器会在后台运行。但是,这并不意味着容器内部没有前台进程。相反,容器内部的前台进程仍然在运行,只是容器本身被置于了后台。


服务镜像(如数据库、Web 服务器):这些镜像通常包含了一个或多个前台进程,这些进程负责提供服务。例如,数据库镜像可能包含了一个前台进程来监听数据库连接请求,Web 服务器镜像可能包含了一个前台进程来监听 HTTP 请求。

基础镜像(如 CentOS):基础镜像通常不包含特定的服务进程,而是提供了一个基本的操作系统环境。如果我们只是简单地启动一个 CentOS 镜像的容器而不运行任何前台进程(如通过 docker run -d centos),那么容器内部将没有持续运行的前台进程,容器可能会在几秒钟后停止,因为它没有做任何事情。


查看日志

docker logs -tf --tail number 容器id

[root@localhost ~]# docker logs -tf --tail 3 2f0fad47b419    # 查到两条日志
2023-01-14T12:33:59.839621096Z [root@2f0fad47b419 /]# exit
2023-01-14T12:45:03.884332494Z [root@2f0fad47b419 /]# exit
 
# 自己编写一段shell脚本
[root@localhost ~]#  docker run -d centos /bin/sh -c "while true;do echo kuangshen;sleep 1;done"
91973e3049338501c282d003c4b8703243aed3ca9362cfda486eefd10f4adc6a

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
91973e304933   centos    "/bin/sh -c 'while t…"   13 seconds ago   Up 13 seconds             dazzling_einstein
2f0fad47b419   centos    "/bin/bash"              37 minutes ago   Up 4 minutes              vigorous_curie
                           lucid_black
 
# 显示日志
-tf                 # 显示日志
--tail number       # 显示日志条数

# 测试
[root@localhost ~]# docker logs -tf --tail 3 91973e304933
2023-01-14T12:58:48.930057833Z kuangshen
2023-01-14T12:58:49.935107229Z kuangshen
2023-01-14T12:58:50.937433583Z kuangshen

查看容器中的进程信息

docker top 容器id
[root@ser878629168738 /]# docker top 21be0719efa1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                3247                3225                0                   02:56               ?                   00:00:00            /bin/sh -c while true;do echo kuangshen;sleep 1;done
root                5659                3247                0                   02:59               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像源数据

[root@ser878629168738 /]# docker inspect 21be0719efa1
[
    {
        "Id": "21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9",
        "Created": "2024-07-14T02:56:34.80030493Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo kuangshen;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 3247,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-07-14T02:56:35.105310691Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9/hostname",
        "HostsPath": "/var/lib/docker/containers/21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9/hosts",
        "LogPath": "/var/lib/docker/containers/21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9/21be0719efa1cd4f7f638d3c1aab3e6b6a05de78328cdfdb5c3d3685f11376e9-json.log",
        "Name": "/hopeful_buck",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                24,
                160
            ],
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": [],
            "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",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/55800655659efaa9b74ee5020cd96af9f6f8682cdcbf21ddeee20bee1d4f7aeb-init/diff:/var/lib/docker/overlay2/39188b282c532b3174eeef11b7cf6836535c6e77858baefed3ce02a0fa7174fe/diff",
                "MergedDir": "/var/lib/docker/overlay2/55800655659efaa9b74ee5020cd96af9f6f8682cdcbf21ddeee20bee1d4f7aeb/merged",
                "UpperDir": "/var/lib/docker/overlay2/55800655659efaa9b74ee5020cd96af9f6f8682cdcbf21ddeee20bee1d4f7aeb/diff",
                "WorkDir": "/var/lib/docker/overlay2/55800655659efaa9b74ee5020cd96af9f6f8682cdcbf21ddeee20bee1d4f7aeb/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "21be0719efa1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo kuangshen;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "966effb4642648521f8d544e341f03e8e838ac379cb253818097d87492182a51",
            "SandboxKey": "/var/run/docker/netns/966effb46426",
            "Ports": {},
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "35a0052ff05e4bf454c2de7531ca1a578535ffbeb7a774877efe134ce2f67a03",
            "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,
                    "MacAddress": "02:42:ac:11:00:02",
                    "NetworkID": "043669c137823c175ada24b7b1020003d7df3b6b93e659fa2f2271b39c2525b4",
                    "EndpointID": "35a0052ff05e4bf454c2de7531ca1a578535ffbeb7a774877efe134ce2f67a03",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DriverOpts": null,
                    "DNSNames": null
                }
            }
        }
    }
]
[root@ser878629168738 /]# 

进入当前正在运行的容器

docker exec -it 容器id /bin/bash       # 进入容器后开启一个新的终端,可以在里面操作
docker attach 容器id     # 进入容器正在执行的终端,不会启动新的进程

容器中的文件拷贝到主机上

docker cp 容器id:容器内路径 目的地主机路径
[root@ser878629168738 ~]# docker run -it centos /bin/bash
[root@ac0120ef32dd /]# cd /home
[root@ac0120ef32dd home]# ls
[root@ac0120ef32dd home]# touch test.java
[root@ac0120ef32dd home]# ls
test.java
[root@ac0120ef32dd home]# exit
exit
[root@ser878629168738 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ser878629168738 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED             STATUS                         PORTS     NAMES
ac0120ef32dd   centos         "/bin/bash"   54 seconds ago      Exited (0) 19 seconds ago                awesome_khorana
a475fc9e5910   centos         "/bin/bash"   3 minutes ago       Exited (0) 2 minutes ago                 inspiring_sammet
6ed2981c6bb3   centos         "/bin/bash"   5 minutes ago       Exited (127) 4 minutes ago               fervent_knuth
1679f11beb1a   centos         "/bin/bash"   59 minutes ago      Exited (0) 59 minutes ago                kind_darwin
cf41b8e4aecd   centos         "/bin/bash"   About an hour ago   Exited (0) About an hour ago             quizzical_almeida
57931efff3da   centos         "/bin/bash"   2 days ago          Exited (0) 2 days ago                    reverent_babbage
ee30dbf0b0da   centos         "/bin/bash"   2 days ago          Exited (0) 2 days ago                    priceless_gould
18d8f574057b   centos         "/bin/bash"   2 days ago          Exited (0) 2 days ago                    crazy_visvesvaraya
09a018300dbd   d2c94e258dcb   "/hello"      4 days ago          Exited (0) 4 days ago                    stoic_chebyshev
[root@ser878629168738 ~]# docker cp ac0120ef32dd:/home/test.java /home
                                               Successfully copied 1.54kB to /home
[root@ser878629168738 ~]# cd /home
[root@ser878629168738 home]# ls
test.java
[root@ser878629168738 home]# 

常用命令小结

在这里插入图片描述
在这里插入图片描述

attach    Attach 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 from a container to a HOSTDIR or to STDOUT  
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 a running container#在已存在的容器上运行命令
# 导出容器的内容流作为一个tar归档文件(对应import)
export    Export a container's filesystem as a tar archive  
history   Show the history of an image  #展示一个镜像形成历史
images    List images  #列出系统当前镜像
# 从tar包中的内容创建一个新的文件系统映像(对应export)
import    Import the contents from a tarball to create a filesystem image  
info      Display system-wide information  #显示系统相关信息
inspect   Return low-level information on a container or image  #查看容器详细信息
kill      Kill a running container  #kill指定docker容器
# 从一个tar包中加载一个镜像(对应save)
load      Load an image from a tar archive or STDIN  
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  #列出容器列表
# 从docker镜像源服务器拉取指定镜像或者库镜像
pull      Pull an image or a repository from a registry  
# 推送指定镜像或者库镜像至docker源服务器
push      Push an image or a repository to a registry  
rename    Rename a container  #重命名容器
restart   Restart a running container  #重启运行的容器
rm        Remove one or more containers  #移除一个或者多个容器
# 移除一个或多个镜像(无容器使用该镜像才可以删除,否则需要删除相关容器才可以继续或者-f强制删除)
rmi       Remove one or more images  
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  

相关推荐

  1. docker笔记

    2024-07-23 07:36:04       65 阅读
  2. Docker笔记

    2024-07-23 07:36:04       31 阅读
  3. 3.11笔记3

    2024-07-23 07:36:04       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-23 07:36:04       172 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-23 07:36:04       190 阅读
  3. 在Django里面运行非项目文件

    2024-07-23 07:36:04       158 阅读
  4. Python语言-面向对象

    2024-07-23 07:36:04       171 阅读

热门阅读

  1. 驱动开发系列07 - 驱动程序如何分配内存

    2024-07-23 07:36:04       30 阅读
  2. C++链表

    C++链表

    2024-07-23 07:36:04      31 阅读
  3. “微软蓝屏”事件暴露的网络安全问题

    2024-07-23 07:36:04       38 阅读
  4. 【SpringBoot】第3章 系统配置之日志配置

    2024-07-23 07:36:04       30 阅读
  5. Hopfield 网络简介

    2024-07-23 07:36:04       35 阅读
  6. 为什么要学习网安技术?

    2024-07-23 07:36:04       28 阅读
  7. R语言读取txt和csv只有1列时

    2024-07-23 07:36:04       33 阅读
  8. 2024 7.15~7.21 周报

    2024-07-23 07:36:04       35 阅读
  9. 力扣 102题 二叉树的层次遍历 记录

    2024-07-23 07:36:04       28 阅读