在国内的服务器上使用Docker时会经常遇到网络不稳定的问题,以下是3种在Docker使用场景中常见网络问题的解决方案,分别是
拉取镜像失败有2种处理方法,分别是:
编辑:/etc/docker/daemon.json
{
"registry-mirrors": [
"https://registry.docker-cn.com",
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}
重启docker应用设置
sudo systemctl daemon-reload
sudo systemctl restart docker
再尝试拉取镜像,可以看到速度非常快
佳如更换源在某些场景下也不被允许,那么可以通过网络加速代理来拉取镜像
可以在拉取前执行网络代理,假设本地8080端口是用于加速的网络代理
export http_proxy=http://localhost:8080
export https_proxy=http://localhost:8080
这样拉取镜像时就会走localhost:8080
的代理,但仅对当前会话生效,在退出后就不再生效
每一次都设置也显得非常麻烦,那么将其添加到启动参数中就不用每次拉取前都设置代理
编辑:/etc/systemd/system/multi-user.target.wants/docker.service
...
[Service]
Environment="HTTP_PROXY=http://localhost:8080"
Environment="HTTPS_PROXY=http://localhost:8080"
...
在service节点中添加环境变量,这样每一次拉取都会走网络代理
重启docker以使上述设置生效
sudo systemctl daemon-reload
sudo systemctl restart docker
但请注意,这个方法修改systemmd的配置单除了对拉取镜像生效,也会影响构建镜像以及容器运行,请谨慎操作
构建镜像时,想使用代理通常有3种方案
--build-arg
参数docker允许在构建过程中传入参数,我们可以在Dockerfile中定义
...
ARG http_proxy
ARG https_proxy
ENV http_proxy=${http_proxy}
ENV https_proxy=${https_proxy}
...
然后在Docker时,传入网络代理参数,但这里无法使用localhost:8080
,因为构建阶段默认是网络隔离的,需要借助局域网内的其他具备代理的服务
sudo docker build --build-arg http_proxy=http://192.168.1.1:8080 \
--build-arg https_proxy=http://192.168.1.1:8080 \
-t your-image .
这种方法的好处是仅对单个镜像构建生效,不会影响全局的镜像构建
创建或编辑:~/.docker/config.json
{
"proxies": {
"default": {
"httpProxy": "http://localhost:8080",
"httpsProxy": "http://localhost:8080"
}
}
}
以上设置会让所有的镜像构建阶段都使用网络代理,但不影响拉取镜像以及容器运行
容器需要使用网络代理一般有如下方法:
-e
参数在Docker运行时,可以通过-e
参数设置环境变量
sudo docker run -e http_proxy=http://localhost:8080 \
-e https_proxy=http://localhost:8080 \
your-image
这种方法同样仅对单个容器生效,不会影响其他容器
编辑:/etc/systemd/system/docker.service.d/http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://localhost:8080"
Environment="HTTPS_PROXY=http://localhost:8080"
这个方法同样会影响拉取镜像、构建镜像以及容器运行,请谨慎使用