Manage Data in Containers

本文介绍如何使用Docker管理容器内的数据,包括数据卷和数据卷容器的概念与使用方法,以及如何进行备份、恢复和迁移。

Manage data in containers

So far we’ve been introduced to some basic Docker concepts,seen how to work with Docker images as well as learned aboutnetworking and links between containers. In this section we’regoing to discuss how you can manage data inside and between your Dockercontainers.

We’re going to look at the two primary ways you can manage data inDocker.

  • Data volumes, and
  • Data volume containers.

Data volumes

A data volume is a specially-designated directory within one or morecontainers that bypasses the Union File System. Data volumes provide several useful features for persistent or shared data:

  • Volumes are initialized when a container is created. If the container’sbase image contains data at the specified mount point, that existing data iscopied into the new volume upon volume initialization.
  • Data volumes can be shared and reused among containers.
  • Changes to a data volume are made directly.
  • Changes to a data volume will not be included when you update an image.
  • Data volumes persist even if the container itself is deleted.

Data volumes are designed to persist data, independent of the container’s lifecycle. Docker therefore never automatically delete volumes when you removea container, nor will it “garbage collect” volumes that are no longerreferenced by a container.

Adding a data volume

You can add a data volume to a container using the -v flag with thedocker create and docker run command. You can use the -v multiple timesto mount multiple data volumes. Let’s mount a single volume now in our webapplication container.

$ docker run -d -P --name web -v /webapp training/webapp python app.py

This will create a new volume inside a container at /webapp.

Note:You can also use the VOLUME instruction in a Dockerfile to add one ormore new volumes to any container created from that image.

Docker volumes default to mount in read-write mode, but you can also set it to be mounted read-only.

$ docker run -d -P --name web -v /opt/webapp:ro training/webapp python app.py

Locating a volume

You can locate the volume on the host by utilizing the ‘docker inspect’ command.

$ docker inspect web

The output will provide details on the container configurations including thevolumes. The output should look something similar to the following:

...
Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true
    }
]
...

You will notice in the above ‘Source’ is specifying the location on the host and‘Destination’ is specifying the volume location inside the container. RW showsif the volume is read/write.

Mount a host directory as a data volume

In addition to creating a volume using the -v flag you can also mount adirectory from your Docker daemon’s host into a container.

$ docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py

This command mounts the host directory, /src/webapp, into the container at/opt/webapp. If the path /opt/webapp already exists inside the container’simage, the /src/webapp mount overlays but does not remove the pre-existingcontent. Once the mount is removed, the content is accessible again. This isconsistent with the expected behavior of the mount command.

The container-dir must always be an absolute path such as /src/docs.The host-dir can either be an absolute path or a name value. If yousupply an absolute path for the host-dir, Docker bind-mounts to the pathyou specify. If you supply a name, Docker creates a named volume by that name.

A name value must start with start with an alphanumeric character,followed by a-z0-9, _ (underscore), . (period) or - (hyphen).An absolute path starts with a / (forward slash).

For example, you can specify either /foo or foo for a host-dir value.If you supply the /foo value, Docker creates a bind-mount. If you supplythe foo specification, Docker creates a named volume.

If you are using Docker Machine on Mac or Windows, your Docker daemon has only limited access to your OS X or Windows filesystem. Docker Machine triesto auto-share your /Users (OS X) or C:\Users (Windows) directory. So,you can mount files or directories on OS X using.

docker run -v /Users/<path>:/<container path> ...

On Windows, mount directories using:

