docker基础

一、安装运行

官网

https://docs.docker.com/engine/install/centos/#install-using-the-repository

1.安装yum环境

yum -y install gcc
yum -y install gcc-c++

安装utils

sudo yum install -y yum-utils

2.配置yum源

--国外 docker 的 yum 源(不使用)

sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

配置国内 docker 的 yum 源(阿里云)

yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

yum makecache fast

3.安装docker

这里建议使用25.0.5版本,本文演示用最新版

最新版:

yum install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

指定版本

注意,最新版v26版安装protainer后,在使用上会有些许问题,比如进入容器控制台页面会出错,这里建议降低版本,比如docker25.0.5版本:

yum install docker-ce-25.0.5 docker-ce-cli-25.0.5 containerd.io-1.6.20 docker-buildx-plugin-0.9.1 docker-compose-plugin-2.16.0

4.启动

systemctl start docker

查看启动状态:

ps -ef|grep docker

显示如下启动成功

root       3587      1  4 20:17 ?        00:00:01 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

root       3787   3157  0 20:17 pts/0    00:00:00 grep --color=auto docker

查看版本:

docker version

如下代表成功

Client: Docker Engine - Community
 Version:           26.0.0
 API version:       1.45
 Go version:        go1.21.8
 Git commit:        2ae903e
 Built:             Wed Mar 20 15:21:09 2024
 OS/Arch:           linux/amd64
 Context:           default

Server: Docker Engine - Community
 Engine:
  Version:          26.0.0
  API version:      1.45 (minimum version 1.24)
  Go version:       go1.21.8
  Git commit:       8b79278
  Built:            Wed Mar 20 15:20:06 2024
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.28
  GitCommit:        ae07eda36dd25f8a1b98dfbf587313b99c0190bb
 runc:
  Version:          1.1.12
  GitCommit:        v1.1.12-0-g51d5e94
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

5.运行镜像

sudo docker run hello-world

显示如下:

因为本地不存在hello-world镜像,无法作为容器实例运行,所以会去远程库拉取,拉到本地后形成容器实例运行

[root@localhost ~]# docker run hello-world
Unable to find image 'hello-world:latest' locally  --本地没有
latest: Pulling from library/hello-world           --远程拉取
c1ec31eb5944: Pull complete 
Digest: sha256:53641cd209a4fecfc68e21a99871ce8c6920b2e7502df0a20671c6fccc73a7c6
Status: Downloaded newer image for hello-world:latest    --拉取完成

Hello from Docker!                              --运行成功
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

6.卸载

停止docker

systemctl stop docker

运行命令如果出现:

Warning: Stopping docker.service, but it can still be activated by:
  docker.socket

这是因为除了docker.service单元文件外,还有一个docker.socket单元文件...这是用来激活socket的。这个警告意味着如果你在docker服务没有运行的情况下尝试连接docker套接字,那么systemd会自动为你启动docker。

解决:

执行

systemctl stop docker.socket

然后再

systemctl stop docker

在移除相关文件

yum remove docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-ce-rootless-extras

rm -rf /var/lib/docker
rm -rf /var/lib/containerd

二、使用

1.镜像加速器

加速器地址获取网址:

https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors

然后在服务器中执行以下命令

  • 创建文件夹

    shell 复制代码
    mkdir -p /etc/docker
  • 粘贴json串

    shell 复制代码
    tee /etc/docker/daemon.json <<-'EOF'
    {
      "registry-mirrors": ["https://wshy6f04.mirror.aliyuncs.com"]
    }
    EOF
  • 重新加载

    shell 复制代码
    systemctl daemon-reload
  • 重启docker

    shell 复制代码
    systemctl restart docker

2.帮助启动类命令

3.镜像命令

3.1 列出可运行的镜像
shell 复制代码
docker images

运行结果:

