当前位置:   article > 正文

Docker常用指令和镜像操作详解一文速学+实例代码_docker运行镜像的命令

docker运行镜像的命令

目录

前言

一、Docker基础命令

1.启动docker

 2.查看状态

 3.关闭docker

 4.开机自启

 5.查看版本信息

 6.查看帮助

二、Docker镜像命令

1.查看docker镜像

 2.搜索镜像

搜索不小于10000星的busybox的镜像

 format格式化输出

 限制搜索输出个数

 禁止截断输出

3.拉取镜像

 4.删除所有镜像

​编辑 5.删除指定镜像

6.TAG修改生成新镜像

 7.保存镜像

 8.加载镜像

 9.显示历史镜像操作

 10.显示镜像的详细信息

11.从归档文件中创建镜像

​编辑

12.上传镜像

13.创建镜像

14.运行镜像

三、docker容器命令

1.查看正在运行容器列表

-a 查看所有容器

​编辑

-n 个数 列出最近创建的容器

-aq 显示所有运行过的容器的id 

 2.删除容器

rm -f 容器id 删除容器

 rm -f $(docker ps -aq) 删除所有docker容器

docker ps -aq|xargs docker rm -f 也可以删除所有的容器

3.启动容器

  start 容器id 启动容器

 restart 容器id 重启容器

stop 容器id  停止容器

当使用docker stop 无法停止时,可以使用docker kill 直接杀掉 

4. 查看日志命令

查看启动容器的最新num行的日志

5. 查看容器的进程信息

6.重新打开一个终端的方式进入docker

 7.进入容器中正在运行的终端

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

点关注,防走丢,如有纰漏之处,请留言指教,非常感谢

参阅



前言

现在搭建部署环境基本都是用Docker进行,学会Docker指令相当重要。在我的Docker系列文章中我们已经进行了很多准备工作,我是在云服务器上面进行部署的工作,大大省去了虚拟机环境配置时间,大家可以用用看:

云服务器Centos8.2SSH登陆、安装部署图形化界面以及VNC连接一文详解

云服务器CentOS8.2安装部署Docker一文详解

云服务器CentOS8.2Docker图形化管理工具Portainer安装部署

下面仍旧还是使用SecureCRT进行指令演示。

很多学Python伙伴问题有没有体系的面试题?
今天为大家推荐一款刷题神奇哦 :刷题面试神器牛客
各大互联网大厂面试真题。从基础到入阶乃至原理刨析类面试题 应有尽有,赶快来装备自己吧!助你面试稳操胜券,solo全场面试官


一、Docker基础命令

1.启动docker

systemctl start docker

 2.查看状态

systemctl status docker

 3.关闭docker

systemctl stop docker

 4.开机自启

systemctl enable docker

 5.查看版本信息

docker version
docker info

 6.查看帮助

docker --help

若忘记了某个指令的功能可以在后面加上help查看功能: 

docker 指令参数 --help

二、Docker镜像命令

1.查看docker镜像

docker images

 可以通过--help查看每一个Image命令的详细信息。

docker image ls --help

 显示所有镜像(默认隐藏中间图像)

docker image ls -a

 docker imagesdocker image lsdocker image ls -a是一样的效果。

docker image ls -q

仅输出image的IMAGE ID。 

 2.搜索镜像

docker search 镜像名

 比如:

docker search [OPTIONS] TERM

其中OPTIONS有:

  •  --automated:弃用,只列出自动构建类型的镜像
  • --filter , -f:基于给定条件过滤输出
  • --format:使用模板格式化显示输出    
  • --limit:Max number of search results ,默认值25
  • --no-trunc:禁止截断输出
  • --stars , -s:弃用,只显示收藏数不小于几颗星的镜像,移到--filter中使用 

代码如下(示例):

搜索不小于10000星的busybox的镜像

docker search --filter=stars=10000 mysql

 format格式化输出

  • .Description   镜像描述
  • .StarCount    star数量   
  •  .IsOfficial    “OK” 表示官方镜像
  • .IsAutomated    “OK” 表示自动构建  
