|
| 1 | +# 配置 HTTP/HTTPS 网络代理 |
| 2 | + |
| 3 | +使用Docker的过程中,因为网络原因,通常需要使用 HTTP/HTTPS 代理来加速镜像拉取、构建和使用。下面是常见的三种场景。 |
| 4 | + |
| 5 | +## 为 dockerd 设置网络代理 |
| 6 | + |
| 7 | +"docker pull" 命令是由 dockerd 守护进程执行。而 dockerd 守护进程是由 systemd 管理。因此,如果需要在执行 "docker pull" 命令时使用 HTTP/HTTPS 代理,需要通过 systemd 配置。 |
| 8 | + |
| 9 | +- 为 dockerd 创建配置文件夹。 |
| 10 | +``` |
| 11 | +sudo mkdir -p /etc/systemd/system/docker.service.d |
| 12 | +``` |
| 13 | + |
| 14 | +- 为 dockerd 创建 HTTP/HTTPS 网络代理的配置文件,文件路径是 /etc/systemd/system/docker.service.d/http-proxy.conf 。并在该文件中添加相关环境变量。 |
| 15 | +``` |
| 16 | +[Service] |
| 17 | +Environment="HTTP_PROXY=http://proxy.example.com:8080/" |
| 18 | +Environment="HTTPS_PROXY=http://proxy.example.com:8080/" |
| 19 | +Environment="NO_PROXY=localhost,127.0.0.1,.example.com" |
| 20 | +``` |
| 21 | + |
| 22 | +- 刷新配置并重启 docker 服务。 |
| 23 | +``` |
| 24 | +sudo systemctl daemon-reload |
| 25 | +sudo systemctl restart docker |
| 26 | +``` |
| 27 | + |
| 28 | +## 为 docker 容器设置网络代理 |
| 29 | + |
| 30 | +在容器运行阶段,如果需要使用 HTTP/HTTPS 代理,可以通过更改 docker 客户端配置,或者指定环境变量的方式。 |
| 31 | + |
| 32 | +- 更改 docker 客户端配置:创建或更改 ~/.docker/config.json,并在该文件中添加相关配置。 |
| 33 | +``` |
| 34 | +{ |
| 35 | + "proxies": |
| 36 | + { |
| 37 | + "default": |
| 38 | + { |
| 39 | + "httpProxy": "http://proxy.example.com:8080/", |
| 40 | + "httpsProxy": "http://proxy.example.com:8080/", |
| 41 | + "noProxy": "localhost,127.0.0.1,.example.com" |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +- 指定环境变量:运行 "docker run" 命令时,指定相关环境变量。 |
| 48 | + |
| 49 | +| 环境变量 | docker run 示例 | |
| 50 | +| -------- | ---------------- | |
| 51 | +| HTTP_PROXY | --env HTTP_PROXY="http://proxy.example.com:8080/" | |
| 52 | +| HTTPS_PROXY | --env HTTPS_PROXY="http://proxy.example.com:8080/" | |
| 53 | +| NO_PROXY | --env NO_PROXY="localhost,127.0.0.1,.example.com" | |
| 54 | + |
| 55 | +## 为 docker build 过程设置网络代理 |
| 56 | + |
| 57 | +在容器构建阶段,如果需要使用 HTTP/HTTPS 代理,可以通过指定 "docker build" 的环境变量,或者在 Dockerfile 中指定环境变量的方式。 |
| 58 | + |
| 59 | +- 使用 "--build-arg" 指定 "docker build" 的相关环境变量 |
| 60 | +``` |
| 61 | +docker build \ |
| 62 | + --build-arg "HTTP_PROXY=http://proxy.example.com:8080/" \ |
| 63 | + --build-arg "HTTPS_PROXY=http://proxy.example.com:8080/" \ |
| 64 | + --build-arg "NO_PROXY=localhost,127.0.0.1,.example.com" . |
| 65 | +``` |
| 66 | + |
| 67 | +- 在 Dockerfile 中指定相关环境变量 |
| 68 | + |
| 69 | +| 环境变量 | Dockerfile 示例 | |
| 70 | +| -------- | ---------------- | |
| 71 | +| HTTP_PROXY | ENV HTTP_PROXY="http://proxy.example.com:8080/" | |
| 72 | +| HTTPS_PROXY | ENV HTTPS_PROXY="http://proxy.example.com:8080/" | |
| 73 | +| NO_PROXY | ENV NO_PROXY="localhost,127.0.0.1,.example.com" | |
| 74 | + |
0 commit comments