谢谢这个问题 https://stackoverflow.com/q/36871588/7106084我意识到你可以跑tc qdisc add dev eth0 root tbf rate 1mbit latency 50ms burst 10000
在容器内将其上传速度设置为 1 MB/s。
下面是一个示例 Dockerfile,它通过生成随机文件并将其上传到来演示这一点/dev/null-as-a-service https://devnull-as-a-service.com/上传速度大约为 25KB/s:
FROM ubuntu
# install dependencies
RUN apt-get update
RUN apt-get install -y iproute curl
# create a large random file to upload
RUN head -c 2M </dev/urandom > /upload.data
# rate-limit the network interface and
# upload the data when docker image is run
RUN echo "#!/bin/bash" >> /upload.sh
RUN echo "tc qdisc add dev eth0 root tbf rate 25kbps latency 50ms burst 2500" >> /upload.sh
RUN echo "curl -d @/upload.data http://devnull-as-a-service.com/dev/null" >> /upload.sh
RUN chmod a+x /upload.sh
ENTRYPOINT exec /upload.sh
假设您的 Dockerfile 位于名为的目录中ratelimit
它位于您当前的工作目录中,您可以使用以下命令运行它:
docker build ratelimit -t ratelimit && docker run --cap-add=NET_ADMIN ratelimit
选项--cap-add=NET_ADMIN
授予容器修改其网络接口的权限。你可以找到文档here https://docs.docker.com/engine/reference/run/#/runtime-privilege-and-linux-capabilities.
Dockerfile 首先安装它需要的依赖项。iproute
提供了tc
工具,以及curl
允许我们提出速率限制的请求。安装依赖项后,我们生成一个 2MB 的随机文件来上传。下一部分构建一个脚本文件,用于配置速率限制并开始上传。最后,我们将该脚本指定为容器运行时要执行的操作。
该容器向网络接口添加令牌桶过滤器,将连接速度减慢至 25KB/s。可以找到提供给令牌存储过滤器的选项的文档here http://lartc.org/manpages/tc-tbf.txt.
可以修改此 Dockerfile 以执行任何其他网络任务,方法是删除对 cURL 的调用并在其位置执行上传(当然,在安装上传所需的任何工具之后)。