shell 复制代码
[root@localhost ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    d2c94e258dcb   11 months ago   13.3kB

TAG为latest时,代表最新版本

3.2 按名字搜索某镜像

从远程仓库按名字搜索

docker search 镜像名字

比如:

docker search hello-world

执行结果:

表头参数说明:

一般情况下就选第一个,OFFICIAL为ok的官方版

如果想只看前几个,而不是列出很多,可以结合limit命令使用

比如,搜索排名前5的redis

docker search --limit 5 redis
3.3 下载镜像

docker pull 镜像名称

先去search查,查得到就pull:

docker pull hello-world

如下,Using default tag: latest代表没有指定版本使用默认最新版本,然后会卡在这里下载一会:

shell 复制代码
[root@localhost ~]# docker pull hello-world
Using default tag: latest

完成后显示如下:

shell 复制代码
[root@localhost ~]# docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
2db29710123e: Pull complete 
Digest: sha256:2498fce14358aa50ead0cc6c19990fc6ff866ce72aeb5546e1d59caac3d0d60f
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest

或者可以指定版本

docker pull 镜像名称:TAG

shell 复制代码
docker pull redis:6.0.8
3.4 查看镜像/容器/数据卷所占用的空间

docker system df

shell 复制代码
[root@localhost ~]# docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          1         0         13.26kB   13.26kB (100%)
Containers      0         0         0B        0B
Local Volumes   0         0         0B        0B
Build Cache     0         0         0B        0B

TYPE:

  • Images --镜像
  • Containers --容器
  • Local Volumes --本地卷
  • Build Cache --占用缓存

TOTAL: 代表各类型的总数

**ACTIVE:**活动数,即处于活动中的有几个

**SIZE:**占用大小

RECLAIMABLE:

3.5 停止及删除镜像

停止

docker stop [镜像ID]

删除单个

docker rmi [镜像ID]

如下:

[root@localhost ~]# docker rmi d2c94e258dcb
Error response from daemon: conflict: unable to delete d2c94e258dcb (must be forced) - image is being used by stopped container 6ab4781e77d6

如出现上面报错,需要先执行docker rm [上面container后面的id]

[root@localhost ~]# docker rm 6ab4781e77d6
6ab4781e77d6

然后再docker rmi,如下即为成功:

[root@localhost ~]# docker rmi d2c94e258dcb
Untagged: hello-world:latest
Untagged: hello-world@sha256:53641cd209a4fecfc68e21a99871ce8c6920b2e7502df0a20671c6fccc73a7c6
Deleted: sha256:d2c94e258dcb3c5ac2798d32e1249e42ef01cba4841c2234249495f87264ac5a
Deleted: sha256:ac28800ec8bb38d5c35b49d45a6ac4777544941199075dff8c4eb63e093aa81e

如果还是报上面的错,但是container后的id不同,就多执行几次docker rm,直到rmi成功

强制删除

如果不想执行docker rmi,可以使用强制删除:

shell 复制代码
docker rmi -f 镜像id

删除多个

多个id间空格隔开

docker rmi 镜像ID 镜像ID 镜像ID

或者

docker rmi 镜像ID:TAG 镜像ID:TAG 镜像ID:TAG

删除全部

先用

docker images -qa

可以查到所有的镜像id,然后执行:

docker rmi -f $(docker images -qa)

相当于删除所有镜像

三、容器实例运行及命令

1.运行容器

通过镜像生成容器实例并运行

docker run 镜像名run就是以一个镜像创建一个容器实例并运行

docker run -it 镜像名:以一个镜像创建一个容器实例运行,通过-it与这个实例进行交互

比如:

docker run -it ubuntu /bin/bash

在这个命令中,-it 表示以交互式和伪终端的方式运行容器,ubuntu 是要启动的容器镜像,/bin/bash 是容器启动后要执行的命令。

因为要操作ubuntu,所以使用/bin/bash 来运行ubuntu的shell终端

虚拟机终端内执行上面命令后

这里就是在centos7 中的docker 中又运行了一个虚拟机ubuntu ,蓝色框就是通过命令操作ubuntu ,即在一个虚拟机中通过docker 操作另一个虚拟机。5f21c95268a4就是运行的容器实例id,然后可以在ubuntu中运行linux命令,如下:

当你使用 docker run 命令创建和启动一个容器时,你可以提供不同的选项和参数来满足你的需求。以下是一些常用的选项和参数:

  • -d:以后台模式(detached mode)运行容器,使容器在后台持续运行。
  • -it:同时开启交互式终端和分配一个伪终端(pseudo-TTY),允许你与容器进行交互。
  • --name:为容器指定一个名称,以便于识别和操作容器。
  • -p:将容器内的端口映射到主机上的端口,允许从主机上访问容器内的服务。
  • -v:将主机上的目录或文件挂载到容器内,实现主机和容器之间的文件共享。
  • --privileged=true:赋予容器特权,提供更高的权限和访问能力。
  • --rm:在容器退出后自动删除容器。这可以避免容器占用过多的磁盘空间。

除了上述选项和参数之外,你还可以在 docker run 命令的末尾提供要在容器内执行的命令。这可以是具体的可执行程序、脚本或者是容器内部的命令。

例如,你可以使用以下命令在容器内运行一个简单的 Python 脚本:

shell 复制代码
docker run python:3.9 python -c "print('Hello, Docker!')"

在上述命令中,python:3.9 是要使用的镜像名称,python -c "print('Hello, Docker!')" 是要在容器内执行的命令。

通过使用不同的选项、参数和命令,你可以根据自己的需求和场景,创建和定制适合的容器。Docker 提供了丰富的功能和灵活性,使你能够方便地构建、部署和管理容器化的应用程序。

2.查看运行的容器实例

查看正在运行的实例:

docker ps

接上面的ubuntu,运行docker ps命令:

shell 复制代码
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
5f21c95268a4   ubuntu    "/bin/bash"   10 minutes ago   Up 10 minutes             agitated_wozniak
  • CONTAINER ID:容器实例id,这里发现其与上面的id相同
  • IMAGE:镜像名
  • COMMAND:运行的命令
  • CREATED:创建时间
  • STATUS:状态,这里是运行了10分钟
  • PORTS:端口号,ubuntu不需要端口映射,所以这里没有
  • NAMES:系统随机生成的实例名

查看正在运行的,及历史上运行过的

docker ps -a

运行结果:

shell 复制代码
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED        STATUS                      PORTS     NAMES
2ad230ad82cb   ubuntu    "/bin/bash"               22 hours ago   Exited (129) 22 hours ago             iubuntu01
b110447a025a   bash      "docker-entrypoint.s..."   22 hours ago   Exited (129) 22 hours ago             myubuntu01
5f21c95268a4   ubuntu    "/bin/bash"               22 hours ago   Exited (129) 22 hours ago             agitated_wozniak

显示最近创建的容器实例

docker ps -l

结果:

shell 复制代码
[root@localhost ~]# docker ps -l
CONTAINER ID   IMAGE     COMMAND       CREATED        STATUS                      PORTS     NAMES
2ad230ad82cb   ubuntu    "/bin/bash"   22 hours ago   Exited (129) 22 hours ago             iubuntu01

显示最近创建的n个容器实例

docker ps -n 1

结果:

shell 复制代码
[root@localhost ~]# docker ps -n 1
CONTAINER ID   IMAGE     COMMAND       CREATED        STATUS                      PORTS     NAMES
2ad230ad82cb   ubuntu    "/bin/bash"   22 hours ago   Exited (129) 22 hours ago             iubuntu01

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

docker ps -q

结果:

shell 复制代码
[root@localhost ~]# docker ps -q
88ef133b98bf

如果想要自己定义运行实例的名字。可以:

shell 复制代码
docker run -it --name=iubuntu01 ubuntu /bin/bash

这里会再运行一个叫iubuntu01的ubuntu实例,与上面的agitated_wozniak是两个不同的运行中实例

shell 复制代码
[root@localhost ~]# docker run -it --name=iubuntu01 ubuntu /bin/bash
root@2ad230ad82cb:/# 

此时再打开一个终端运行docker ps

shell 复制代码
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS              PORTS     NAMES
2ad230ad82cb   ubuntu    "/bin/bash"   About a minute ago   Up About a minute             iubuntu01
5f21c95268a4   ubuntu    "/bin/bash"   23 minutes ago       Up 23 minutes                 agitated_wozniak
[root@localhost ~]# 

发现多了自定义的ubuntu实例iubuntu01

3.帮助命令

 docker run --help

可以查看docker run可运行的命令

shell 复制代码
[root@localhost ~]# 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-interval duration   Time between running the check during
                                         the start period (ms|s|m|h) (default 0s)
      --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

4.退出、返回正在运行的容器

直接exit即可,通过run命令运行的容器实例,在里面执行exit后,则会推出至外面的命令行

shell 复制代码
[root@localhost ~]# docker run -it ubuntu
root@88ef133b98bf:/# exit
exit
[root@localhost ~]# 

run命令运行的容器,在执行exit后,容器会停止运行

docker ps查看,已没有运行的容器实例:

shell 复制代码
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# 

按下键盘ctrl+q+p,则不会停止容器跳出

按下后,root@实例id后会出现[root@localhost ~]

shell 复制代码
[root@localhost ~]# docker run -it ubuntu
root@69f9a0406917:/# [root@localhost ~]# 

再执行docker ps,发现容器没有停止

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS          PORTS     NAMES
69f9a0406917   ubuntu    "bash"    44 seconds ago   Up 42 seconds             upbeat_roentgen

如果想要切换回去,执行下面两个命令:

docker attach [容器ID或容器名称]
或
docker exec -it [容器ID或容器名称] [命令]

运行效果,推荐使用容器id:

shell 复制代码
[root@localhost ~]# docker attach 69f9a0406917
root@69f9a0406917:/# 
shell 复制代码
[root@localhost ~]# docker exec -it 69f9a0406917 /bin/bash
root@69f9a0406917:/# 

二者区别:

  • attach会直接进入容器已启动的终端,不会启动新的线程,如果执行exit退出,会关闭容器
  • exec是在容器中打开新的终端,会启动新的线程,如果执行exit退出,不会关闭容器

一般都使用exec

5.启动已停止的容器

docker start 容器id或容器名

先查出最近运行过的容器,再启动:

shell 复制代码
[root@localhost ~]# docker ps -l
CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS                     PORTS     NAMES
69f9a0406917   ubuntu    "bash"    13 minutes ago   Exited (0) 7 minutes ago             upbeat_roentgen
[root@localhost ~]# docker start 69f9a0406917
69f9a0406917
[root@localhost ~]# 

6.重启容器

docker restart 容器id或容器名

7.停止容器

docker stop 容器id或容器名

8.强制停止容器

docker kill 容器id或容器名

9.删除已停止的容器

docker rm 容器id或容器名

需要先停止,否则会出现如下错误:

shell 复制代码
[root@localhost ~]# docker rm 69f9a0406917
Error response from daemon: cannot remove container "/upbeat_roentgen": container is running: stop the container before removing or force remove

然后执行停止,再rm,最后查看,已没有运行实例:

shell 复制代码
[root@localhost ~]# docker stop 69f9a0406917
69f9a0406917
[root@localhost ~]# docker rm 69f9a0406917
69f9a0406917
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

如果容器即便运行,也要删除,可以执行强制删除命令

docker rm -f 容器id或容器名

或者删除所有(危险不执行):

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

10.后台运行容器

即不显示交互界面。但是,docker容器后台运行,就必须有一个前台进程,所以有些应用,就必须以docker run -it来运行,比如ubuntu

命令:

docker run -d 镜像名

比如 docker run -d redis,运行结果:

shell 复制代码
[root@localhost ~]# docker run -d redis
92fc46d1eee90839834c8b29cb16113097d4d3eeb7047cafe11df48d1692967f
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS         PORTS      NAMES
92fc46d1eee9   redis     "docker-entrypoint.s..."   5 seconds ago   Up 3 seconds   6379/tcp   musing_jang

11.查看容器日志

docker logs 容器实例id

这里用上面的redis查看:

docker logs 92fc46d1eee9

运行结果:

shell 复制代码
[root@localhost ~]# docker logs 92fc46d1eee9
1:C 05 Apr 2024 11:23:22.192 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 05 Apr 2024 11:23:22.192 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 05 Apr 2024 11:23:22.192 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
1:M 05 Apr 2024 11:23:22.193 * monotonic clock: POSIX clock_gettime
1:M 05 Apr 2024 11:23:22.196 * Running mode=standalone, port=6379.
1:M 05 Apr 2024 11:23:22.196 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
1:M 05 Apr 2024 11:23:22.196 # Server initialized
1:M 05 Apr 2024 11:23:22.196 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
1:M 05 Apr 2024 11:23:22.197 * Ready to accept connections

12.查看容器内运行的进程

docker top 容器实例id

shell 复制代码
[root@localhost ~]# docker top 92fc46d1eee9
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
polkitd             3322                3302                0                   19:23               ?                   00:00:02            redis-server *:6379
[root@localhost ~]# 

13.查看容器内部细节

docker inspect 容器实例id

docker inspect 92fc46d1eee9

还是以第10步的redis为例:

下面包含了redis的一些运行参数,包括状态State、网络Networks等

shell 复制代码
[root@localhost ~]# docker inspect 92fc46d1eee9
[
    {
        "Id": "92fc46d1eee90839834c8b29cb16113097d4d3eeb7047cafe11df48d1692967f",
        "Created": "2024-04-05T11:23:21.139837716Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "redis-server"
        ],
        "State": {
            "Status": "running",
            "Running": true,
			........................................
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:02",
                    "NetworkID": "08769e1f3c84ab05b46380483a8cf1b7531bea1293d9555bc2f2d0b56419c855",
                    "EndpointID": "6f92d6cf944346df1d715e4a1c9f2274e5791e57f47421c9effcc98e2c6096de",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DriverOpts": null,
                    "DNSNames": null
                }
            }
        }
    }
]

