在Ubuntu上搭建私有仓库前,需先安装Docker。推荐使用Docker CE(社区版),步骤如下:
sudo apt update
sudo apt install apt-transport-https ca-certificates curl software-properties-common -y
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "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/null
sudo apt update && sudo apt install docker-ce -y
sudo systemctl start docker && sudo systemctl enable docker
Docker官方提供了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)。