Docker常用基础命令

Docker常用命令

常规帮助启动类命令

  • 启|停|重启|状态|开机自启命令
systemctl start|stop|restart|status|enable docker
  • 查看docker概要信息
docker info
  • 查看docker总体帮助文档
docker --help
  • 查看docker命令帮助文档
docker 具体命令 --help

镜像命令

docker images

  • 查看本地镜像列表
[root@TestMachine ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    9c7a54a9a43c   7 months ago   13.3kB

各选项说明:

选项名 意思
REPOSITORY 表示镜像的仓库源
TAG 镜像的标签版本号
IMAGE ID 镜像ID
CREATED 镜像创建时间
SIZE 镜像大小

​ 同意仓库源可以有多个TAG版本,代表这个仓库源的不同版本,我们使用REPOSITORY:TAG来定义不同的镜像。如果不指定一个镜像版本标签,列如你只使用hello-wold,docker将默认使用hello-world:latest镜像。

  • 参数说明
[root@TestMachine ~]# docker images --help

Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Aliases:
  docker image ls, docker image list, docker images

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Format output using a custom template:
                        'table':            Print output in table format with
                        column headers (default)
                        'table TEMPLATE':   Print output in table format using
                        the given Go template
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go
                        template.
                        Refer to https://docs.docker.com/go/formatting/ for more
                        information about formatting output with templates
      --no-trunc        Don't truncate output
  -q, --quiet           Only show image IDs

-a :列出本地所有的镜像(含历史映像层)

-q :只显示镜像ID

  • 查找某个镜像信息
[root@TestMachine ~]# docker search hello-world
NAME                                       DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
hello-world                                Hello World! (an example of minimal Dockeriz…   2152      [OK]       
rancher/hello-world                        This container image is no longer maintained…   6                    
okteto/hello-world                                                                         0                    
tacc/hello-world                                                                           0                    
armswdev/c-hello-world                     Simple hello-world C program on Alpine Linux…   0                    
tutum/hello-world                          Image to test docker deployments. Has Apache…   90                   [OK]
thomaspoignant/hello-world-rest-json       This project is a REST hello-world API to bu…   2                    
kitematic/hello-world-nginx                A light-weight nginx container that demonstr…   152                  
dockercloud/hello-world                    Hello World!                                    20                   [OK]
ansibleplaybookbundle/hello-world-apb      An APB which deploys a sample Hello World! a…   1                    [OK]
ansibleplaybookbundle/hello-world-db-apb   An APB which deploys a sample Hello World! a…   2                    [OK]
crccheck/hello-world                       Hello World web server in under 2.5 MB          20                   [OK]
strimzi/hello-world-consumer                                                               0                    
strimzi/hello-world-producer                                                               0                    
businessgeeks00/hello-world-nodejs                                                         0                    
koudaiii/hello-world                                                                       0                    
freddiedevops/hello-world-spring-boot                                                      0                    
strimzi/hello-world-streams                                                                0                    
garystafford/hello-world                   Simple hello-world Spring Boot service for t…   0                    [OK]
ppc64le/hello-world                        Hello World! (an example of minimal Dockeriz…   2                    
tsepotesting123/hello-world                                                                0                    
kevindockercompany/hello-world                                                             0                    
dandando/hello-world-dotnet                                                                0                    
vad1mo/hello-world-rest                    A simple REST Service that echoes back all t…   7                    [OK]
infrastructureascode/hello-world           A tiny "Hello World" web server with a healt…   1                    [OK]

各选项说明

选项 说明
NAME 镜像名称
DESCRIPTION 镜像说明
STARS 点赞数量
OFFICIAL 是否是官当的
OFFICIAL 是否是自动构建的
  • 参数说明
[root@TestMachine ~]# docker search --help

Usage:  docker search [OPTIONS] TERM

Search Docker Hub for images

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
      --no-trunc        Don't truncate output

查找redis点赞数前5的镜像

[root@TestMachine ~]# docker search --limit 5 redis
NAME                       DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
redis                      Redis is an open source key-value store that…   12540     [OK]       
redislabs/redisearch       Redis With the RedisSearch module pre-loaded…   61                   
redislabs/redisinsight     RedisInsight - The GUI for Redis                94                   
redis/redis-stack-server   redis-stack-server installs a Redis server w…   62                   
redis/redis-stack          redis-stack installs a Redis server with add…   85                   

docker pull

  • 下载镜像
[root@TestMachine ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    9c7a54a9a43c   7 months ago   13.3kB
[root@TestMachine ~]# docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
7b1a6ab2e44d: Pull complete 
Digest: sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest
[root@TestMachine ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    9c7a54a9a43c   7 months ago   13.3kB
ubuntu        latest    ba6acccedd29   2 years ago    72.8MB

docker pull不指定版本也是默认拉去最新的latest

  • 下载指定版本
[root@TestMachine ~]# docker pull redis:6.0.8
6.0.8: Pulling from library/redis
bb79b6b2107f: Pull complete 
1ed3521a5dcb: Pull complete 
5999b99cee8f: Pull complete 
3f806f5245c9: Pull complete 
f8a4497572b2: Pull complete 
eafe3b6b8d06: Pull complete 
Digest: sha256:21db12e5ab3cc343e9376d655e8eabbdbe5516801373e95a8a9e66010c5b8819
Status: Downloaded newer image for redis:6.0.8
docker.io/library/redis:6.0.8
[root@TestMachine ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    9c7a54a9a43c   7 months ago   13.3kB
ubuntu        latest    ba6acccedd29   2 years ago    72.8MB
redis         6.0.8     16ecd2772934   3 years ago    104MB
  • 参数说明
[root@TestMachine ~]# docker pull --help

Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Download an image from a registry

Aliases:
  docker image pull, docker pull

Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)
      --platform string         Set platform if server is multi-platform capable
  -q, --quiet                   Suppress verbose output

docker system df

查看镜像/容器/数据卷所占的空间

[root@TestMachine ~]# docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          3         1         177MB     177MB (99%)
Containers      3         0         0B        0B
Local Volumes   0         0         0B        0B
Build Cache     0         0         0B        0B

docker rmi

  • 删除某个镜像文件:docker rmi 镜像文件ID
[root@TestMachine ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    9c7a54a9a43c   7 months ago   13.3kB
ubuntu        latest    ba6acccedd29   2 years ago    72.8MB
redis         6.0.8     16ecd2772934   3 years ago    104MB
[root@TestMachine ~]# docker rmi 9c7a54a9a43c
Error response from daemon: conflict: unable to delete 9c7a54a9a43c (must be forced) - image is being used by stopped container 9d0534274667

这里提示一定要强制删除,因为该镜像正在被某个容器使用

  • 使用 -f 强制删除
[root@TestMachine ~]# docker rmi -f 9c7a54a9a43c
Untagged: hello-world:latest
Untagged: hello-world@sha256:c79d06dfdfd3d3eb04cafd0dc2bacab0992ebc243e083cabe208bac4dd7759e0
Deleted: sha256:9c7a54a9a43cca047013b82af109fe963fde787f63f9e016fdc3384500c2823d
[root@TestMachine ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    ba6acccedd29   2 years ago   72.8MB
redis        6.0.8     16ecd2772934   3 years ago   104MB
  • 删除多个镜像
docker rmi -f 镜像名1:TAG 镜像名2:TAG
  • 删除全部
docker rmi -f $(docker images -qa)

通过$(docker images -qa)返回全部镜像ID

面试题:谈谈docker虚悬镜像是什么

​ 什么是docker虚悬镜像:即仓库名、标签都是<none>的镜像,俗称虚悬镜像dangling image。一般docker在拉取镜像构建时失败的时候会出现这种情况,拉取后发现存在,删除重拉就行了

​ 具体长什么样:

image-20231211162421392

容器命令

docker run

首次运行一个容器

[root@TestMachine ~]# docker run --help

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

Create and run a new container from an image

Aliases:
  docker container run, docker run

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
      --annotation map                 Add an annotation to the container (passed
                                       through to the OCI runtime) (default map[])
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and
                                       1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight)
                                       (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker
                                       host's cgroup namespace
                                       'private': Run the container in its own
                                       private cgroup namespace
                                       '':        Use the cgroup namespace as
                                       configured by the
                                                  default-cgroupns-mode option on
                                       the daemon (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler)
                                       period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print
                                       container ID
      --detach-keys string             Override the key sequence for detaching a
                                       container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a
                                       device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a
                                       device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a
                                       device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a
                                       device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all'
                                       to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h)
                                       (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to
                                       initialize before starting health-retries
                                       countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run
                                       (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that
                                       forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1'
                                       to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to
                                       100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for
                                       unlimited)
      --platform string                Set platform if server is multi-platform
                                       capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always",
                                       "missing", "never") (default "missing")
  -q, --quiet                          Suppress the pull output
      --read-only                      Mount the container's root filesystem as
                                       read only
      --restart string                 Restart policy to apply when a container
                                       exits (default "no")
      --rm                             Automatically remove the container when it
                                       exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process
                                       (default true)
      --stop-signal string             Signal to stop the container
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format:
                                       <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

参数解释

参数 说明
--name="容器新名字" 为容器指定一个名称,如果为指定,则会随机给个名称
-d 后台运行容器并返回容器ID,也即启动守护式容器(后台运行)
-i 以交互模式运行容器,通常与-t同时使用
-t 为容器重新分配一个伪输入终端,通常与-i同时使用。二者搭配也即启功交互式容器(前台有伪终端,等待交互)
-P 随机端口映射。大写P
-p 指定端口映射。小写p
  • 前台交互式启动
docker run -it IMAGE [COMMAND] [ARG...]
  • 后台守护式启动
docker run -d IMAGE [COMMAND] [ARG...]

Docker容器后台运行,就必须有一个前台进程。容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就会自动退出。

用docker模拟一个ubuntu系统

[root@TestMachine ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    ba6acccedd29   2 years ago   72.8MB
redis        6.0.8     16ecd2772934   3 years ago   104MB
[root@TestMachine ~]# 
[root@TestMachine ~]# 
[root@TestMachine ~]# docker run -it ubuntu:latest /bin/bash
root@b6019d9ad162:/#
[root@TestMachine ~]# 
[root@TestMachine ~]# docker run -it ubuntu:latest /bin/bash
root@b6019d9ad162:/# ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 14:26 pts/0    00:00:00 /bin/bash
root          9      1  0 14:29 pts/0    00:00:00 ps -ef
root@b6019d9ad162:/# ls
bin   dev  home  lib32  libx32  mnt  proc  run   srv  tmp  var
boot  etc  lib   lib64  media   opt  root  sbin  sys  usr
root@b6019d9ad162:/# 
  • b6019d9ad162:为容器ID
  • /bin/bash:表示交互式容器内执行的命令。exit退出终端

docker ps

列出所有正常运行的容器实例

[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS         PORTS     NAMES
b6019d9ad162   ubuntu:latest   "/bin/bash"   5 minutes ago   Up 5 minutes             epic_jang

选项意思

选项 解释
CONTAINER ID 容器实例ID
IMAGE 镜像名
COMMAND 执行的命令
CREATED 创建时间
STATUS 运行状态
PORTS 端口。当前没有
NAMES 容器名称。未指定的会随机生成

启动一个带名称的容器

[root@TestMachine ~]# docker run -it --name=myu1 ubuntu bash
root@f0aa44e29730:/# 

再开一个终端窗口,查看状态

[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE           COMMAND       CREATED              STATUS              PORTS     NAMES
f0aa44e29730   ubuntu          "bash"        About a minute ago   Up About a minute             myu1
b6019d9ad162   ubuntu:latest   "/bin/bash"   15 minutes ago       Up 15 minutes                 epic_jang
  • 参数说明
[root@TestMachine ~]# docker ps --help

Usage:  docker ps [OPTIONS]

List containers

Aliases:
  docker container ls, docker container list, docker container ps, docker ps

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Format output using a custom template:
                        'table':            Print output in table format with
                        column headers (default)
                        'table TEMPLATE':   Print output in table format using
                        the given Go template
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go
                        template.
                        Refer to https://docs.docker.com/go/formatting/ for more
                        information about formatting output with templates
  -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

-a:列出当前所有正在运行的容器 + 历史上运行过

-i:显示最近创建的容器

-n:显示最近n个创建的容器

-q:静默模式,只显示容器编号

退出容器

  • exit:退出并终止容器
  • ctrl + p + q:退出容器,但不终止容器运行

进出容器

  1. 后台运行redis容器
docker run -d redis:6.0.8
  1. 查看当前运行的容器有哪些
[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED         STATUS         PORTS      NAMES
ff8b851cb33e   redis:6.0.8   "docker-entrypoint.s…"   2 minutes ago   Up 2 minutes   6379/tcp   keen_gould

思考:为什么这里后台运行了redis,但没有终止,而后台运行ubunu、centos这类容器,如果没有执行挂起命令就会立马终止。

  1. 进入容器

语法:docker exec -it 容器ID bashShell

[root@TestMachine ~]# docker exec -it ff8b851cb33e /bin/bash
root@ff8b851cb33e:/data#
  1. 退出容器

这里通过exit退出容器

root@ff8b851cb33e:/data# exit 
exit
  1. 查看当前运行容器的状态
[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED         STATUS         PORTS      NAMES
ff8b851cb33e   redis:6.0.8   "docker-entrypoint.s…"   3 minutes ago   Up 3 minutes   6379/tcp   keen_gould
  1. 再次进入容器

进入容器docker提供了两种方法,这里使用attach方法

[root@TestMachine ~]# docker attach ef2f039f8d5d

此时会发现什么也没有,因为attach会进入容器正在执行的终端,这里重新创建一个ubuntu容器,注意观察变化

[root@TestMachine ~]# docker run -it ubuntu /bin/bash
root@9221d499fc83:/# [root@TestMachine ~]# 
[root@TestMachine ~]# 
[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
9221d499fc83   ubuntu    "/bin/bash"   5 seconds ago   Up 4 seconds             hopeful_robinson
[root@TestMachine ~]# 
[root@TestMachine ~]# docker attach 9221d499fc83
root@9221d499fc83:/# exit
exit
[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@TestMachine ~]#
  • 总结

attach直接进入容器启动命令终端,不会启动新进程,用exit退出,会导致容器的终止

exec是在容器中打开新的终端,并且可以启动新的进程,用exit退出时,不会导致容器的停止

容器启|重启|停|强制停|删

docker start|restart|stop|kill|rm 容器ID或容器名字
  • start:启动已停止运行的容器
  • restart:重启容器
  • stop:停止容器
  • kill:强制停止容器
  • rm:删除已停止容器。注意:rmi是删除镜像,rm是删除容器,同rmi一样,后接 -f 表示强制删除

删除多个容器

docker rm -f $(docker ps -a -q)
docker ps -a -q | xargs docker rm

查看容器日志

docler logs 容器id/容器名字

具体命令:

[root@TestMachine ~]# docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Aliases:
  docker container logs, docker logs

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:37Z") or
                       relative (e.g. "42m" for 42 minutes)
  -n, --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:37Z")
                       or relative (e.g. "42m" for 42 minutes)

查看容器内部运行的进程

docker top 容器id/容器名字

查看容器内部细节

docker inspect 容器id/容器名字

将容器的数据拷贝到主机上

语法:docker cp 容器ID:容器文件路径 主机路径

root@dadd750d2430:/# cd tmp/ 
root@dadd750d2430:/tmp# ll
total 0
drwxrwxrwt 2 root root 6 Oct  6  2021 ./
drwxr-xr-x 1 root root 6 Dec 25 12:37 ../
root@dadd750d2430:/tmp# touch test.txt
root@dadd750d2430:/tmp# ll
total 0
drwxrwxrwt 1 root root 22 Dec 25 12:38 ./
drwxr-xr-x 1 root root 17 Dec 25 12:37 ../
-rw-r--r-- 1 root root  0 Dec 25 12:38 test.txt
root@dadd750d2430:/tmp# [root@TestMachine ~]# 
[root@TestMachine ~]# 
[root@TestMachine ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
dadd750d2430   ubuntu    "/bin/bash"   2 minutes ago   Up 2 minutes             wonderful_grothendieck
[root@TestMachine ~]# docker cp dadd750d2430:/tmp/test.txt /
                                               Successfully copied 1.54kB to /
[root@TestMachine ~]# ll
total 3444
-rw-------. 1 root root    2757 Nov 21 11:37 anaconda-ks.cfg
-rw-r--r--. 1 root root   26024 Apr 25  2019 mysql80-community-release-el7-3.noarch.rpm
-rw-------. 1 root root    2037 Nov 21 11:37 original-ks.cfg
drwxrwxr-x. 8 pzb  pzb     4096 Nov  1 20:38 redis-stable
-rw-r--r--. 1 root root 3477620 Nov  1 20:40 redis-stable.tar.gz
-rw-r--r--. 1 root root       7 Dec  6 22:07 test.txt
[root@TestMachine ~]# 

反之从主机导到容器

容器的导入导出

  • 导出容器

export导出容器的内容留作为一个tar归档文件 [对应import命令]

docker export 容器ID > 文件名.tar
  • 导入容器

import从tar包中的内容创建一个新的文件系统再导入为镜像 [对应export]

cat 文件名.tar | docker import - 镜像用户/镜像名:镜像版本号

导入导出场景案例:备份容器|容器发生误删情况

  1. 备份容器
[root@TestMachine ~]# docker export dadd750d2430 > ubuntuImage.tar
[root@TestMachine ~]# ll
total 76844
-rw-------. 1 root root     2757 Nov 21 11:37 anaconda-ks.cfg
-rw-r--r--. 1 root root    26024 Apr 25  2019 mysql80-community-release-el7-3.noarch.rpm
-rw-------. 1 root root     2037 Nov 21 11:37 original-ks.cfg
drwxrwxr-x. 8 pzb  pzb      4096 Nov  1 20:38 redis-stable
-rw-r--r--. 1 root root  3477620 Nov  1 20:40 redis-stable.tar.gz
-rw-r--r--  1 root root        0 Dec 25 21:14 test2.txt
-rw-r--r--. 1 root root        7 Dec  6 22:07 test.txt
-rw-r--r--  1 root root 75158528 Dec 25 21:19 ubuntuImage.tar
  1. 容器被人强制删除,里面数据很重要
[root@TestMachine ~]# docker rm -f dadd750d2430
dadd750d2430
[root@TestMachine ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    ba6acccedd29   2 years ago   72.8MB
redis        6.0.8     16ecd2772934   3 years ago   104MB
  1. 将备份的容器导入到镜像中
[root@TestMachine ~]# cat ubuntuImage.tar | docker import - zb/ubuntu:1.0.0
sha256:de55d722c8adbc6990bdc479ce154fb0ef1ed7e31567410f5afc48472074e4ca
[root@TestMachine ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
zb/ubuntu    1.0.0     de55d722c8ad   5 seconds ago   72.8MB
ubuntu       latest    ba6acccedd29   2 years ago     72.8MB
redis        6.0.8     16ecd2772934   3 years ago     104MB
  1. 验证容器内的数据是否还存在
[root@TestMachine ~]# docker run -it zb/ubuntu:1.0.0 /bin/bash
root@bdc04fc48b66:/# cd tmp/
root@bdc04fc48b66:/tmp# ll
total 0
drwxrwxrwt 2 root root 39 Dec 25 13:15 ./
drwxr-xr-x 1 root root  6 Dec 25 13:30 ../
-rw-r--r-- 1 root root  0 Dec 25 12:38 test.txt
-rw-r--r-- 1 root root  0 Dec 25 13:14 test2.txt
root@bdc04fc48b66:/tmp# 
posted @ 2023-12-25 21:35  MrSponge  Views(102)  Comments(0Edit  收藏  举报