14.切入到正在运行的某容器

参见第4个标题,推荐使用exec

docker exec -it [容器ID] [命令]

这里还是以第10个标题的redis为例(这里不加 /bin/bash 会出问题,先记录):

shell 复制代码
[root@localhost ~]# docker exec -it 92fc46d1eee9 /bin/bash
root@92fc46d1eee9:/data# redis-cli -p 6379
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> 

使用exec,再退出redis后,执行ps发现其依旧在运行状态

shell 复制代码
[root@localhost ~]# docker exec -it 92fc46d1eee9 /bin/bash
root@92fc46d1eee9:/data# redis-cli -p 6379
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> exit
root@92fc46d1eee9:/data# exit
exit
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED          STATUS          PORTS      NAMES
92fc46d1eee9   redis     "docker-entrypoint.s..."   36 minutes ago   Up 36 minutes   6379/tcp   musing_jang

15.复制容器内文件到主机

docker cp 容器id:容器内路径 目的主机路径

通过容器id进入Ubuntu中,并在临时目录tmp中创建一个a.txt:

shell 复制代码
[root@localhost ~]# docker exec -it c47b98bc8275 /bin/bash
root@c47b98bc8275:/# pwd
/
root@c47b98bc8275:/# cd /tmp
root@c47b98bc8275:/tmp# touch a.txt
root@c47b98bc8275:/tmp# ll
total 0
drwxrwxrwt. 1 root root 19 Apr  5 12:09 ./
drwxr-xr-x. 1 root root 29 Apr  5 12:03 ../
-rw-r--r--. 1 root root  0 Apr  5 12:09 a.txt
root@c47b98bc8275:/tmp# 

