仓库(Repository)是集中存放镜像的地方,又分为公共镜像和私有仓库。
当执行 docker pull xxx 的时候,它实际上是从 registry.docker.com 这个地址去查找,这就是Docker公司提供的公共仓库。在工作中,有时使用类似 Docker Hub 这样的公共仓库可能不方便,不可能把企业项目上传到公共仓库进行管理,所以为了更多管理镜像,用户可以搭建一个本地私有仓库。
搭建私有仓库
docker-registry
是官方提供的工具,可以用于构建私有的镜像仓库,只需把镜像下载下来,运行容器并暴露5000端口,就可以使用。
下载镜像
[root@localhost ~]# docker pull registry:2
运行容器
[root@localhost ~]# docker run -d -v /opt/data/registry:/var/lib/registry -p 5000:5000 --name myregistry registry:2
注:registry服务默认将上传的镜像保存在容器的/var/lib/registry
,使用-v
参数将容器的/var/lib/registry
目录映射到本地/opt/data/registry
目录。即可实现将镜像保存到宿主机/opt/data/registry
目录。
浏览器访问 宿主机IP:5000/v2
,显示 {}
说明registry运行正常。
[root@localhost ~]# curl 127.0.0.1:5000/v2
<a href="/v2/">Moved Permanently</a>.
[root@localhost ~]# curl 127.0.0.1:5000/v2/_catalog
{"repositories":[]}
说明registry部署成功。
上传镜像到私有仓库
先在本机查看已有的镜像
[root@localhost ~]# docker image ls
下载 Docker Hub 官方镜像
[root@localhost ~]# docker pull ubuntu
将镜像标记为要推送到私有仓库
使用 docker tag
将 ubuntu:latest
这个镜像标记为 127.0.0.1:5000/myubuntu:latest
格式为 docker tag IMAGE[:TAG] [REGISTRY_HOST[:REGISTRY_PORT]/]REPOSITORY[:TAG]
[root@localhost ~]# docker tag ubuntu:latest 127.0.0.1:5000/myubuntu:v1
上传镜像到私有仓库
[root@localhost ~]# docker push 127.0.0.1:5000/myubuntu:v1
The push refers to repository [127.0.0.1:5000/myubuntu]
Get 127.0.0.1:5000/v2/: http: server gave HTTP response to HTTPS client
注:上传镜像时报错,http: server gave HTTP response to HTTPS client
出现这个问题原因是:Docker自从1.3.X之后docker registry交互默认使用的是HTTPS,但是搭建私有镜像默认使用的是HTTP服务,所以与私有仓库交互时出现以上错误。
解决办法:
在所有需要访问私有仓库的客户端上
编辑 /etc/docker/daemon.json
{
"exec-opts": [
"native.cgroupdriver=systemd"
],
"registry-mirrors": [
"hub-mirror.c.163.com",
"mirror.baidubce.com"
],
"insecure-registries": [
"127.0.0.1:5000"
]
}
重启生效:
[root@localhost ~]# systemctl daemon-reload
[root@localhost ~]# systemctl restart docker
再次上传,问题解决
[root@localhost ~]# docker push 127.0.0.1:5000/myubuntu:v1
用 curl
查看仓库中的镜像
[root@localhost ~]# curl 127.0.0.1:5000/v2/_catalog
{"repositories":["myubuntu"]}
这里可以看到 {"repositories":["myubuntu"]}
,表明镜像已经被成功上传了。
先删除已有镜像,再尝试从私有仓库中下载这个镜像。
[root@localhost ~]# docker image rm 127.0.0.1:5000/myubuntu:v1
[root@localhost ~]# docker pull 127.0.0.1:5000/myubuntu:v1
[root@localhost ~]# docker image ls
停止私有仓库
停止仓库并删除所有数据
[root@localhost ~]# docker container stop myregistry && docker container rm -v registry