docker search --format "{{.Name}}:{{.StarCount}}" mysql

docker search --format "table {{.Name}}\t{{.IsAutomated}}\t{{.IsOfficial}}" redis

 限制搜索输出个数

docker search redis --filter=stars=500 --limit 3

 禁止截断输出

 docker search --no-trunc mysql

 

3.拉取镜像

代码如下(示例):

docker image pull

参数可以选有两个:

 例如拉取一个最新的redis:

docker image pull redis

 

拉取完后docker images查看:

 

 4.删除所有镜像

代码如下:

docker image prune [OPTIONS]

 5.删除指定镜像

docker image rm [OPTIONS] IMAGE [IMAGE...]

 

 删除TAG为latest最新版本的redis:

docker image rm redis:latest

6.TAG修改生成新镜像

docker image tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

 

docker image tag hello-world:latest hello-world:v.1.0

 7.保存镜像

docker image save [OPTIONS] IMAGE [IMAGE...]

docker image save hello-world:v.1.0 > hw.tar

 保存到指定目录:

docker image save hello-worl:v.1.0 -o /usr/local/hw.tar

 8.加载镜像

docker image load [OPTIONS]

 我们一开始是把hello-world的v.1.0的版本给删了,现在我们可以把通过本地保存的hello-world给放到image里面去:

 docker image load <hw.tar

 

 加载指定路径的镜像源:

docker load -i /usr/local/hw.tar   # 指定加载镜像的源

 9.显示历史镜像操作

docker image history [OPTIONS] IMAGE

 docker image history hello-world:v.1.0

 10.显示镜像的详细信息

docker image inspect [OPTIONS] IMAGE [IMAGE...]

 例如我们查看hello-world镜像的详细信息会发现:

docker image inspect hello-world

 一大串JSON文件格式:

11.从归档文件中创建镜像

docker image import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

docker image import hw.tar   # 一般需要指定镜像名字

12.上传镜像

docker image push [OPTIONS] NAME[:TAG]

 这样就是上传成功了可以在dockerhub上看到自己上传的镜像:

docker push fanstuck/my-private-repo:hellow-world

 

13.创建镜像

docker image build [OPTIONS] PATH | URL | -

 bulid属于制作镜像是一个较为复杂且需要编写程序的过程,因此参数相应的会比较复杂:

  1. Usage: docker [OPTIONS] COMMAND
  2. A self-sufficient runtime for containers
  3. Options:
  4. --config string Location of client config files (default "/root/.docker")
  5. -c, --context string Name of the context to use to connect to the daemon
  6. (overrides DOCKER_HOST env var and default context set
  7. with "docker context use")
  8. -D, --debug Enable debug mode
  9. -H, --host list Daemon socket(s) to connect to
  10. -l, --log-level string Set the logging level
  11. ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
  12. --tls Use TLS; implied by --tlsverify
  13. --tlscacert string Trust certs signed only by this CA (default
  14. "/root/.docker/ca.pem")
  15. --tlscert string Path to TLS certificate file (default
  16. "/root/.docker/cert.pem")
  17. --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
  18. --tlsverify Use TLS and verify the remote
  19. -v, --version Print version information and quit
  20. Management Commands:
  21. app* Docker App (Docker Inc., v0.9.1-beta3)
  22. builder Manage builds
  23. buildx* Build with BuildKit (Docker Inc., v0.6.3-docker)
  24. compose* Docker Compose (Docker Inc., v2.6.0)
  25. config Manage Docker configs
  26. container Manage containers
  27. context Manage contexts
  28. image Manage images
  29. manifest Manage Docker image manifests and manifest lists
  30. network Manage networks
  31. node Manage Swarm nodes
  32. plugin Manage plugins
  33. scan* Docker Scan (Docker Inc., v0.17.0)
  34. secret Manage Docker secrets
  35. service Manage services
  36. stack Manage Docker stacks
  37. swarm Manage Swarm
  38. system Manage Docker
  39. trust Manage trust on Docker images
  40. volume Manage volumes
  41. Commands:
  42. attach Attach local standard input, output, and error streams to a running container
  43. build Build an image from a Dockerfile
  44. commit Create a new image from a container's changes
  45. cp Copy files/folders between a container and the local filesystem
  46. create Create a new container
  47. diff Inspect changes to files or directories on a container's filesystem
  48. events Get real time events from the server
  49. exec Run a command in a running container
  50. export Export a container's filesystem as a tar archive
  51. history Show the history of an image
  52. images List images
  53. import Import the contents from a tarball to create a filesystem image
  54. info Display system-wide information
  55. inspect Return low-level information on Docker objects
  56. kill Kill one or more running containers
  57. load Load an image from a tar archive or STDIN
  58. login Log in to a Docker registry
  59. logout Log out from a Docker registry
  60. logs Fetch the logs of a container
  61. pause Pause all processes within one or more containers
  62. port List port mappings or a specific mapping for the container
  63. ps List containers
  64. pull Pull an image or a repository from a registry
  65. push Push an image or a repository to a registry
  66. rename Rename a container
  67. restart Restart one or more containers
  68. rm Remove one or more containers
  69. rmi Remove one or more images
  70. run Run a command in a new container
  71. save Save one or more images to a tar archive (streamed to STDOUT by default)
  72. search Search the Docker Hub for images
  73. start Start one or more stopped containers
  74. stats Display a live stream of container(s) resource usage statistics
  75. stop Stop one or more running containers
  76. tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  77. top Display the running processes of a container
  78. unpause Unpause all processes within one or more containers
  79. update Update configuration of one or more containers
  80. version Show the Docker version information
  81. wait Block until one or more containers stop, then print their exit codes
  82. Run 'docker COMMAND --help' for more information on a command.