执行:

docker cp c47b98bc8275:/tmp/a.txt /tmp

结果(记得退出ubuntu终端在外面执行):可以看到本机的/tmp下多了一个a.txt

root@c47b98bc8275:/tmp# exit
exit
[root@localhost ~]# docker cp c47b98bc8275:/tmp/a.txt /tmp
Successfully copied 1.54kB to /tmp
[root@localhost ~]# cd /tmp
[root@localhost tmp]# ll
总用量 880
-rw-r--r--. 1 root root      0 4月   5 20:09 a.txt
drwx------. 2 root root     24 4月   5 19:05 ssh-Iu7aXwuozIDi
drwx------. 3 root root     17 4月   5 19:05 systemd-private-da3cf3129e8c43cba10ba9b367aca03a-bolt.service-EzWQsQ
..................省略

[root@localhost tmp]# 

16.导入导出容器

导出

导出,导出的是整个容器,导出为tar文件

docker export 容器实例id > tar文件名

先查看有哪些运行的容器:docker ps

shell 复制代码
[root@localhost tmp]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED             STATUS             PORTS      NAMES

c47b98bc8275   ubuntu    "bash"                    20 minutes ago      Up 20 minutes                 practical_bardeen

92fc46d1eee9   redis     "docker-entrypoint.s..."   About an hour ago   Up About an hour   6379/tcp   musing_jang

这里使用较小的ubuntu做示例,执行导出命令:

docker export c47b98bc8275 > ubuntu.tar

默认就是生成在执行命令所在的文件夹内:

shell 复制代码
[root@localhost tmp]# docker export c47b98bc8275 > ubuntu.tar
[root@localhost tmp]# ls -l
总用量 74280
-rw-r--r--. 1 root root        0 4月   5 20:09 a.txt
-rw-r--r--. 1 root root 75159040 4月   5 20:27 ubuntu.tar

想要生成在其他位置,在tar前加路径即可

docker export 容器实例id > /路径/tar文件名

比如:

shell 复制代码
[root@localhost tmp]# docker export c47b98bc8275 > /ubuntu.tar
[root@localhost tmp]# cd ..
[root@localhost /]# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp         usr
boot  etc  lib   media  opt  root  sbin  sys  ubuntu.tar  var
[root@localhost /]# 

可以看到直接生成在根目录下了。

导入

将导出的tar文件导入到docker,tar会变为一个新的镜像

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

为了演示,先将已有的ubuntu删除,这里直接强制删除(先删容器再删镜像),最后docker images确认不存在ubuntu:

shell 复制代码
[root@localhost /]# docker rm -f c47b98bc8275
c47b98bc8275
[root@localhost /]# docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED             STATUS             PORTS      NAMES
92fc46d1eee9   redis     "docker-entrypoint.s..."   About an hour ago   Up About an hour   6379/tcp   musing_jang
[root@localhost tmp]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
ubuntu       latest    4fb714199360   3 minutes ago   72.8MB
redis        latest    7614ae9453d1   2 years ago     113MB
bash         latest    6a03c8e7e2be   2 years ago     12.9MB
[root@localhost tmp]# docker rmi -f  4fb714199360
Untagged: ubuntu:latest
Untagged: ubuntu@sha256:876600f8a1ce04df27722f482ebfe6696aa4fec6a61a7ea2cf6d5045a63c5d9a
Deleted: sha256:6a03c8e7e2be03e010d21a78c56090566e418e6957a97e5b8906b0c8df7d4e5b
[root@localhost tmp]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
redis        latest    7614ae9453d1   2 years ago   113MB

然后执行导入,images查看ubuntu又有了:

cat ubuntu.tar | docker import - ubuntu

shell 复制代码
[root@localhost tmp]# cat ubuntu.tar | docker import - ubuntu
sha256:efb62633a1736869689bd8e58680e01100895a74ed96b07ff0ca9daf5ddbffdb
[root@localhost tmp]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
ubuntu       latest    efb62633a173   8 seconds ago   72.8MB
redis        latest    7614ae9453d1   2 years ago     113MB

这里运行导入的镜像实例,发现之前创建的a.txt文件也在:

shell 复制代码
[root@localhost tmp]# docker run -it ubuntu
docker: Error response from daemon: no command specified.
See 'docker run --help'.
[root@localhost tmp]# docker run -it ubuntu /bin/bash
root@c845a23bcccd:/# cd /tmp
root@c845a23bcccd:/tmp# ls
a.txt
root@c845a23bcccd:/tmp# exit
exit
[root@localhost tmp]# 

17.端口映射

将docker实例的运行端口映射到宿主机(服务器)上,用于访问服务器的请求可以访问到docker实例上

四、镜像

1.原理

镜像是打包好的软件运行环境,而且镜像是分层的

Docker镜像加载原理

2.操作

1.提交

docker commit -m="提交的信息" -a="作者" 容器id 要创建的镜像名:[版本号]

docker commit 提交容器副本使之成为一个新的镜像

运行ubuntu,然后尝试编辑a.txt文件。发现vim命令是不存在的,这里为ubuntu添加vim功能并提交

shell 复制代码
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    efb62633a173   3 days ago    72.8MB
redis        latest    7614ae9453d1   2 years ago   113MB
[root@localhost ~]# docker run -it ubuntu /bin/bash
root@037879a362cf:/# pwd
/
root@037879a362cf:/# cd /tmp
root@037879a362cf:/tmp# ls
a.txt
root@037879a362cf:/tmp# vim a.txt 
bash: vim: command not found
root@037879a362cf:/tmp# 

然后为ubuntu安装vim,先使用**apt-get update更新包管理工具**