docker run -v /c/Users/<path>:/<container path> ...`

All other paths come from your virtual machine’s filesystem. For example, ifyou are using VirtualBox some other folder available for sharing, you need to doadditional work. In the case of VirtualBox you need to make the host folderavailable as a shared folder in VirtualBox. Then, you can mount it using theDocker -v flag.

Mounting a host directory can be useful for testing. For example, you can mountsource code inside a container. Then, change the source code and see its effecton the application in real time. The directory on the host must be specified asan absolute path and if the directory doesn’t exist Docker will automaticallycreate it for you. This auto-creation of the host path has been deprecated.

Docker volumes default to mount in read-write mode, but you can also set it tobe mounted read-only.

$ docker run -d -P --name web -v /src/webapp:/opt/webapp:ro training/webapp python app.py

Here we’ve mounted the same /src/webapp directory but we’ve added the rooption to specify that the mount should be read-only.

Because of limitations in the mountfunction,moving subdirectories within the host’s source directory can giveaccess from the container to the host’s file system. This requires a malicioususer with access to host and its mounted directory.

Note: The host directory is, by its nature, host-dependent. For thisreason, you can’t mount a host directory from Dockerfile because built imagesshould be portable. A host directory wouldn’t be available on all potentialhosts.

Volume labels

Labeling systems like SELinux require that proper labels are placed on volumecontent mounted into a container. Without a label, the security system mightprevent the processes running inside the container from using the content. Bydefault, Docker does not change the labels set by the OS.

To change a label in the container context, you can add either of two suffixes:z or :Z to the volume mount. These suffixes tell Docker to relabel fileobjects on the shared volumes. The z option tells Docker that two containersshare the volume content. As a result, Docker labels the content with a sharedcontent label. Shared volume labels allow all containers to read/write content.The Z option tells Docker to label the content with a private unshared label.Only the current container can use a private volume.

Mount a host file as a data volume

The -v flag can also be used to mount a single file - instead of justdirectories - from the host machine.

$ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash

This will drop you into a bash shell in a new container, you will have your bashhistory from the host and when you exit the container, the host will have thehistory of the commands typed while in the container.

Note:Many tools used to edit files including vi and sed --in-place may resultin an inode change. Since Docker v1.1.0, this will produce an error such as“sed: cannot rename ./sedKdJ9Dy: Device or resource busy”. In the case whereyou want to edit the mounted file, it is often easiest to instead mount theparent directory.

Creating and mounting a data volume container

If you have some persistent data that you want to share betweencontainers, or want to use from non-persistent containers, it’s best tocreate a named Data Volume Container, and then to mount the data fromit.

Let’s create a new named container with a volume to share.While this container doesn’t run an application, it reuses the training/postgresimage so that all containers are using layers in common, saving disk space.

$ docker create -v /dbdata --name dbdata training/postgres /bin/true

You can then use the --volumes-from flag to mount the /dbdata volume in another container.

$ docker run -d --volumes-from dbdata --name db1 training/postgres

And another:

$ docker run -d --volumes-from dbdata --name db2 training/postgres

In this case, if the postgres image contained a directory called /dbdatathen mounting the volumes from the dbdata container hides the/dbdata files from the postgres image. The result is only the filesfrom the dbdata container are visible.

You can use multiple --volumes-from parameters to bring together multiple datavolumes from multiple containers.

You can also extend the chain by mounting the volume that came from thedbdata container in yet another container via the db1 or db2 containers.

$ docker run -d --name db3 --volumes-from db1 training/postgres

If you remove containers that mount volumes, including the initial dbdatacontainer, or the subsequent containers db1 and db2, the volumes will notbe deleted. To delete the volume from disk, you must explicitly calldocker rm -v against the last container with a reference to the volume. Thisallows you to upgrade, or effectively migrate data volumes between containers.

Note: Docker will not warn you when removing a container withoutproviding the -v option to delete its volumes. If you remove containerswithout using the -v option, you may end up with “dangling” volumes;volumes that are no longer referenced by a container.Dangling volumes are difficult to get rid of and can take up a large amountof disk space. We’re working on improving volume management and you can checkprogress on this in pull request #14214

Backup, restore, or migrate data volumes

Another useful function we can perform with volumes is use them forbackups, restores or migrations. We do this by using the--volumes-from flag to create a new container that mounts that volume,like so:

$ docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata

Here we’ve launched a new container and mounted the volume from thedbdata container. We’ve then mounted a local host directory as/backup. Finally, we’ve passed a command that uses tar to backup thecontents of the dbdata volume to a backup.tar file inside our/backup directory. When the command completes and the container stopswe’ll be left with a backup of our dbdata volume.

You could then restore it to the same container, or another that you’ve madeelsewhere. Create a new container.

$ docker run -v /dbdata --name dbdata2 ubuntu /bin/bash

Then un-tar the backup file in the new container’s data volume.

$ docker run --volumes-from dbstore2 -v $(pwd):/backup ubuntu bash -c "cd /dbdata && tar xvf /backup/backup.tar"

You can use the techniques above to automate backup, migration andrestore testing using your preferred tools.

Important tips on using shared volumes

Multiple containers can also share one or more data volumes. However, multiple containers writing to a single shared volume can cause data corruption. Make sure you’re applications are designed to write to shared data stores.

Data volumes are directly accessible from the Docker host. This means you can read and write to them with normal Linux tools. In most cases you should not do this as it can cause data corruption if your containers and applications are unaware of your direct access.

Next steps

Now we’ve learned a bit more about how to use Docker we’re going to see how tocombine Docker with the services available onDocker Hub including Automated Builds and privaterepositories.

Go to Working with Docker Hub.

下载前必看:https://renmaiwang.cn/s/bvbfw Verilog设计_串并转换 / 移位寄存器实现了一种串并转换的功能,其核心原理在于移位寄存器的运用。 这里详细展示了串转并以及并转串两种不同的设计方案。 每一种转换模式都设有专属的使能信号,同时并行输出数据的格式提供了两种选择:最低有效位优先(lsb)和最高有效位优先(msb)。 串并转换技术主要应用于串行传输与并行传输这两种数据传输模式之间的相互转换,而移位寄存器是达成这一目标的常用工具,能够支持并行及串行的数据输入与输出操作。 这些移位寄存器通常被设定为“串行输入、并行输出”(SIPO)或“并行输入、串行输出”(PISO)两种工作模式。 在串行数据输出的过程中,构成数据和字符的码元会按照既定的时间顺序逐位进行传输。 相比之下,并行数据传输则是在同一时刻将固定数量(普遍为8位或16位等)的数据和字符码元同时发送至接收端。 数据输入通常采用串行格式进行。 一旦数据成功输入寄存器,它便可以在所有输出端同时被读取,或者选择逐位移出。 寄存器中的每个触发器均设计为边沿触发类型,并且所有触发器均以特定的时钟频率协同工作。 对于每一个输入位而言,它需要经过N个时钟周期才能最终在N个输出端呈现,从而完成并行输出。 值得注意的是,在串行加载数据期间,并行输出端的数据状态应保持稳定。 数据输入则采用并行格式。 在将数据写入寄存器的操作过程中,写/移位控制线必须暂时处于非工作状态;而一旦需要执行移位操作,控制线便会变为激活状态,并且寄存器会被锁定以保持当前状态。 只要时钟周期数不超过输入数据串的长度,数据输出端Q将按照预定的顺序逐位读出并行数据,并且必须明确区分最低有效位(LSB)和最高有效位(MSB)。
<think>我们之前已经确定用户环境中缺少dockerd二进制文件,这可能是因为没有安装dockerd包或者安装不完整。 用户通过`opkg list | grep docker`列出了相关包,我们需要根据这些包的信息来指导用户安装正确的包以解决dockerd缺失的问题。 根据引用[1],我们知道在OpenWRT中可以通过opkg安装docker,但是注意:docker包可能只包含客户端(docker命令),而dockerd可能在另一个包中。 通常,在OpenWRT中,dockerd二进制文件是由一个单独的包提供的,比如`dockerd`包。而客户端工具则是由`docker`包提供。 我们需要检查用户列出的包中是否有包含dockerd的包。假设用户列出的包中有如下几个: docker - 提供客户端工具(docker命令) dockerd - 提供守护进程(dockerd) docker-compose - 提供docker-compose命令 python3-docker - Docker的Python SDK 因此,解决方案是安装`dockerd`包。 步骤: 1. 安装dockerd包:`opkg install dockerd` 2. 启动dockerd服务:`service dockerd start` 3. 设置开机启动:`service dockerd enable` 但是,注意:安装dockerd包可能会自动安装其依赖,包括containerd、runc等。 另外,引用[2]和[3]提到了docker-compose的安装,但这不是用户当前问题的核心。用户当前的核心问题是缺少dockerd。 因此,回答应聚焦于如何安装dockerd,并解决守护进程缺失的问题。 同时,根据引用[4]中的使用案例,在安装好dockerd后,用户就可以使用docker命令来管理容器了。 注意:由于OpenWRT的特殊性,可能还需要配置存储驱动等,但先确保dockerd安装成功并运行。 如果用户在安装dockerd后仍然找不到dockerd,可能需要检查安装路径。通常,dockerd安装在`/usr/sbin/dockerd`而不是`/usr/bin/dockerd`。因此,之前的命令`which dockerd || ls -l /usr/bin/dockerd`可能因为路径不对而找不到。正确的做法是检查`/usr/sbin/dockerd`。 所以,我们可以在回答中调整检查路径。 回答结构如下: 1. 指出问题原因:dockerd包未安装,且通常安装在/usr/sbin目录。 2. 安装dockerd包。 3. 验证安装:检查/usr/sbin/dockerd。 4. 启动并启用服务。 5. 验证docker服务状态。 同时,生成相关问题。 注意:在OpenWRT中,dockerd的服务名称可能是`dockerd`也可能是`docker`,需要根据实际情况调整。通常,安装dockerd包后会创建一个init脚本`/etc/init.d/dockerd`。 下面开始组织回答。 </think>### 解决 Docker 相关包安装及 `dockerd` 缺失问题 #### ▶ Docker 包功能解析(基于 `opkg list | grep docker` 输出) | **包名称** | **功能说明** | **关键路径** | |--------------------|-----------------------------------------------------------------------------|--------------------------------| | `docker` | Docker 客户端工具 (`docker` 命令) | `/usr/bin/docker` | | **`dockerd`** | **Docker守护进程核心引擎**(缺失部分)<br>⚠️ 当前未安装导致服务不可用 | `/usr/sbin/dockerd` | | `docker-compose` | 容器编排工具(依赖 `dockerd`) | `/usr/bin/docker-compose` | | `python3-docker` | Docker SDK for Python(API 开发依赖) | `/usr/lib/python3.9/site-packages/docker` | | `containerd` | 容器运行时(`dockerd` 的底层依赖) | `/usr/bin/containerd` | --- #### ▶ 解决 `dockerd` 未找到的核心步骤 **1. 安装守护进程包**(关键修复) ```bash # 安装 dockerd 包 opkg update opkg install dockerd # 验证安装路径(注意在 /usr/sbin 而非 /usr/bin) ls -l /usr/sbin/dockerd && echo "安装成功" ``` 输出示例: `-rwxr-xr-x 1 root root 45M Jul 15 10:30 /usr/sbin/dockerd`[^1] **2. 配置并启动服务** ```bash # 创建服务配置文件 cat > /etc/docker/daemon.json <<EOF { "data-root": "/opt/docker", "iptables": false } EOF # 启动守护进程 service dockerd start service dockerd enable ``` **3. 验证服务状态** ```bash # 检查进程 pgrep dockerd && echo "运行中" # 测试客户端连接 docker info | grep "Server Version" ``` --- #### ▶ 其他包的安装与使用 **1. Docker Compose 安装**(需先安装 `dockerd`) ```bash # 下载二进制文件(适配 CPU 架构) opkg install curl curl -L "https://github.com/docker/compose/releases/download/v2.21.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose # 设置可执行权限 chmod +x /usr/local/bin/docker-compose ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose # 验证版本 docker-compose version # 输出:Docker Compose version v2.21.0[^2][^3] ``` **2. Python Docker SDK 使用示例** ```python from docker import DockerClient client = DockerClient(base_url='unix:///var/run/docker.sock') print(client.images.list()) # 列出所有镜像[^4] ``` --- ### 故障排查表 | **现象** | **解决方案** | |-----------------------------------|-----------------------------------------------------------------------------| | `service dockerd start` 失败 | 检查依赖:`opkg install containerd runc` | | `/opt/docker` 空间不足 | 修改存储路径:`sed -i 's|/opt/docker|/mnt/sda1/docker|' /etc/docker/daemon.json` | | `docker-compose` 连接超时 | 验证守护进程:`netstat -ln | grep docker.sock` | | 客户端报错 `Cannot connect...` | 重启服务:`service dockerd restart` | > 💡 **架构关系图解** > $$ \begin{array}{c} \text{用户命令} \\ \downarrow \\ \text{docker-client} \xrightarrow{\text{API}} \text{dockerd} \xrightarrow{\text{驱动}} \text{containerd} \\ \downarrow \\ \text{容器} \end{array} $$ > - `docker-compose` 通过客户端操作 `dockerd`[^3] > - `python3-docker` 直接调用 Docker API --- ### 典型应用场景 1. **容器启动**(使用 `docker` 包) ```bash docker run -d --name nginx -p 80:80 nginx:alpine ``` 2. **编排服务**(使用 `docker-compose` 包) ```yaml # docker-compose.yml services: web: image: nginx:alpine ports: - "80:80" ``` 3. **自动化管理**(使用 `python3-docker` 包) ```python # 自动清理停止的容器 client = DockerClient() for container in client.containers.list(all=True): if container.status == 'exited': container.remove() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值