这里参数十分丰富,以后将独自写一期docker bulid来详细介绍该功能的使用,属于制作镜像一块的,是比较大的一块docker内容。

14.运行镜像

创建一个新的容器并运行一个命令

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

 相应的参数也是十分的多的:

  1. Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
  2. Run a command in a new container
  3. Options:
  4. --add-host list Add a custom host-to-IP mapping (host:ip)
  5. -a, --attach list Attach to STDIN, STDOUT or STDERR
  6. --blkio-weight uint16 Block IO (relative weight), between 10 and
  7. 1000, or 0 to disable (default 0)
  8. --blkio-weight-device list Block IO weight (relative device weight)
  9. (default [])
  10. --cap-add list Add Linux capabilities
  11. --cap-drop list Drop Linux capabilities
  12. --cgroup-parent string Optional parent cgroup for the container
  13. --cgroupns string Cgroup namespace to use (host|private)
  14. 'host': Run the container in the Docker
  15. host's cgroup namespace
  16. 'private': Run the container in its own
  17. private cgroup namespace
  18. '': Use the cgroup namespace as
  19. configured by the
  20. default-cgroupns-mode option on
  21. the daemon (default)
  22. --cidfile string Write the container ID to the file
  23. --cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
  24. --cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
  25. --cpu-rt-period int Limit CPU real-time period in microseconds
  26. --cpu-rt-runtime int Limit CPU real-time runtime in microseconds
  27. -c, --cpu-shares int CPU shares (relative weight)
  28. --cpus decimal Number of CPUs
  29. --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
  30. --cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
  31. -d, --detach Run container in background and print container ID
  32. --detach-keys string Override the key sequence for detaching a
  33. container
  34. --device list Add a host device to the container
  35. --device-cgroup-rule list Add a rule to the cgroup allowed devices list
  36. --device-read-bps list Limit read rate (bytes per second) from a
  37. device (default [])
  38. --device-read-iops list Limit read rate (IO per second) from a device
  39. (default [])
  40. --device-write-bps list Limit write rate (bytes per second) to a
  41. device (default [])
  42. --device-write-iops list Limit write rate (IO per second) to a device
  43. (default [])
  44. --disable-content-trust Skip image verification (default true)
  45. --dns list Set custom DNS servers
  46. --dns-option list Set DNS options
  47. --dns-search list Set custom DNS search domains
  48. --domainname string Container NIS domain name
  49. --entrypoint string Overwrite the default ENTRYPOINT of the image
  50. -e, --env list Set environment variables
  51. --env-file list Read in a file of environment variables
  52. --expose list Expose a port or a range of ports
  53. --gpus gpu-request GPU devices to add to the container ('all' to
  54. pass all GPUs)
  55. --group-add list Add additional groups to join
  56. --health-cmd string Command to run to check health
  57. --health-interval duration Time between running the check (ms|s|m|h)
  58. (default 0s)
  59. --health-retries int Consecutive failures needed to report unhealthy
  60. --health-start-period duration Start period for the container to initialize
  61. before starting health-retries countdown
  62. (ms|s|m|h) (default 0s)
  63. --health-timeout duration Maximum time to allow one check to run
  64. (ms|s|m|h) (default 0s)
  65. --help Print usage
  66. -h, --hostname string Container host name
  67. --init Run an init inside the container that
  68. forwards signals and reaps processes
  69. -i, --interactive Keep STDIN open even if not attached
  70. --ip string IPv4 address (e.g., 172.30.100.104)
  71. --ip6 string IPv6 address (e.g., 2001:db8::33)
  72. --ipc string IPC mode to use
  73. --isolation string Container isolation technology
  74. --kernel-memory bytes Kernel memory limit
  75. -l, --label list Set meta data on a container
  76. --label-file list Read in a line delimited file of labels
  77. --link list Add link to another container
  78. --link-local-ip list Container IPv4/IPv6 link-local addresses
  79. --log-driver string Logging driver for the container
  80. --log-opt list Log driver options
  81. --mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
  82. -m, --memory bytes Memory limit
  83. --memory-reservation bytes Memory soft limit
  84. --memory-swap bytes Swap limit equal to memory plus swap: '-1' to
  85. enable unlimited swap
  86. --memory-swappiness int Tune container memory swappiness (0 to 100)
  87. (default -1)
  88. --mount mount Attach a filesystem mount to the container
  89. --name string Assign a name to the container
  90. --network network Connect a container to a network
  91. --network-alias list Add network-scoped alias for the container
  92. --no-healthcheck Disable any container-specified HEALTHCHECK
  93. --oom-kill-disable Disable OOM Killer
  94. --oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
  95. --pid string PID namespace to use
  96. --pids-limit int Tune container pids limit (set -1 for unlimited)
  97. --platform string Set platform if server is multi-platform capable
  98. --privileged Give extended privileges to this container
  99. -p, --publish list Publish a container's port(s) to the host
  100. -P, --publish-all Publish all exposed ports to random ports
  101. --pull string Pull image before running
  102. ("always"|"missing"|"never") (default "missing")
  103. --read-only Mount the container's root filesystem as read only
  104. --restart string Restart policy to apply when a container
  105. exits (default "no")
  106. --rm Automatically remove the container when it exits
  107. --runtime string Runtime to use for this container
  108. --security-opt list Security Options
  109. --shm-size bytes Size of /dev/shm
  110. --sig-proxy Proxy received signals to the process
  111. (default true)
  112. --stop-signal string Signal to stop a container (default "SIGTERM")
  113. --stop-timeout int Timeout (in seconds) to stop a container
  114. --storage-opt list Storage driver options for the container
  115. --sysctl map Sysctl options (default map[])
  116. --tmpfs list Mount a tmpfs directory
  117. -t, --tty Allocate a pseudo-TTY
  118. --ulimit ulimit Ulimit options (default [])
  119. -u, --user string Username or UID (format: <name|uid>[:<group|gid>])
  120. --userns string User namespace to use
  121. --uts string UTS namespace to use
  122. -v, --volume list Bind mount a volume
  123. --volume-driver string Optional volume driver for the container
  124. --volumes-from list Mount volumes from the specified container(s)
  125. -w, --workdir string Working directory inside the container

 run的执行流程为:

