Docker 容器不会自动继承宿主机的代理设置,容器内部访问外网需要显式注入代理环境变量。
在 docker-compose.yml 中注入代理
在需要走代理的服务 environment 中添加:
services:
web:
image: nginx:latest
environment:
http_proxy: http://172.17.0.1:7890
https_proxy: http://172.17.0.1:7890
HTTP_PROXY: http://172.17.0.1:7890
HTTPS_PROXY: http://172.17.0.1:7890
NO_PROXY: localhost,127.0.0.1,172.17.0.0/16
同时写大写和小写两种形式,因为不同程序读取的环境变量名不一致(curl/wget 读小写,Java/Python 可能读大写)。
Linux 宿主机代理地址
Linux 下 Docker 默认网桥 IP 是 172.17.0.1,容器内可以用它访问宿主机上运行的代理:
# 先在宿主机验证端口可达
curl 172.17.0.1:7890
更推荐的写法是用 host-gateway,语义更清晰且不依赖具体网桥 IP:
services:
web:
extra_hosts:
- "host.docker.internal:host-gateway"
environment:
http_proxy: http://host.docker.internal:7890
https_proxy: http://host.docker.internal:7890
host.docker.internal 在 macOS/Windows 的 Docker Desktop 中默认可用,Linux 需要通过 extra_hosts 手动映射。
Dockerfile 构建阶段代理
environment 只对运行中的容器生效,docker build 阶段(apt install、pip install、git clone)需要在 Dockerfile 里设置:
FROM ubuntu:24.04
ENV http_proxy=http://host.docker.internal:7890
ENV https_proxy=http://host.docker.internal:7890
RUN apt-get update && apt-get install -y curl
或者构建时通过 --build-arg 传入(更灵活,不会写死到镜像层):
ARG http_proxy
ARG https_proxy
RUN apt-get update && apt-get install -y curl
docker build \
--build-arg http_proxy=http://172.17.0.1:7890 \
--build-arg https_proxy=http://172.17.0.1:7890 \
-t myimage .
常见问题
容器外能上网,容器内不行 → 忘记设置 environment 代理变量。
代理地址用 127.0.0.1 不通 → 容器的 127.0.0.1 指向容器本身而非宿主机,必须用 172.17.0.1 或 host.docker.internal。
https_proxy 写成 https:// → 代理地址的 scheme 必须用 http://,即使是 HTTPS 流量也一样:
HTTPS_PROXY=https://... ← 错误
HTTPS_PROXY=http://... ← 正确