Q:

Extending CouchDB Docker image

I’m trying to extend CouchDB docker image to pre-populate CouchDB (with initial databases, design documents, etc.).  
In order to create a database named db, I first tried this initial Dockerfile:
FROM couchdb
RUN curl -X PUT localhost:5984/db

but the build failed since couchdb service is not yet started at build time.  So I changed it into this:
FROM couchdb
RUN service couchdb start && \ 
  sleep 3 && \                 
  curl -s -S -X PUT localhost:5984/db && \
  curl -s -S localhost:5984/_all_dbs

Note:

the sleep was the only way I found to make it work, since it did not work with curl option --connect-timeout,
the second curl is only to check that the database was created. 

The build seems to work fine:
$ 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

What is weird is that now when I start it as a container, database db does not seem to be saved into test3 image:
$ docker run -p 5984:5984 -d test3
b34ad93f716e5f6ee68d5b921cc07f6e1c736d8a00e354a5c25f5c051ec01e34

$ curl localhost:5984/_all_dbs
[]

A:

Most of the standard Docker database images include a VOLUME line that prevents creating a derived image with prepopulated data.   For the official couchdb image you can see the relevant line in its Dockerfile.   Unlike the relational-database images, this image doesn’t have any support for scripts that run at first startup. 
That means you need to do the initialization from the host or from another container.   If you can directly interact with it using its HTTP API, then this could look like:
# 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

