[Docker] Persistir mudanças feitas durante build

Estou tentando construir uma imagem no Docker que é simplesmente a original do MongoDB com um usuário admin adicionado mas estou tendo problemas. Alguém que manja de Docker pode me ajudar?

Meu Dockerfile está assim:

FROM mongo:latest

RUN mongod --fork --logpath /var/log/mongodb.log \
    && mongo admin --eval " \
        db.createUser({ user: 'root', pwd: 'root', roles: [ 'root' ]}); \
        db.shutdownServer() \
    "

CMD ["mongod", "--auth"]

O comando docker build --tag lvbarbosa/task-db ., executado no diretório do Dockerfile, me dá o seguinte output:

Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM mongo:latest
latest: Pulling from library/mongo
5233d9aed181: Pull complete 
5bbfc055e8fb: Pull complete 
aaf85a329dc4: Pull complete 
1360aef7d266: Pull complete 
9cb9d47c5d80: Pull complete 
80e12bf92c3c: Pull complete 
fd3679b936e6: Pull complete 
5cb080b90ae5: Pull complete 
46cf38664c75: Pull complete 
59693a4ecb90: Pull complete 
dff9fc3b430d: Pull complete 
Digest: sha256:90b78c44a58d6d927f96baabea3212d8c756017846715b630044aefcabcab2eb
Status: Downloaded newer image for mongo:latest
 ---> 6833171fe0ad
Step 2/3 : RUN mongod --fork --logpath /var/log/mongodb.log     && mongo admin --eval "         db.createUser({ user: 'root', pwd: 'root', roles: [ 'root' ]});         db.shutdownServer()     "
 ---> Running in 6c1a5530b7b6
about to fork child process, waiting until server is ready for connections.
forked process: 10
child process started successfully, parent exiting
MongoDB shell version v3.4.6
connecting to: mongodb://127.0.0.1:27017/admin
MongoDB server version: 3.4.6
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
server should be down...
 ---> 82fa5430003c
Removing intermediate container 6c1a5530b7b6
Step 3/3 : CMD mongod
 ---> Running in 42f240f05661
 ---> 90ec29686438
Removing intermediate container 42f240f05661
Successfully built 90ec29686438
Successfully tagged lvbarbosa/task-db:latest

Em seguida, eu crio um container com essa imagem com o comando docker run --detach --publish 27017:27017 --name task-db lvbarbosa/task-db e tento conectar ao mongo pelo terminal no meu host com mongo admin -u root -p root e o login falha. Dá um erro de user not found.

Parece que as mudanças feitas durante o build time dentro do DB não aparecem no runtime. Mas eu tinha aprendido que o que você faz no union file system durante o build é persistido. Estou confuso. O log completo do servidor é esse aqui:

2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db 64-bit host=86b7b24efed4
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] db version v3.4.6
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] git version: c55eb86ef46ee7aede3b1e2a5d184a7df4bfb5b5
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1t  3 May 2016
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] modules: none
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten] build environment:
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten]     distmod: debian81
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten]     distarch: x86_64
2017-07-27T13:20:47.687+0000 I CONTROL  [initandlisten]     target_arch: x86_64
2017-07-27T13:20:47.688+0000 I CONTROL  [initandlisten] options: { security: { authorization: "enabled" } }
2017-07-27T13:20:47.690+0000 I STORAGE  [initandlisten] 
2017-07-27T13:20:47.690+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-07-27T13:20:47.690+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-07-27T13:20:47.690+0000 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=3474M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-07-27T13:20:47.719+0000 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2017-07-27T13:20:47.727+0000 I INDEX    [initandlisten] build index on: admin.system.version properties: { v: 2, key: { version: 1 }, name: "incompatible_with_version_32", ns: "admin.system.version" }
2017-07-27T13:20:47.727+0000 I INDEX    [initandlisten] 	 building index using bulk method; build may temporarily use up to 500 megabytes of RAM
2017-07-27T13:20:47.728+0000 I INDEX    [initandlisten] build index done.  scanned 0 total records. 0 secs
2017-07-27T13:20:47.728+0000 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.4
2017-07-27T13:20:47.728+0000 I NETWORK  [thread1] waiting for connections on port 27017
2017-07-27T13:20:48.963+0000 I NETWORK  [thread1] connection accepted from 172.17.0.1:45804 #1 (1 connection now open)
2017-07-27T13:20:48.963+0000 I NETWORK  [conn1] received client metadata from 172.17.0.1:45804 conn1: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.6" }, os: { type: "Darwin", name: "Mac OS X", architecture: "x86_64", version: "17.0.0" } }
2017-07-27T13:20:48.970+0000 I ACCESS   [conn1] SCRAM-SHA-1 authentication failed for root on admin from client 172.17.0.1:45804 ; UserNotFound: Could not find user root@admin
2017-07-27T13:20:48.972+0000 I -        [conn1] end connection 172.17.0.1:45804 (1 connection now open)

O Dockerfile do mongo tá no github deles.

Descobri o porquê da mudança desaparecer.

No Dockerfile original, o /data/db é declarado como VOLUME. Na documentação, tem falando:

  • Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded

A adição do usuário altera os arquivos dentro da pasta /data/db e por isso a mudança não é persistida.