0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

docker-containerでmongodbにpymongoから繋ぐまで

Last updated at Posted at 2022-05-08

TL;DR

ローカルでpymongoの動作確認するためのdocker-composeを作成した。
docker-compose.ymlをローカルに保存して、upした後下のexecからのフローでpymongoの簡単な確認ができる。

docker-compose up -d
docker-compose exec app /bin/bash
docker-compose.yml
version: '3.7'
services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    ports:
      - 27017:27017
    volumes:
      - ./db:/data/db
      - ./configdb:/data/configdb
    networks:
      - default


  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
    networks:
      - default
  app:
    image: python3.8
    depends_on:
      - mongo
    tty: true
    networks:
      - default

networks:
  default:
    driver: bridge
pip install --upgrade pip
pip install ipython pymongo

ipythonから接続を確認する

docker-compose ps
docker-compose exec app /bin/bash
pip install --upgrade pip
pip install ipython pymongo
ipython

ipythonの中に入ると、[project_name]の中身はdocker containerの名前で下で確認できる。

client = MongoClient('mongodb://[project_name]_mongo_1', username='root', password='example')
db = client.test
collection = db.test
accounts = [{'account_id': 100002, 'limit': 9000, 'products': ['TEST2', 'TEST2-1']}]
result = collection.insert_many(accounts)
account = collection.find_one({"account_id": 100002})

accountを確認すると、入れたものが入ってる。
MongoClient'mongodb://[project_name]_mongo_1'は下のリンクが参考になる
docker-compose ps
で確認した、container nameから引っ張ってくる。

                Name                              Command               State            Ports
--------------------------------------------------------------------------------------------------------
[project_name]_app_1             python3                          Up
[project_name]_mongo-express_1   tini -- /docker-entrypoint ...   Up      0.0.0.0:8081->8081/tcp
[project_name]_mongo_1           docker-entrypoint.sh mongod      Up      0.0.0.0:27017->27017/tcp

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?