shell 复制代码
root@037879a362cf:/tmp# apt-get update
Get:1 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
Get:2 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 Packages [29.8 kB]
Get:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:5 http://security.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [3483 kB]
Get:6 http://archive.ubuntu.com/ubuntu focal-backports InRelease [108 kB]
Get:7 http://archive.ubuntu.com/ubuntu focal/multiverse amd64 Packages [177 kB]
Get:8 http://archive.ubuntu.com/ubuntu focal/restricted amd64 Packages [33.4 kB]
Get:9 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages [11.3 MB]        
Get:10 http://security.ubuntu.com/ubuntu focal-security/universe amd64 Packages [1194 kB]
Get:11 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [3546 kB] 
Get:12 http://archive.ubuntu.com/ubuntu focal/main amd64 Packages [1275 kB]           
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [4021 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 Packages [32.5 kB]
Get:15 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [3634 kB]
Get:16 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [1489 kB]
Get:17 http://archive.ubuntu.com/ubuntu focal-backports/universe amd64 Packages [28.6 kB]
Get:18 http://archive.ubuntu.com/ubuntu focal-backports/main amd64 Packages [55.2 kB] 
Fetched 30.9 MB in 8s (4119 kB/s)                                                     
Reading package lists... Done
root@037879a362cf:/tmp# 

再使用apt-get -y install vim安装vim

shell 复制代码
root@037879a362cf:/tmp# apt-get -y install vim
Reading package lists... Done
Building dependency tree       
Reading state information... Done
................. 中间省略
update-alternatives: warning: skip creation of /usr/share/man/man1/editor.1.gz because associated file /usr/share/man/man1/vim.1.gz (of link group editor) doesn't exist
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...

再执行vim a.txt时,发现可以编辑,输入自定义信息,然后按esc,输入:wq保存退出即可

shell 复制代码
root@037879a362cf:/tmp# vim a.txt
shell 复制代码
this is docker
~                                                                                      
~                                                                                      
~                                                                                                                                                                     
:wq

cat查看

shell 复制代码
root@037879a362cf:/tmp# cat a.txt
this is docker
root@037879a362cf:/tmp# 

接下来提交带有vim的ubuntu镜像

docker commit -m="提交的信息" -a="作者" 容器id 要创建的镜像名:[版本号]

将上一步的ubuntu容器id复制下来,版本自定义:

docker commit -m="vim add" -a="wzy" 037879a362cf wzyubt:1.0

提交成功后返回sha256码,通过命令查看已存在wzyubt新镜像:

shell 复制代码
[root@localhost ~]# docker commit -m="vim add" -a="wzy" 037879a362cf wzyubt:1.0
sha256:67785ab852930f3fedde0beb78cca45203eb5d0a37570bcd80dc5e7103c8e6aa
[root@localhost ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
wzyubt       1.0       67785ab85293   8 seconds ago   191MB
ubuntu       latest    efb62633a173   3 days ago      72.8MB
redis        latest    7614ae9453d1   2 years ago     113MB
[root@localhost ~]# 

这样,就生成了一个带有vim功能的新ubuntu镜像

2.发布镜像到阿里云

将上一步的镜像发布到阿里云。

进入阿里云,登陆后进入控制台,搜索镜像,点击容器镜像服务ACR

然后进入个人实例,没有的话点添加,个人版免费,然后先创建命名空间,再建镜像仓库,建仓库填完信息后选本地仓库

点击上面的仓库名,进入如下页面,然后执行第3步

第一条命令:登陆阿里云

docker login --username=你的用户名 registry.cn-hangzhou.aliyuncs.com

出现下面结果即为登陆成功:

[root@localhost ~]# docker login --username=*** registry.cn-hangzhou.aliyuncs.com
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

第二条命令:提交

docker tag 镜像id registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号

不出现报错即为成功

第三条命令:推送

docker push registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号

出现下面结果即为登陆成功:

[root@localhost ~]# docker push registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号
The push refers to repository [registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号]
b68a178733cd: Pushed 
afbdb0332390: Pushed 
1.0: digest: sha256:bba124b943dbc671204676513deae8888a301e3d11364fb690256e4e124422e3 size: 741
[root@localhost ~]# 
3.从阿里云下载镜像

从个人实例仓库页面中,找到从Registry中拉取镜像的命令

$ docker pull registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号

运行结果如下即为成功:

[root@localhost ~]# docker pull registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号
1.0: Pulling from /你的命名空间/你的仓库
8dbaff88j615: Already exists 
72390cdr343a: Pull complete 
Digest: sha256:bba124b943dbc983404697511deae8888a301e3d11364fb690256e4e124422e3
Status: Downloaded newer image for registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号:1.0
registry.cn-hangzhou.aliyuncs.com/你的命名空间/你的仓库:版本号

然后查看:

[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
registry.cn-hangzhou.aliyuncs./你的命名空间/你的仓库   1.0       67785ab85293   56 minutes ago   191MB

验证,通过id去运行这个镜像:

[root@localhost ~]# docker run -it 67785ab85293 /bin/bash
root@21e562108df4:/# pwd
/
root@21e562108df4:/# cd /tmp
root@21e562108df4:/tmp# ls
a.txt
root@21e562108df4:/tmp# vim a.txt 

可以看到有上一步的a.txt

4.本地镜像发布到私有库

Docker Registry是官方提供的工具,用于构建私有镜像仓库

1.拉取registry

docker pull registry

如下即为成功

shell 复制代码
[root@localhost ~]# docker pull registry
Using default tag: latest
latest: Pulling from library/registry
79e9f2f55bf5: Pull complete 
0d96da54f60b: Pull complete 
5b27040df4a2: Pull complete 
e2ead8259a04: Pull complete 
3790aef225b9: Pull complete 
Digest: sha256:169211e20e2f2d5d115674681eb79d21a217b296b43374b8e39f97fcf866b375
Status: Downloaded newer image for registry:latest
docker.io/library/registry:latest
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED        SIZE
registry                                           latest    b8604a3fe854   2 years ago    26.2MB

运行Registry,相当于本地有一个Docker Hub

2.运行私有仓库

命令

docker run -d -p 5000:5000 -v /wzy/myregistry/:/tmp/registry --privileged=true registry

默认情况,仓库被创建在容器的var/ib/registry目录下,建议自行用容器卷映射,方便于宿主机联调。
这里指定为/wzy/myregistry目录,无需提前创建,运行命令自动创建,-v是容器卷命令,详见下一节
  • docker run: 运行一个容器的命令。
  • -d: 后台模式(detached mode),将容器在后台运行。
  • -p 5000:5000: 将容器的端口号 5000 映射到主机的端口号 5000。这样可以通过主机的 5000 端口访问运行在容器内的服务。
  • -v /wzy/myregistry/:/tmp/registry: 将主机上的 /wzy/myregistry/ 目录挂载到容器内的 /tmp/registry 目录。这样可以实现主机和容器之间的文件共享。
  • --privileged=true: 赋予容器特权。这将使容器在安全限制方面更宽松,具有更高的访问权限。
  • registry: 指定要运行的镜像名称。在这个例子中,运行的是名为 registry 的镜像。

执行:

shell 复制代码
[root@localhost ~]# docker run -d -p 5000:5000 -v /wzy/myregistry/:/tmp/registry --privileged=true registry
071a032b7355440076696650b63aeaf677c6bedc8588179308158d9da83ca5be

[root@localhost ~]# docker ps
CONTAINER ID   IMAGE      COMMAND                   CREATED          STATUS         PORTS                                       NAMES
071a032b7355   registry   "/entrypoint.sh /etc..."   10 seconds ago   Up 9 seconds   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   naughty_maxwell
[root@localhost ~]# 
3.提交镜像

创建一个新的Ubuntu镜像,安装ifconfig命令用于演示

shell 复制代码
[root@localhost ~]# docker run -it ubuntu /bin/bash
root@9cd8be1e0305:/# ifconfig
bash: ifconfig: command not found
root@9cd8be1e0305:/# 

先使用**apt-get update更新包管理工具**,再使用**apt-get install net-tools安装ifconfig**

shell 复制代码
[root@localhost ~]# docker run -it ubuntu /bin/bash
root@9cd8be1e0305:/# ifconfig
bash: ifconfig: command not found

root@9cd8be1e0305:/# apt-get update
Get:1 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]            
Get:2 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]  
Get:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:4 http://archive.ubuntu.com/ubuntu focal-backports InRelease [108 kB]
Get:5 http://security.ubuntu.com/ubuntu focal-security/universe amd64 Packages [1194 kB]
Get:6 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages [11.3 MB]
Get:7 http://security.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [3483 kB]
Get:8 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 Packages [29.8 kB]
Get:9 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [3546 kB]
Get:10 http://archive.ubuntu.com/ubuntu focal/main amd64 Packages [1275 kB]           
Get:11 http://archive.ubuntu.com/ubuntu focal/multiverse amd64 Packages [177 kB]      
Get:12 http://archive.ubuntu.com/ubuntu focal/restricted amd64 Packages [33.4 kB]     
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [1489 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 Packages [32.5 kB]
Get:15 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [4021 kB]   
Get:16 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [3634 kB]
Get:17 http://archive.ubuntu.com/ubuntu focal-backports/universe amd64 Packages [28.6 kB]
Get:18 http://archive.ubuntu.com/ubuntu focal-backports/main amd64 Packages [55.2 kB] 
Fetched 30.9 MB in 8s (3791 kB/s)                                                     
Reading package lists... Done

root@9cd8be1e0305:/# apt-get install net-tools
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  net-tools
0 upgraded, 1 newly installed, 0 to remove and 51 not upgraded.
Need to get 196 kB of archives.
After this operation, 864 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 net-tools amd64 1.60+git20180626.aebd88e-1ubuntu1 [196 kB]
Fetched 196 kB in 6s (34.3 kB/s)    
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package net-tools.
(Reading database ... 4127 files and directories currently installed.)
Preparing to unpack .../net-tools_1.60+git20180626.aebd88e-1ubuntu1_amd64.deb ...
Unpacking net-tools (1.60+git20180626.aebd88e-1ubuntu1) ...
Setting up net-tools (1.60+git20180626.aebd88e-1ubuntu1) ...
root@9cd8be1e0305:/#

再次执行ifconfig:

shell 复制代码
root@9cd8be1e0305:/# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:acff:fe11:3  prefixlen 64  scopeid 0x20<link>
        ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
        RX packets 8438  bytes 31702735 (31.7 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 8407  bytes 654464 (654.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

root@9cd8be1e0305:/# 

提交镜像,将上一步安装ifconfig的ubuntu进行提交

记得要退出运行的容器执行,ctrl+q+p:

shell 复制代码
docker commit -m="ifconfig add" -a="wzy" 9cd8be1e0305 wzynewubt:1.0

额外注意,最后的镜像名加版本号要小写,运行结果:

shell 复制代码
[root@localhost ~]# docker commit -m="ifconfig add" -a="wzy" 9cd8be1e0305 wzynewubt:1.0
sha256:e0b810b1a75f363b769835edf6a122579bb0ca7aec852ddc778dae58fb93d816

images命令查看,第一个就是:

shell 复制代码
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED              SIZE
wzynewubt                                          1.0       e0b810b1a75f   About a minute ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   24 hours ago         191MB
ubuntu                                             latest    efb62633a173   4 days ago           72.8MB
redis                                              latest    7614ae9453d1   2 years ago          113MB
registry                                           latest    b8604a3fe854   2 years ago          26.2MB
[root@localhost ~]# 
4.改镜像标签

查看私有库中是否有镜像

先拿到registry私有仓库的ip及端口:

shell 复制代码
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE      COMMAND                   CREATED          STATUS          PORTS                                       NAMES
071a032b7355   registry   "/entrypoint.sh /etc..."   36 minutes ago   Up 36 minutes   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   naughty_maxwell

再用http请求查看本地私有库:

curl -XGET http://0.0.0.0:5000/v2/_catalog

执行结果为空,证明目前本地私有库中还没有镜像:

shell 复制代码
[root@localhost ~]# curl -XGET http://0.0.0.0:5000/v2/_catalog
{"repositories":[]}
[root@localhost ~]# 

修改镜像标签,以符合上传私服规范

先看要上传的镜像现在的名字:

wzynewubt:1.0

[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
wzynewubt                                          1.0       e0b810b1a75f   22 minutes ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   24 hours ago     191MB
ubuntu                                             latest    efb62633a173   4 days ago       72.8MB
redis                                              latest    7614ae9453d1   2 years ago      113MB
registry                                           latest    b8604a3fe854   2 years ago      26.2MB
[root@localhost ~]# 

执行docker tag改标签

docker tag 原本的镜像名:TAG标签 私有库ip/原本的镜像名:TAG标签

这里就是

docker tag wzynewubt:1.0 0.0.0.0:5000/wzynewubt:1.0

执行结果,看到第一个就是改完的:

shell 复制代码
[root@localhost ~]# docker tag wzynewubt:1.0 0.0.0.0:5000/wzynewubt:1.0
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
0.0.0.0:5000/wzynewubt                             1.0       e0b810b1a75f   29 minutes ago   125MB
wzynewubt                                          1.0       e0b810b1a75f   29 minutes ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   24 hours ago     191MB
ubuntu                                             latest    efb62633a173   4 days ago       72.8MB
redis                                              latest    7614ae9453d1   2 years ago      113MB
registry                                           latest    b8604a3fe854   2 years ago      26.2MB
[root@localhost ~]# 
5.让私有库支持http

进入docker配置文件

执行修改:

vim /etc/docker/daemon.json

添加如下内容,ip从上面docker ps查看私有库运行的ip:

"insecure-registries":["0.0.0.0:5000"]

如图,将上面内容粘贴进来,注意逗号(先按键盘的i,粘贴完按esc,最后输入:wq回车)

如果不生效,重启docker,在启动私有库

[root@localhost ~]# systemctl restart docker
[root@localhost ~]# docker run -d -p 5000:5000 -v /wzy/myregistry/:/tmp/registry --privileged=true registry
6.推送镜像到私有库

docker push 符合要求的镜像名:TAG

shell 复制代码
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
0.0.0.0:5000/wzynewubt                             1.0       e0b810b1a75f   43 minutes ago   125MB
wzynewubt                                          1.0       e0b810b1a75f   43 minutes ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   24 hours ago     191MB
ubuntu                                             latest    efb62633a173   5 days ago       72.8MB
redis                                              latest    7614ae9453d1   2 years ago      113MB
registry                                           latest    b8604a3fe854   2 years ago      26.2MB
[root@localhost ~]# 

这里将上面第一个改过标签符合要求的镜像推送到私有库

docker push 0.0.0.0:5000/wzynewubt:1.0

执行结果

这里报这个错,就是修改完上面的配置没有重启生效

shell 复制代码
[root@localhost ~]# docker push 0.0.0.0:5000/wzynewubt:1.0
The push refers to repository [0.0.0.0:5000/wzynewubt]
Get "https://0.0.0.0:5000/v2/": http: server gave HTTP response to HTTPS client

重启在执行:

shell 复制代码
[root@localhost ~]# systemctl restart docker
[root@localhost ~]# docker run -d -p 5000:5000 -v /wzy/myregistry/:/tmp/registry --privileged=true registry
0e4ab965386912c6dd2f7af463a7dc8de07ed09a84823a94d1e3e36ad50b099e
[root@localhost ~]# docker push 0.0.0.0:5000/wzynewubt:1.0
The push refers to repository [0.0.0.0:5000/wzynewubt]
602bc96b42c9: Pushed 
afbdb0332390: Pushed 
1.0: digest: sha256:fe85a0843c1c4ca7641694af46cc90fb7970ab4eec9b10f8a7b56fa1a2c1f5c4 size: 741
[root@localhost ~]# 

curl验证

curl -XGET http://docker ps查看到的私有库ip:端口号/v2/_catalog
我这里是:
curl -XGET http://0.0.0.0:5000/v2/_catalog

执行,有了刚才推送的镜像:

shell 复制代码
[root@localhost ~]# curl -XGET http://0.0.0.0:5000/v2/_catalog
{"repositories":["wzynewubt"]}
[root@localhost ~]# 
7.将私有库镜像拉到本地

实际生产环境,私有库会有单独的服务器,这里的私有库建在了本地,为了演示先删除本地的0.0.0.0:5000/wzynewubt镜像

shell 复制代码
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
wzynewubt                                          1.0       e0b810b1a75f   52 minutes ago   125MB
0.0.0.0:5000/wzynewubt                             1.0       e0b810b1a75f   52 minutes ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   24 hours ago     191MB
ubuntu                                             latest    efb62633a173   5 days ago       72.8MB
redis                                              latest    7614ae9453d1   2 years ago      113MB
registry                                           latest    b8604a3fe854   2 years ago      26.2MB
[root@localhost ~]# docker rmi -f e0b810b1a75f
Untagged: 0.0.0.0:5000/wzynewubt:1.0
Untagged: 0.0.0.0:5000/wzynewubt@sha256:fe85a0843c1c4ca7641694af46cc90fb7970ab4eec9b10f8a7b56fa1a2c1f5c4
Untagged: wzynewubt:1.0
Deleted: sha256:e0b810b1a75f363b769835edf6a122579bb0ca7aec852ddc778dae58fb93d816
[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED        SIZE
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   25 hours ago   191MB
ubuntu                                             latest    efb62633a173   5 days ago     72.8MB
redis                                              latest    7614ae9453d1   2 years ago    113MB
registry                                           latest    b8604a3fe854   2 years ago    26.2MB
[root@localhost ~]# 

拉取

docker pull 私服ip:端口号/镜像名:tag

执行

docker pull 0.0.0.0:5000/wzynewubt:1.0

执行后如下即为成功,再用images查看发现又有了0.0.0.0:5000/wzynewubt

shell 复制代码
[root@localhost ~]# docker pull 0.0.0.0:5000/wzynewubt:1.0
1.0: Pulling from wzynewubt
8dbaff99f615: Already exists 
696b01e53a04: Already exists 
Digest: sha256:fe85a0843c1c4ca7641694af46cc90fb7970ab4eec9b10f8a7b56fa1a2c1f5c4
Status: Downloaded newer image for 0.0.0.0:5000/wzynewubt:1.0
0.0.0.0:5000/wzynewubt:1.0

[root@localhost ~]# docker images
REPOSITORY                                         TAG       IMAGE ID       CREATED          SIZE
0.0.0.0:5000/wzynewubt                             1.0       e0b810b1a75f   58 minutes ago   125MB
registry.cn-hangzhou.aliyuncs.com/bigworth/stock   1.0       67785ab85293   25 hours ago     191MB
ubuntu                                             latest    efb62633a173   5 days ago       72.8MB
redis                                              latest    7614ae9453d1   2 years ago      113MB
registry                                           latest    b8604a3fe854   2 years ago      26.2MB
[root@localhost ~]# 

再次运行验证:

shell 复制代码
[root@localhost ~]# docker run -it e0b810b1a75f /bin/bash
root@3325f2f62cc7:/# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:acff:fe11:3  prefixlen 64  scopeid 0x20<link>
        ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
        RX packets 7  bytes 586 (586.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 7  bytes 586 (586.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

root@3325f2f62cc7:/# exit
exit
[root@localhost ~]# 

五、容器数据卷

1.概念

什么是容器卷,以及好处

卷就是目录或文件,存在于一个或多个容器中,由docker挂载到容器,但不属于联合文件系统,因此能够绕过Union File System提供一些用于持续存储或共享数据的特性:

卷的设计目的就是数据的持久化,完全独立于容器的生存周期,因此Docker不会在容器删除时删除其挂载的数据卷。

权限扩容

--privileged=true

容器数据卷映射,其实就是把容器内的数据备份+持久化到宿主机目录

这里看运行私有仓库的命令:

docker run -d -p 5000:5000   -v /wzy/myregistry/:/tmp/registry  --privileged=true  registry

-v就是容器卷映射命令,这里会把容器内/tmp/registry目录中的数据复制到宿主机/wzy/myregistry/目录下,这样容器内与宿主机的两个目录都有相同的数据,容器内的数据被删除时,可以通过宿主机恢复。

Docker不会在容器删除时删除其挂载的数据卷,也就是说registry被删除时,不会删除/wzy/myregistry/目录下的内容。

2.运行

运行一个带有容器卷存储功能的容器实例,容器与宿主机的数据卷内容完全共享:

  • 当容器中指定被映射目录下的内容被修改时,会同步到宿主机指定的容器卷,反之亦然。

  • 即便容器被停止的情况下,宿主机在数据卷内添加修改数据,在容器重新启动后,也会同步过去。

命令公式:

docker run  -it  --privileged=true  -v  /宿主机绝对路径目录:/容器内目录  镜像名

如下命令,运行一个名叫myubuntu的实例,将此实例 /tmp/docker_data 目录的内容映射到宿主机 /wzy/docker_data 目录下,如果没有这两个目录,会被自动创建:

记得Ubuntu后面跟/bin/bash,不然报错docker: Error response from daemon: no command specified.

docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash

运行后,进入ubuntu:

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash
root@9e73bbf13fae:/# 

进入容器内的 /tmp/docker_data 目录,发现为空,然后再看宿主机的 /wzy/docker_data 目录内部,也是空

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash
root@9e73bbf13fae:/# pwd
/
root@9e73bbf13fae:/# cd /tmp/docker_data
root@9e73bbf13fae:/tmp/docker_data# ls
root@9e73bbf13fae:/tmp/docker_data# 

接下来,向容器内 /tmp/docker_data 目录添加文件dockerin.txt

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash
root@9e73bbf13fae:/# pwd
/
root@9e73bbf13fae:/# cd /tmp/docker_data
root@9e73bbf13fae:/tmp/docker_data# ls
root@9e73bbf13fae:/tmp/docker_data# touch dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# ls
dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# 

再看宿主机,也有了该文件:

再宿主机上创建一个文件text.txt

然后看容器,也是存在的

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash
root@9e73bbf13fae:/# pwd
/
root@9e73bbf13fae:/# cd /tmp/docker_data
root@9e73bbf13fae:/tmp/docker_data# ls
root@9e73bbf13fae:/tmp/docker_data# touch dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# ls
dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# ls
dockerin.txt  text.txt
root@9e73bbf13fae:/tmp/docker_data# 

向宿主机dockerin.txt内写数据

再看容器中的dockerin.txt,也同步了该数据

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true -v /wzy/docker_data:/tmp/docker_data --name=myubuntu ubuntu /bin/bash
root@9e73bbf13fae:/# pwd
/
root@9e73bbf13fae:/# cd /tmp/docker_data
root@9e73bbf13fae:/tmp/docker_data# ls
root@9e73bbf13fae:/tmp/docker_data# touch dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# ls
dockerin.txt
root@9e73bbf13fae:/tmp/docker_data# ls
dockerin.txt  text.txt
root@9e73bbf13fae:/tmp/docker_data# cat dockerin.txt 

hello docker
root@9e73bbf13fae:/tmp/docker_data# 

3.查看数据卷是否挂载成功

docker inspect 容器id

查看输出的Mounts内容

shell 复制代码
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
9e73bbf13fae   ubuntu    "/bin/bash"   22 minutes ago   Up 22 minutes             myubuntu
[root@localhost ~]# docker inspect 9e73bbf13fae

找到输出的这段,Source即为宿主机挂载目录,Destination是容器的:

json 复制代码
"Mounts": [
            {
                "Type": "bind",
                "Source": "/wzy/docker_data",
                "Destination": "/tmp/docker_data",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],

4.映射规则

默认情况下,容器与宿主机的数据卷是双向互通的,无论谁修改,双方都会同步,这就是默认规则,即rw

即:

docker run  -it  --privileged=true  -v  /宿主机绝对路径目录:/容器内目录  镜像名

docker run  -it  --privileged=true  -v  /宿主机绝对路径目录:/容器内目录:rw  镜像名

的效果一致,默认即为rw规则,可读可写。

ro

read only只读

如下:

docker run  -it  --privileged=true  -v  /宿主机绝对路径目录:/容器内目录:ro  镜像名

这样的话,容器内就无法在映射的数据卷目录添加修改文件及数据了,但宿主机可以,而且宿主机修改的内容也可以同步到容器内

5.卷的继承与共享

docker run -it --privileged=true --volumes-from 父类 --name=自定容器名 ubuntu /bin/bash

父类用第2步运行的myubuntu

docker run -it --privileged=true --volumes-from myubuntu --name=ubuntutwo ubuntu /bin/bash

执行:

shell 复制代码
[root@localhost ~]# docker run -it --privileged=true --volumes-from myubuntu --name=ubuntutwo ubuntu /bin/bash
root@dd6394bc7a4c:/# pwd
/
root@dd6394bc7a4c:/# cd /tmp/docker_data
root@dd6394bc7a4c:/tmp/docker_data# ls
dockerin.txt  text.txt
root@dd6394bc7a4c:/tmp/docker_data# 

可以看到,新创建的ubuntutwo也同样同步了myubuntu与宿主机的数据卷内容,这样,就是三者互相同步了。即使有任意容器挂掉,也会在重启后同步关闭期的数据。

相关推荐
网络研究院1 小时前
Am I Isolated:一款安全态势基准测试工具
容器·工具·基准测试·安全态势
涔溪2 小时前
Docker简介
spring cloud·docker·eureka
内核程序员kevin3 小时前
在Linux环境下使用Docker打包和发布.NET程序并配合MySQL部署
linux·mysql·docker·.net
kayotin4 小时前
Wordpress博客配置2024
linux·mysql·docker
Ztiddler4 小时前
【Linux Shell命令-不定期更新】
linux·运维·服务器·ssh
小小不董4 小时前
Oracle OCP认证考试考点详解082系列16
linux·运维·服务器·数据库·oracle·dba
IPdodo全球网络4 小时前
如何利用静态住宅IP优化Facebook商城的网络稳定性与运营效率
运维·服务器
颜淡慕潇5 小时前
【K8S问题系列 | 9】如何监控集群CPU使用率并设置告警?
后端·云原生·容器·kubernetes·问题解决
运维&陈同学5 小时前
【模块一】kubernetes容器编排进阶实战之k8s基础概念
运维·docker·云原生·容器·kubernetes·云计算
信子姚青5 小时前
K8s使用nfs
容器