Docker常用命令

https://docs.docker.com/engine/reference/commandline/docker/

Doker命令学习docs

1.查看docker信息
#查看docker版本信息
[root@VM-0-4-centos ~]# docker version

image-20210409112206466

# docker 系统的信息,包括容器,镜像信息
[root@VM-0-4-centos ~]# docker infO

image-20210409112102106

2.镜像命令
docker images #查看所有本地主机上的镜像 可以使用docker image ls代替
docker search #搜索镜像
docker pull   #下载镜像 docker image pull
docker rmi    #删除镜像 docker image rm
2.1查看镜像
[root@VM-0-4-centos ~]# docker images --help

image-20210409112251817

#显示本地所有的iamges
[root@VM-0-4-centos ~]# docker images -a

image-20210409112404362

  • **REPOSITORY:**表示镜像的仓库源

  • **TAG:**镜像的标签

  • **IMAGE ID:**镜像ID

  • **CREATED:**镜像创建时间

  • **SIZE:**镜像大小

    同一仓库源可以有多个 TAG,代表这个仓库源的不同个版本,如 ubuntu 仓库源里,有 15.10、14.04 等多个不同的版本,我们使用 REPOSITORY:TAG 来定义不同的镜像。

#显示本地所有的iamges的ID
[root@VM-0-4-centos ~]# docker images -q

image-20210409112518572

[root@VM-0-4-centos ~]# docker images --digests

image-20210409113146594

#List images by name and tag
[root@VM-0-4-centos ~]# docker images mysql
[root@VM-0-4-centos ~]# docker images mysql:5.7

image-20210409123511916

#展示image完整得ID
[root@VM-0-4-centos ~]# docker images --no-trunc

image-20210409123649267

2.2 删除镜像
#删除容器
docker rmi name:tag/ID


#此命令取消标记并删除与指定ID匹配的所有图像
docker rmi -f ID


#删除符合条件得images
docker rmi -f $()

image-20210409124450600

image-20210409124819785

2.3查找镜像

