温馨提示×

Ubuntu Docker镜像仓库怎么搭建

小樊
46
2025-10-12 02:25:21
栏目: 智能运维

Ubuntu系统搭建Docker镜像仓库(私有)详细步骤

1. 准备环境:安装Docker

在Ubuntu上搭建私有仓库前,需先安装Docker。推荐使用Docker CE(社区版),步骤如下:

  • 更新软件包索引:sudo apt update
  • 安装必要依赖:sudo apt install apt-transport-https ca-certificates curl software-properties-common -y
  • 添加Docker官方GPG密钥:curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
  • 添加Docker存储库: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
  • 安装Docker CE:sudo apt update && sudo apt install docker-ce -y
  • 启动Docker服务并设置开机自启:sudo systemctl start docker && sudo systemctl enable docker

2. 拉取官方Registry镜像

Docker官方提供了registry:2镜像(版本2为当前主流),用于快速搭建私有仓库:
docker pull registry:2

3. 运行私有仓库容器

使用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

4. 配置Docker信任私有仓库

默认情况下,Docker不信任非HTTPS的私有仓库(如本地的localhost:5000)。需修改Docker守护进程配置,添加私有仓库地址到信任列表:

  • 编辑配置文件:sudo vim /etc/docker/daemon.json
  • 添加以下内容(若文件为空,直接粘贴;若有其他配置,合并后确保JSON格式正确):
    {
      "insecure-registries": ["localhost:5000"]
    }
    
  • 保存并退出(:wq),然后重启Docker服务使配置生效:sudo systemctl restart docker

5. 测试私有仓库功能

5.1 标记本地镜像

将本地的hello-world镜像(或其他镜像)标记为私有仓库的地址格式:<私有仓库地址>/<镜像名称>:<标签>。例如:
docker tag hello-world:latest localhost:5000/hello-world:latest

5.2 推送镜像到私有仓库

使用docker push命令将标记后的镜像推送到私有仓库:
docker push localhost:5000/hello-world:latest
若推送成功,终端会显示类似latest: digest: sha256:... size: 1336的信息

5.3 从私有仓库拉取镜像

使用docker pull命令从私有仓库拉取镜像,验证是否可用:
docker pull localhost:5000/hello-world:latest
若拉取成功,说明私有仓库功能正常

5.4 查看仓库中的镜像列表

通过浏览器或curl命令访问私有仓库的API,查看已存储的镜像列表:

  • 浏览器访问:http://<私有仓库服务器IP>:5000/v2/_catalog(如localhost:5000/v2/_catalog);
  • curl命令:curl http://localhost:5000/v2/_catalog
    返回结果应包含repositories字段,列出所有存储的镜像名称

注意事项

  • 防火墙/安全组:若私有仓库部署在远程服务器,需开放5000端口(如ufw allow 5000或云服务器安全组配置);
  • HTTPS配置:生产环境建议使用HTTPS(可通过Let’s Encrypt申请免费证书,修改daemon.json移除insecure-registries并配置证书路径);
  • 数据持久化:确保挂载的主机目录(如/opt/docker-registry/data)有足够存储空间,且权限正确(chown -R 1000:1000 /opt/docker-registry/data,1000为Docker默认用户ID)。

0