Docker 清除代理的几种方法

在不再需要代理、切换网络环境或代理配置错误时,需要彻底清除 Docker 相关代理配置,否则可能导致 docker pull 失败、容器网络异常等问题。


一、清除 Docker daemon(宿主机)代理(最常见)

1️⃣ 删除 systemd 代理配置文件

sudo rm -f /etc/systemd/system/docker.service.d/proxy.conf

如果目录下有多个代理文件:

sudo rm -f /etc/systemd/system/docker.service.d/*.conf

2️⃣ 重新加载并重启 Docker

sudo systemctl daemon-reload
sudo systemctl restart docker

3️⃣ 验证代理是否已清除

systemctl show --property=Environment docker

正常情况下看不到 HTTP_PROXY / HTTPS_PROXY


二、清除 Docker 客户端(~/.docker/config.json)代理

有些环境会在 Docker 客户端层配置代理。

1️⃣ 查看配置

cat ~/.docker/config.json

可能看到类似:

{
  "proxies": {
    "default": {
      "httpProxy": "http://proxy:port",
      "httpsProxy": "http://proxy:port",
      "noProxy": "localhost,127.0.0.1"
    }
  }
}

2️⃣ 删除代理配置

方式一:直接删除整个文件

rm -f ~/.docker/config.json

方式二:编辑并删除 proxies 字段

vim ~/.docker/config.json

三、清除容器级代理(已运行容器)

⚠️ 重要说明

容器内环境变量一旦启动无法修改
必须 停止并删除容器后重新启动

1️⃣ 停止并删除容器

docker stop <container_id>
docker rm <container_id>

2️⃣ 重新启动(不带代理参数)

docker run ubuntu

四、清除 Docker Compose 中的代理

1️⃣ 检查 docker-compose.yml

environment:
  HTTP_PROXY: http://proxy:port
  HTTPS_PROXY: http://proxy:port

删除相关字段即可。


2️⃣ 重新创建容器

docker compose down
docker compose up -d

五、清除 Dockerfile 中的代理

1️⃣ 查找代理配置

ENV HTTP_PROXY=http://proxy:port
ENV HTTPS_PROXY=http://proxy:port

2️⃣ 删除后重新构建镜像

docker build --no-cache -t myimage .
⚠️ 不加 --no-cache 可能仍使用旧镜像层

六、清除 build 阶段代理(BuildKit / ARG)

如果你曾这样构建:

docker build \
  --build-arg HTTP_PROXY=http://proxy:port \
  --build-arg HTTPS_PROXY=http://proxy:port .

👉 解决方法:
重新构建 不带 build-arg

docker build --no-cache .

七、清除系统环境变量代理(容易被忽略)

1️⃣ 查看当前代理

env | grep -i proxy

2️⃣ 临时清除(当前 shell)

unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY

3️⃣ 永久清除

检查并删除以下文件中的代理配置:

~/.bashrc
~/.bash_profile
~/.profile
/etc/environment
/etc/profile

八、彻底排查清单(推荐顺序)

☑ systemd Docker daemon
☑ ~/.docker/config.json
☑ docker-compose.yml
☑ Dockerfile
☑ 容器是否重建
☑ shell 环境变量

九、快速“一键”清除 Docker 代理脚本(可选)

sudo rm -f /etc/systemd/system/docker.service.d/*.conf
rm -f ~/.docker/config.json
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY
sudo systemctl daemon-reload
sudo systemctl restart docker

十、总结

层级是否需要重启
Docker daemon✅ 必须
容器✅ 必须重建
docker-compose✅ up/down
shell 环境❌ 新 shell 即可

如果你需要,我可以帮你:

  • 写成 公司标准 SOP
  • 输出 清除代理 + 重新配置代理 的完整脚本
  • 排查 “明明清了代理却还在走代理” 的疑难问题
最后修改:2025 年 12 月 17 日
反正没人给,你也爱给不给吧。