扩展 CouchDB Docker 图片

Extending CouchDB Docker image

我正在尝试扩展 CouchDB docker 图像以预填充 CouchDB(使用初始数据库、设计文档等)。

为了创建一个名为 db 的数据库,我首先尝试了这个初始 Dockerfile:

FROM couchdb
RUN curl -X PUT localhost:5984/db

但构建失败,因为 couchdb 服务在构建时尚未启动。所以我把它改成这样:

FROM couchdb
RUN service couchdb start && \ 
  sleep 3 && \                 
  curl -s -S -X PUT localhost:5984/db && \
  curl -s -S localhost:5984/_all_dbs

注:

构建似乎工作正常:

$ docker build . -t test3 --no-cache
Sending build context to Docker daemon  6.656kB
Step 1/2 : FROM couchdb
 ---> 7f64c92d91fb
Step 2/2 : RUN service couchdb start &&   sleep 3 &&   curl -s -S -X PUT localhost:5984/db &&   curl -s -S localhost:5984/_all_dbs
 ---> Running in 1f3b10080595
Starting Apache CouchDB: couchdb.
{"ok":true}
["db"]
Removing intermediate container 1f3b10080595
 ---> 7d733188a423
Successfully built 7d733188a423
Successfully tagged test3:latest

奇怪的是,现在当我将它作为容器启动时,数据库 db 似乎没有保存到 test3 图像中:

$ docker run -p 5984:5984 -d test3
b34ad93f716e5f6ee68d5b921cc07f6e1c736d8a00e354a5c25f5c051ec01e34

$ curl localhost:5984/_all_dbs
[]

大多数标准 Docker 数据库图像都包含一个 VOLUME 行,用于防止使用预填充数据创建派生图像。对于official couchdb image you can see the relevant line in its Dockerfile。与关系数据库映像不同,此映像不支持首次启动时 运行 的脚本。

这意味着您需要从主机或另一个容器进行初始化。如果您可以使用它的 HTTP API 直接与它交互,那么它可能看起来像:

# Start the container
docker run -d -p 5984:5984 -v ... couchdb

# Wait for it to be up
for i in $(seq 20); do
  if curl -s http://localhost:5984 >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

# Create the database
curl -XPUT http://localhost:5984/db