三、docker容器命令

1.查看正在运行容器列表

 docker ps [OPTIONS]

  1. Usage: docker ps [OPTIONS]
  2. List containers
  3. Options:
  4. -a, --all Show all containers (default shows just running)
  5. -f, --filter filter Filter output based on conditions provided
  6. --format string Pretty-print containers using a Go template
  7. -n, --last int Show n last created containers (includes all states) (default -1)
  8. -l, --latest Show the latest created container (includes all states)
  9. --no-trunc Don't truncate output
  10. -q, --quiet Only display container IDs
  11. -s, --size Display total file sizes

-a 查看所有容器

docker ps -a

-n 个数 列出最近创建的容器

docker ps -n 2

-aq 显示所有运行过的容器的id 

docker ps -aq

 

 2.删除容器

rm -f 容器id 删除容器

docker rm -f 0150f4c51f21

 rm -f $(docker ps -aq) 删除所有docker容器

docker ps -aq|xargs docker rm -f 也可以删除所有的容器

docker rm -f $(docker ps -aq)
docker ps -aq|xargs docker rm -f 

3.启动容器

  start 容器id 启动容器

docker start e8sdzx524

 restart 容器id 重启容器

docker restart e8sdzx524

stop 容器id  停止容器

docker stop e8sdzx524