网页上(https://hub.docker.com/)可以查找你需要得image,和docker search redis 结果是一样得

image-20210409130054525

image-20210409130117039

#根据条件查找
[root@VM-0-4-centos ~]# docker search redis --filter=stars=500

image-20210409130214382

2.4下载镜像
[root@VM-0-4-centos ~]# docker pull centos  #没有设置tag ,默认拉取:latest
[root@VM-0-4-centos ~]# docker pull centos:7  

image-20210409131024165

2.5创建镜像

当我们从 docker 镜像仓库中下载的镜像不能满足我们的需求时,我们可以通过以下两种方式对镜像进行更改。

  • 1、从已经创建的容器中更新镜像,并且提交这个镜像
#1.运行一个容器
[root@VM-0-4-centos ~]# docker run --name=centos01 -it centos:7  /bin/bash
#2.在容器内做你想做得操作然后退出容器
#3 docker commit 来提交容器副本
[root@VM-0-4-centos ~]# docker commit -m="test" -a="wangxing" 41fff8e1d760 centos:7.1w
#4.查看我们的新镜像
[root@VM-0-4-centos ~]# docker images

各个参数说明:
-m: 提交的描述信息
-a: 指定镜像作者
41fff8e1d760:容器 ID
centos:7.1w: 指定要创建的目标镜像名

image-20210409142146449


  • 2、使用 Dockerfile 指令来创建一个新的镜像

docker build 构建一个新得镜像 ,需要创建一个新得Dockerfile,其中包含一组指令来告诉 Docker 如何构建我们的镜像。

FROM    centos:7
MAINTAINER      Fisher "fisher@sudops.com"

RUN     /bin/echo 'root:123456' |chpasswd
RUN     useradd runoob
RUN     /bin/echo 'runoob:123456' |chpasswd
RUN     /bin/echo -e "LANG=\"en_US.UTF-8\"" >/etc/default/local
EXPOSE  22
EXPOSE  80
CMD     /usr/sbin/sshd -D

每一个指令都会在镜像上创建一个新的层,每一个指令的前缀都必须是大写的。

第一条FROM,指定使用哪个镜像源

RUN 指令告诉docker 在镜像内执行命令,安装了什么。。。

[root@VM-0-4-centos ~]# docker build -t centos:7.2w .

参数说明:

  • -t :指定要创建的目标镜像名
  • . :Dockerfile 文件所在目录,可以指定Dockerfile 的绝对路径

image-20210409143121286

image-20210409143227283

设置镜像标签

[root@VM-0-4-centos ~]# docker tag 5643da3e0475 centos:7.2wtag
[root@VM-0-4-centos ~]# docker images    

image-20210409143447726

3.容器命令
docker run 镜像ID  			#新建容器并启动
docker ps					 #列出所有运行的容器 docker container list
docker rm 容器id   			#删除指定容器
docker start 容器id			#启动容器
docker restart 容器id 		#启动容器
docker stop 容器id 			#停止当前正在运行的容器
docker kill 容器id			#强制停止当前容器
3.1 docker run
-a stdin    #指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;
-d: 		#后台运行容器,并返回容器ID;
-i:			#以交互模式运行容器,通常与 -t 同时使用;	
-t: 		#为容器重新分配一个伪输入终端,通常与 -i 同时使用;
--name="":  #为容器指定一个名称;
-h "mars":  #指定容器的hostname;
-e username="ritchie": #设置环境变量;
--env-file=[]: #从指定文件读入环境变量;
--dns 8.8.8.8: #指定容器使用的DNS服务器,默认和宿主一致;
--dns-search example.com: #指定容器DNS搜索域名,默认和宿主一致;
-m :		#设置容器使用内存最大值;
--net="bridge": #指定容器的网络连接类型,支持 bridge/host/none/container: 四种类型;
--link=[]: 	#添加链接到另一个容器;
--expose=[]:#开放一个端口或一组端口;
-v: 		#绑定一个卷
-P:			#随机端口映射,容器内部端口随机映射到主机的端口
-p:			#指定端口映射,格式为:主机(宿主)端口:容器端口
3.2 docker ps
[root@VM-0-4-centos ~]# 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 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-0-4-centos ~]# docker ps -a

image-20210409143647910

[root@VM-0-4-centos ~]# docker ps -n 2
[root@VM-0-4-centos ~]# docker ps -l
[root@VM-0-4-centos ~]# docker ps -s
[root@VM-0-4-centos ~]# docker ps -q

image-20210409145019828

[root@VM-0-4-centos ~]# docker ps -f name=redis01

image-20210409145113403

FilterDescription
idContainer’s ID
nameContainer’s name
labelAn arbitrary string representing either a key or a key-value pair. Expressed as <key> or <key>=<value>
exitedAn integer representing the container’s exit code. Only useful with --all.
statusOne of created, restarting, running, removing, paused, exited, or dead
ancestorFilters containers which share a given image as an ancestor. Expressed as <image-name>[:<tag>], <image id>, or <image@digest>
before or sinceFilters containers created before or after a given container ID or name
volumeFilters running containers which have mounted a given volume or bind mount.
networkFilters running containers connected to a given network.
publish or exposeFilters containers which publish or expose a given port. Expressed as <port>[/<proto>] or <startport-endport>/[<proto>]
healthFilters containers based on their healthcheck status. One of starting, healthy, unhealthy or none.
isolationWindows daemon only. One of default, process, or hyperv.
is-taskFilters containers that are a “task” for a service. Boolean option (true or false)
3.3 docker rm
[root@VM-0-4-centos ~]# docker rm --help

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container
#docker rm 容器名字/ID 不能删除正在运行得容器,可以使用docker rm -f 

image-20210409145824911

#移除所有停止的容器
docker rm $(docker ps --filter status=exited -q)
#移除容器和它的数据卷
docker rm -v redis01

3.4 docker start

3.5 docker restart

3.6 docker stop

image-20210409172107436

3.7 docker kill —kill 一个或多个容器

4.常用其他命令
4.1后台运行容器
docker run -d  镜像ID

# 问题docker ps, 发现 centos 停止了

# 常见的坑, docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

解决方式
1.docker run --name=centos02 -d -it centos:7 /bin/bash
2.在启动脚本里面增加一个执行进程:(做一个死循环,持续输出任意)
docker run -d --name=centos03 centos:7 /bin/sh -c "while true; do echo hello world; sleep 1; done"

image-20210409173014033

4.2 查看日志
[root@VM-0-4-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         #跟踪日志输出
      --since string   #显示某个开始时间的所有日志
  -n, --tail string    #仅列出最新N条容器日志 (default "all")
  -t, --timestamps     #显示时间戳
      --until string   #显示某个结束时间的所有日志
      
[root@VM-0-4-centos ~]# docker logs -n 10 -t redis01

image-20210409173947238

4.3查看容器中得进程信息
docker top 容器id

image-20210409175825661

4.4查看镜像源数据
[root@VM-0-4-centos ~]# docker inspect redis01 #容器id/name
[
    {
        "Id": "d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d",
        "Created": "2021-04-09T09:15:32.484963252Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "redis-server"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 32477,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-04-09T09:20:29.934524198Z",
            "FinishedAt": "2021-04-09T09:20:10.144792208Z"
        },
        "Image": "sha256:7f33e76fcb56c96639cd127aca5f6cb61c526c3c6013048f637c32e863b7b012",
        "ResolvConfPath": "/var/lib/docker/containers/d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d/hostname",
        "HostsPath": "/var/lib/docker/containers/d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d/hosts",
        "LogPath": "/var/lib/docker/containers/d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d/d6a0525b37504865629c93a00eefc0cf0e94921a65f1d65b9d0f4dcafaa7e42d-json.log",
        "Name": "/redis01",
        "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/0576e2c8a2e11c76dbfeb687e18141191e2c13f8ef51396771a4875c7c1586f0-init/diff:/var/lib/docker/overlay2/b95ae13a63e6c5658af6f9efc550ace5fa20ecf6d23e16b5051d5b65b36da32a/diff:/var/lib/docker/overlay2/622caa3389fa64710e9fc1c2406274f4f7e7ce7f4e7790356dd5e3416fd024a0/diff:/var/lib/docker/overlay2/8d2c793c0614d5441f8513e648b2f636858598e8428cb916e134986f2b967f26/diff:/var/lib/docker/overlay2/50bc5f5ef3d05579dbcf2764bfd941037f919cadb195516bf3eb6cf5acb04631/diff:/var/lib/docker/overlay2/1c73be575a123bfe712122769a3870f27c3ea8679fe536c1099df59d5865f583/diff:/var/lib/docker/overlay2/e8cf2071e7d9b36fb57c537bde819666c714f3b24a658c673df7622ff6336851/diff",
                "MergedDir": "/var/lib/docker/overlay2/0576e2c8a2e11c76dbfeb687e18141191e2c13f8ef51396771a4875c7c1586f0/merged",
                "UpperDir": "/var/lib/docker/overlay2/0576e2c8a2e11c76dbfeb687e18141191e2c13f8ef51396771a4875c7c1586f0/diff",
                "WorkDir": "/var/lib/docker/overlay2/0576e2c8a2e11c76dbfeb687e18141191e2c13f8ef51396771a4875c7c1586f0/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "c9067efe46ede5b1b668fc00b1e35b7ed510fc7b95662341073f730a47927308",
                "Source": "/var/lib/docker/volumes/c9067efe46ede5b1b668fc00b1e35b7ed510fc7b95662341073f730a47927308/_data",
                "Destination": "/data",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "d6a0525b3750",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "6379/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "REDIS_VERSION=6.2.1",
                "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-6.2.1.tar.gz",
                "REDIS_DOWNLOAD_SHA=cd222505012cce20b25682fca931ec93bd21ae92cb4abfe742cf7b76aa907520"
            ],
            "Cmd": [
                "redis-server"
            ],
            "Image": "redis",
            "Volumes": {
                "/data": {}
            },
            "WorkingDir": "/data",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "ee3f599e6d928a08fd0b34d785c7d03056909389c8942a705d43e5f40906fb11",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "6379/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/ee3f599e6d92",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "0dfd99feedb6d9a2314c40ab3cfc1abf42e243135110a09589f5b30557b0d44a",
            "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": "fa10e19790b36b0053727f1ddb39eb939050d9d6a48999a0ae81803666a150e2",
                    "EndpointID": "0dfd99feedb6d9a2314c40ab3cfc1abf42e243135110a09589f5b30557b0d44a",
                    "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
                }
            }
        }
    }
]

