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@localhost /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    dd898494feb5d   7 months ago   13.3kB

# 解释
#REPOSITORY			# 镜像的仓库源
#TAG				# 镜像的标签(版本)		---lastest 表示最新版本
#IMAGE ID			# 镜像的id
#CREATED			# 镜像的创建时间
#SIZE				# 镜像的大小

# 可选项
Options:
  -a, --all         Show all images (default hides intermediate images) #列出所有镜像
  -q, --quiet       Only show numeric IDs # 只显示镜像的id
  
[root@localhost /]# docker images -a
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    dd898494feb5d   7 months ago   13.3kB
[root@localhost /]# docker images -aq
dd898494feb5d
docker search 搜索镜像
[root@localhost /]# docker search mysql

# --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@localhost /]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   12665     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4860      [OK]  
docker pull 下载镜像
# 下载镜像 docker pull 镜像名[:tag]
[root@localhost /]# docker pull tomcat:8
8: Pulling from library/tomcat #如果不写tag,默认就是latest
90fe46dd8199: Already exists   #分层下载: docker image 的核心 联合文件系统
35a4f1977689: Already exists 
bbc37f14aded: Already exists 
74e27dc593d4: Already exists 
93a01fbfad7f: Already exists 
1478df405869: Pull complete 
64f0dd11682b: Pull complete 
68ff4e050d11: Pull complete 
f576086003cf: Pull complete 
3b72593ce10e: Pull complete 
Digest: sha256:0c6234e7ec9d10ab32c06423ab829b32e3183ba5bf2620ee66de866df # 签名防伪
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 #删除指定id的镜像
docker rmi -f 镜像id 镜像id 镜像id  #删除多个镜像
[root@localhost /]# docker rmi -f f19c56ce92a8

docker rmi -f $(docker images -aq) #删除全部的镜像
[root@localhost /]# docker stop $(docker ps -a -q)

容器命令

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

镜像下载
#docker中下载centos
docker pull centos

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

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

docker rm 容器id #删除指定容器

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

#h和docker ps相同
[root@localhost~]# docker container list  

在这里插入图片描述

新建容器并启动
docker run [可选参数] image | docker container run [可选参数] image 

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


[root@localhost /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d898494feb5d   7 months ago   13.3kB
centos        latest    5d0da3dc9764   8 months ago   231MB

# 测试、启动并进入容器
#交互运行一般需要控制台,linux下交互一般是在/bin/bash
[root@localhost /]# docker run -it centos /bin/bash
#查看容器内的centos,基础版本,很多命令都是不完善的。
[root@e3f2795dcd8d /]# ls  
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@e3f2795dcd8d /]# exit #从容器退回主机
exit

在这里插入图片描述

列出所有运行的容器
docker ps 命令  		#列出当前正在运行的容器
  -a, --all     	 #列出当前正在运行的容器 + 带出历史运行过的容器
  -n=?, --last int   #列出最近创建的?个容器 ?为1则只列出最近创建的一个容器,为2则列出2个
  -q, --quiet        #只列出容器的编号

在这里插入图片描述

退出容器
exit 		#容器直接退出
ctrl +P +Q  #容器不停止退出 	---注意:这个很有用的操作
删除容器
docker rm 容器id   				#删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -rf
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@localhost /]# docker run -d centos
f568016737ce078966da6f355630333c6a9548f941062e9b447ecc817f942c17

[root@localhost /]# docker ps    
CONTAINER ID      IMAGE       COMMAND    CREATED     STATUS   PORTS    NAMES
# 问题docker ps. 发现centos 停止了
# 常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了
查看日志
docker logs --help
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:37) or relative (e.g. 42m for 42 minutes)
*      --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:37) or relative (e.g. 42m for 42 minutes)
      
#模拟日志      
➜  ~ docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done"

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

在这里插入图片描述

在这里插入图片描述

脚本日志会一直打印,Ctrl+C可以结束。

