借助 Cloud Run,您可以将容器实例连接到 CIFS 和 SMB 网络文件共享,以便读取和写入共享文件。您可以使用 smbnetfs 在用户空间(而非内核空间)中装载共享,也可以使用 smbclient 传输文件。
如需了解 Cloud Run 上的其他存储选项,请参阅如何为服务、作业、工作器池或实例配置 NFS 或 Filestore 卷。您还可以为服务、作业、工作器池或实例配置 Cloud Storage FUSE 卷。
限制
使用
smbnetfs时,您必须指定第二代执行环境。由于 Cloud Run 执行环境限制,CIFS/SMB 无法直接装载到 Cloud Run 中。不过,您可以使用不依赖于内核装载的 SMB 客户端,例如
smbnetfs(基于 FUSE)或smbclient。Cloud Run 旨在快速扩容到大量实例。但是,大多数网络文件系统并非设计为供大量客户端并发使用。对于 Cloud Run 服务,请考虑使用实例数上限功能来限制 Cloud Run 实例的数量。
使用 smbnetfs
smbnetfs 是一个基于 FUSE 的文件系统,可让您将 SMB 共享作为本地文件系统层次结构的一部分进行装载。
如需将 smbnetfs 与 Cloud Run 搭配使用,请更新 Dockerfile 以安装 smbnetfs 及其依赖项,并配置凭证。
在 Dockerfile 中配置 smbnetfs
将以下指令添加到 Dockerfile 中:
# Install smbnetfs, fuse and other dependencies
RUN apt-get update && apt-get install -y smbnetfs fuse && rm -rf /var/lib/apt/lists/*
# Setup smbnetfs configuration
RUN mkdir -p ~/.smb
# Check if files exist before copying, as strict locations might vary or be missing in minimal images
RUN [ -f /etc/smbnetfs.conf ] && cp /etc/smbnetfs.conf ~/.smb/ || echo "smbnetfs.conf not found"
# Create the auth file
# In production, use mechanisms like [Secret Manager](/run/docs/configuring/services/secrets) to handle credentials
# securely instead of placing them directly in the Dockerfile.
RUN echo 'auth "<smb-server-ip>" "<smb-username>" "<smb-password>"' > ~/.smb/smbnetfs.auth
RUN chmod 600 ~/.smb/smbnetfs.auth
# Create the host file
RUN echo 'host <smb-server-ip> visible=true' > ~/.smb/smbnetfs.host
RUN chmod 600 ~/.smb/smbnetfs.host
# Enable the includes in the main config if they exist
RUN if [ -f ~/.smb/smbnetfs.conf ]; then \
sed -i 's/^#include "smbnetfs.auth"/include "smbnetfs.auth"/' ~/.smb/smbnetfs.conf && \
sed -i 's/^#include "smbnetfs.host"/include "smbnetfs.host"/' ~/.smb/smbnetfs.conf; \
fi
将 <smb-server-ip>、<smb-username> 和 <smb-password> 替换为 SMB 服务器的连接详细信息。
在容器启动期间装载 SMB 共享
在容器启动后且应用启动前,运行 smbnetfs 以装载共享。如果您的容器以非根用户身份运行,您可能需要调整权限或 FUSE 配置。
创建装载点(例如
/mnt/smb),如以下命令所示:mkdir /mnt/smb使用
smbnetfs命令装载 SMB 文件系统:smbnetfs /mnt/smb在
/mnt/smb/<smb-server-ip>/<share-name>下访问您的共享,如以下命令所示:ls /mnt/smb/smb-server-ip/share-name
问题排查
使用 O_APPEND 标志和 smbnetfs 写入文件时,您可能会遇到输入/输出错误。如需了解详情,请参阅 Stack Overflow 讨论。
使用 smbclient
smbclient 是一种命令行工具,可提供类似 FTP 的界面来访问 SMB 共享。您可以使用它在 SMB 服务器上转移文件或运行命令。
为避免在每个命令中提供凭证,您可以将其存储在文件中。
将凭据存储在文件中,例如
smb-cred.txt:username = <smb-username> password = <smb-password>除了凭证文件之外,您还可以使用
-U或--user选项为每个命令提供凭证,例如:--user=[DOMAIN\]USERNAME[%PASSWORD]。将
smbclient工具与-A标志搭配使用,以指定凭据文件。例如,如需列出共享中的文件,请运行以下命令:smbclient //smb-server-ip/share-name -A smb-cred.txt -c 'ls'
如需使用 smbclient 工具修改文件,请下载文件,在本地进行修改,然后将其上传回共享,如以下步骤所示。
运行 get 命令下载文件:
smbclient //smb-server-ip/share-name -A smb-cred.txt -c 'get remote local'
在本地修改文件。
修改后,运行 put 命令上传文件:
smbclient //smb-server-ip/share-name -A smb-cred.txt -c 'put local remote'
当您使用 smbclient 工具时,SMB 服务器会使用您提供的凭据来识别您的身份。这样,服务器就可以应用正确的文件权限。
如需查看 smbclient 命令的完整列表,请参阅官方 smbclient 文档。