4.5进入正在运行的容器
root@VM-0-4-centos ~]# docker exec --help

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container

docker exec -it 容器id baseShell #进入容器后开启一个新的终端,可以在里面操作(常用)
[root@VM-0-4-centos ~]# docker exec -it redis01 /bin/bash
root@d6a0525b3750:/data# 

docker attach 容器id #进入容器正在执行的终端,不会启动新的进程

image-20210409225717143

4.6从容器内拷贝到主机上
#容器到主机
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-

#先在运行的容器中/usr/local/下,增加一个testcp文件,将文件copy到主机的相应位置下 

image-20210409231646287

#主机到容器
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

image-20210409232120052

5.镜像仓库命令
5.1 login/logout
docker login -u -p		#登陆到一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub
docker logout 		#登出一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub
5.2 pull
docker pull #从镜像仓库中拉取或者更新指定镜像

docker pull [OPTIONS] NAME[:TAG|@DIGEST]
#OPTIONS
	-a 拉取所有 tagged 镜像
5.3 push
我们在上面docker commit时更新了镜像,现在我们将centos:7.1w push到Docker Hub, 必须先登录
https://hub.docker.com/   注册

image-20210409234816326

登陆后还是denied,因为推送镜像的规范是:docker push 注册用户名/镜像名

image-20210409234850852

tag命令修改为规范的镜像,然后推送(推送Docker Hub速度很慢,耐心等待,很有可能失败,失败会尝试多次重传)

image-20210409235046847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值