😸

MongoDBをDockerで試してみる

2022/10/20に公開

背景

MongoDBを触ってみたくなったのでDockerで色々試してみる。

前提

Dockerがインストールされていること。

手順

1. コンテナ作成

下記のコマンドで、Docker内でコンテナを作成します。
※最初の場合は、mongoイメージのpullが実行されるため少しダウンロードが実行されます。

docker run -itd \
        -e MONGO_INITDB_ROOT_USERNAME=root \
        -e MONGO_INITDB_ROOT_PASSWORD=pass \
        -p 27017:27017 \
        --name mongo \
        mongo 

各引数の意味は下記です。自由に編集してください。
-e MONGO_INITDB_ROOT_USERNAME=root:ユーザ名を指定しています。
-e MONGO_INITDB_ROOT_PASSWORD=pass:パスワードを指定しています。
-p 27017:27017:ホスト側で共有するポートを指定しています。(外部から接続しない場合は不要です。)
--name mongo:コンテナ名を指定しています。

このコマンドを実行すると、下記のようにDocker内にmongoが存在している事がわかります。

$ docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                      NAMES
080c60afc116   mongo     "docker-entrypoint.s…"   3 seconds ago   Up 2 seconds   0.0.0.0:27017->27017/tcp   mongo

補足

このコマンドで起動したコンテナは自動再起動が有効になっていません。
PCを再起動などした場合、終了した状態で起動します。

コンテナを再起動したい場合は、docker start mongoで起動をしてください。
嫌な場合はコンテナ生成時に --restart=alwaysオプションを追加してください。
自動再起動が有効となります。

2. コンテナに入って操作

コンテナが起動している場合は、下記のコマンドでコンテナの内部に入る事ができます。

$ docker exec -it mongo bash
root@080c60afc116:/# 
root@080c60afc116:/# ls
bin  boot  data  dev  docker-entrypoint-initdb.d  etc  home  js-yaml.js  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

この状態でDocker内のコンテナ内部でbashコマンドを実行する事ができます。
私達はmongodbに接続したいのでmongosh -u root -p passというコマンドを実行します。

-u root:ユーザ名を指定しています。
-p pass:パスワードを指定しています。

root@080c60afc116:/# mongosh -u root -p pass
Current Mongosh Log ID: 63509dd7a7d04257e3ab28b4
Connecting to:          mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
Using MongoDB:          6.0.2
Using Mongosh:          1.6.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2022-10-20T00:48:28.347+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2022-10-20T00:48:28.878+00:00: vm.max_map_count is too low
------

------
   Enable MongoDB's free cloud-based monitoring service, which will then receive and display
   metrics about your deployment (disk utilization, CPU, operation statistics, etc).
   
   The monitoring data will be available on a MongoDB website with a unique URL accessible to you
   and anyone you share the URL with. MongoDB may use this information to make product
   improvements and to suggest MongoDB products and deployment options to you.
   
   To enable free monitoring, run the following command: db.enableFreeMonitoring()
   To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
------
test> 

この状態で、mongoDBのコマンドを送ることができるようになりました。

3. お試しコマンド

DBに新しいデータを作成して参照してみようと思います。

データ作成

usersというテーブル内に、{username:"hashito"}を持つデータを書き込みます。

test> db.users.insert({username:"hashito"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("63509ddb39e7cde9bce5f310") }
}

MongoDBではテーブルなどはアクセスした瞬間に自動的に生成されます。
生成を行いたくない場合はstaticなどを宣言しておく必要があるようです。

データ参照

次は、追加したデータを参照してみます。

test> db.users.find()
[ { _id: ObjectId("63509ddb39e7cde9bce5f310"), username: 'hashito' } ]

MongoDBではデータはキーと一緒に保存されています。

感想

とりあえず、今回はDockerコンテナを作成して触るところまでをやってみました。
結構かんたんに色々できそうな気はしています。
少し今更感がありますが、引き続き学習していく予定です…

Discussion