查看容器中进程信息ps
# 命令 
[root@localhost /]# docker top f5d864654949
UID:用户ID
PID:进程ID
PPID:父进程ID

在这里插入图片描述

查看镜像的元数据
# 命令
docker inspect 容器id

#测试[root@localhost /]# docker inspect d782dc86b584
[
    {
        "Id": "d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e",
        "Created": "2022-05-31T04:09:28.405677559Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo 6666;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 97211,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-05-31T04:09:28.914047565Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e/hostname",
        "HostsPath": "/var/lib/docker/containers/d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e/hosts",
        "LogPath": "/var/lib/docker/containers/d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e/d782dc86b584cb74551a42ed2f86e819ded89fe2d5ddfafaebe5c521330d544e-json.log",
        "Name": "/adoring_easley",
        "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/9b226c584452ed1d378608ae5f83bead130b851f16e1c4b287139c49524b0cbc-init/diff:/var/lib/docker/overlay2/d53e1df239ef5a7c9f595ee2e3636f1b52fd0a646d205f9b3e7ffd0da1cd67ca/diff",
                "MergedDir": "/var/lib/docker/overlay2/9b226c584452ed1d378608ae5f83bead130b851f16e1c4b287139c49524b0cbc/merged",
                "UpperDir": "/var/lib/docker/overlay2/9b226c584452ed1d378608ae5f83bead130b851f16e1c4b287139c49524b0cbc/diff",
                "WorkDir": "/var/lib/docker/overlay2/9b226c584452ed1d378608ae5f83bead130b851f16e1c4b287139c49524b0cbc/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d782dc86b584",
            "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 6666;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": "06754b8eafa35ef30dc1663970007571227d9654f80094585b9b7279cf0787f9",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/06754b8eafa3",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "d2d1cbb568c8645f5b9d2961556bf63ce8e7ce9ca39484ba0af9fe994d345049",
            "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": "41c637617071a9efa6df60f7acd67cda087db9dafae3e3cc9ff13f1797fa2eb0",
                    "EndpointID": "d2d1cbb568c8645f5b9d2961556bf63ce8e7ce9ca39484ba0af9fe994d345049",
                    "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
docker exec -it 容器id /bin/bash

\#测试
➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d782dc86b584 centos “/bin/sh -c 'while t…” 10 minutes ago Up 10 minutes bold_bell
d782dc86b584 centos “/bin/bash” 15 minutes ago Up 15 minutes lucid_clarke
➜ ~ docker exec -it d782dc86b584 /bin/bash
[root@d782dc86b584 /]#
# 方式二
docker attach 容器id
#测试
docker attach d782dc86b584 
正在执行当前的代码...



区别
docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
docker attach # 进入容器正在执行的终端,不会启动新的进程
从容器内拷贝到主机上
docker cp 容器id:容器内路径  主机目的路径

[root@localhost /]# docker ps
CONTAINER ID     IMAGE    COMMAND     CREATED         STATUS       PORTS      NAMES
d782dc86b584     centos   "/bin/bash" 7seconds ago    Up 6 seconds      

#1. 进入docker容器内部
[root@localhost /]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS       PORTS     NAMES
d782dc86b584   centos    "/bin/sh -c 'while t…"   3 hours ago   Up 3 hours             adoring_easley
[root@localhost /]# docker exec -it d782dc86b584 /bin/bash
[root@d782dc86b584 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

#新建一个文件
[root@d782dc86b584 /]# touch test.java
[root@d782dc86b584 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  test.java  tmp  usr  var
[root@d782dc86b584 /]# exit
exit

#test.java拷贝到这个主机 home文件加下
[root@localhost /]# docker cp d782dc86b584:/test.java /home 
[root@localhost /]# cd /home
[root@localhost home]# ls
apache-skywalking-apm-9.0.0.tar.gz  apache-skywalking-apm-bin  hxl  hxlStudy  mysql  one  test  test.java
[root@localhost home]# 
小结

image-20200514214313962
命令大全

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
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秦 羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值