当使用docker stop 无法停止时,可以使用docker kill 直接杀掉 

docker kill ec8626df668c

4. 查看日志命令

docker logs [OPTIONS] CONTAINER
  1. Usage: docker logs [OPTIONS] CONTAINER
  2. Fetch the logs of a container
  3. Options:
  4. --details Show extra details provided to logs
  5. -f, --follow Follow log output
  6. --since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or
  7. relative (e.g. 42m for 42 minutes)
  8. -n, --tail string Number of lines to show from the end of the logs (default
  9. "all")
  10. -t, --timestamps Show timestamps
  11. --until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z)
  12. or relative (e.g. 42m for 42 minutes)

查看启动容器的最新num行的日志

docker logs -tf --tail num 容器id

 例如:

 docker logs -tf --tail 10 ec8626df668c

5. 查看容器的进程信息

docker top 容器id

6.重新打开一个终端的方式进入docker

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  1. Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  2. Run a command in a running container
  3. Options:
  4. -d, --detach Detached mode: run command in the background
  5. --detach-keys string Override the key sequence for detaching a container
  6. -e, --env list Set environment variables
  7. --env-file list Read in a file of environment variables
  8. -i, --interactive Keep STDIN open even if not attached
  9. --privileged Give extended privileges to the command
  10. -t, --tty Allocate a pseudo-TTY
  11. -u, --user string Username or UID (format: <name|uid>[:<group|gid>])
  12. -w, --workdir string Working directory inside the container

 7.进入容器中正在运行的终端

docker attach [OPTIONS] CONTAINER
  1. Usage: docker attach [OPTIONS] CONTAINER
  2. Attach local standard input, output, and error streams to a running container
  3. Options:
  4. --detach-keys string Override the key sequence for detaching a container
  5. --no-stdin Do not attach STDIN
  6. --sig-proxy Proxy all received signals to the process (default true)

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

docker cp 容器id:容器文件路径 本地文件路径

例如:

docker cp ec8626df668c:/opt/test.txt /opt/test.txt

很多学Python伙伴问题有没有体系的面试题?
今天为大家推荐一款刷题神奇哦 :刷题面试神器牛客
各大互联网大厂面试真题。从基础到入阶乃至原理刨析类面试题 应有尽有,赶快来装备自己吧!助你面试稳操胜券,solo全场面试官 


点关注,防走丢,如有纰漏之处,请留言指教,非常感谢

以上就是本期全部内容。我是fanstuck ,有问题大家随时留言讨论 ,我们下期见。

参阅

docker 常用命令大全

Docker Image 命令详解

Docker - Docker Image及Image命令详解

Docker----Docker容器操作常用命令

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号