Thursday, July 16, 2015

配置 Docker 镜像下载的本地 mirror 服务

Docker registry 工具现在已经很好的支持了 mirror 功能,使用它可以配置一个本地的 mirror 服务,将 pull 过的镜像 cache 在本地,这样其它主机再次 pull 的时候会极大提高响应速度。

使用 docker-compose 启动 registry mirror 服务

以 ubuntu 为例,首先要安装 docker 和 docker-compose。

安装 docker

$ sudo wget -qO- https://get.docker.com/ | sh

安装 docker-compose

$ sudo pip install docker-compose
之后,在本地创建 /opt/data/registry 目录,作为镜像文件的存储位置;创建 /opt/data/redis 目录,作为 redis 数据的存放位置。
编写一个 docker-compose.yml 文件。
该文件将启动一个 registry 容器监听在本地的 5000 端口,并使用一个 redis 容器作为小文件的 cache。
内容如下:
# This compose file will start 2 containers: registry and redis.
# registry container will listen on host port 5000,
# and depend on the redis container as the cache scheme.


registry:
    image: registry:latest
    cpu_shares: 10
    environment:
        - STANDALONE=false
        - MIRROR_SOURCE=https://registry-1.docker.io
        - MIRROR_SOURCE_INDEX=https://index.docker.io
        - CACHE_REDIS_HOST=redis
        - CACHE_REDIS_PORT=6379
        - DEBUG=false
    hostname: docker-registry
    links:
        - redis:redis
    mem_limit: 512m
    ports:
        - "5000:5000"
    privileged: false
    restart: always
    user: root
    volumes:
        - /opt/data/registry:/tmp/registry

redis:
    image: redis:3.0
    cpu_shares: 10
    expose:
        - "6379"
    mem_limit: 512m
    restart: always
    volumes:
        - /opt/data/redis:/data
之后,启动服务。
$ docker-compose up -d

配置主机使用 mirror 服务

在其它主机上,配置 docker 的配置文件(例如 /etc/default/docker),添加一行:
DOCKER_OPTS="$DOCKER_OPTS --registry-mirror http://localmirror:5000"
其中 localmirror 替换为刚才配置了 mirror 服务的机器地址。
之后重启 docker 服务。
$ sudo service docker restart

测试

随便下载一个镜像,比如 ubuntu:14.04,正常需要十几分钟。
删除下载的镜像,再次下载,一分钟不到,就下载完毕了。