在Ubuntu上搭建私有仓库前,需先安装Docker。推荐使用Docker CE(社区版),步骤如下:
sudo apt updatesudo apt install apt-transport-https ca-certificates curl software-properties-common -ycurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpgecho "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/nullsudo apt update && sudo apt install docker-ce -ysudo systemctl start docker && sudo systemctl enable dockerDocker官方提供了registry:2镜像(版本2为当前主流),用于快速搭建私有仓库:
docker pull registry:2
使用docker run命令启动容器,关键参数说明:
-d:后台运行容器;-p 5000:5000:将容器的5000端口映射到主机5000端口(默认仓库端口);--name registry:容器名称设为registry(便于管理);-v /opt/docker-registry/data:/var/lib/registry:将主机/opt/docker-registry/data目录挂载到容器内/var/lib/registry(持久化存储镜像,避免容器删除后数据丢失)。完整命令:
docker run -d -p 5000:5000 --name registry -v /opt/docker-registry/data:/var/lib/registry registry:2
默认情况下,Docker不信任非HTTPS的私有仓库(如本地的localhost:5000)。需修改Docker守护进程配置,添加私有仓库地址到信任列表:
sudo vim /etc/docker/daemon.json{
"insecure-registries": ["localhost:5000"]
}
:wq),然后重启Docker服务使配置生效:sudo systemctl restart docker将本地的hello-world镜像(或其他镜像)标记为私有仓库的地址格式:<私有仓库地址>/<镜像名称>:<标签>。例如:
docker tag hello-world:latest localhost:5000/hello-world:latest
使用docker push命令将标记后的镜像推送到私有仓库:
docker push localhost:5000/hello-world:latest
若推送成功,终端会显示类似latest: digest: sha256:... size: 1336的信息
使用docker pull命令从私有仓库拉取镜像,验证是否可用:
docker pull localhost:5000/hello-world:latest
若拉取成功,说明私有仓库功能正常
通过浏览器或curl命令访问私有仓库的API,查看已存储的镜像列表:
http://<私有仓库服务器IP>:5000/v2/_catalog(如localhost:5000/v2/_catalog);curl命令:curl http://localhost:5000/v2/_catalog。repositories字段,列出所有存储的镜像名称ufw allow 5000或云服务器安全组配置);daemon.json移除insecure-registries并配置证书路径);/opt/docker-registry/data)有足够存储空间,且权限正确(chown -R 1000:1000 /opt/docker-registry/data,1000为Docker默认用户ID)。