local-mongo container를
docker mongo의 rs.initiate()
를 config 하는 방법입니다.
https://velog.io/@youngkiu/MongoDB-Replica-Set-for-Prisma와 같이 하면, app src 상태에서는 localhost로 잘 접속되지만,
app container 상태에서는 localhost가 app container 자신이 되어 접속되지 않는다.
그래서, local PC의 /etc/hosts
에 다음을 추가한다.
$ sudo vi /etc/hosts
127.0.0.1 local-mongo
그리고, rs.initiate(config)
시 host
를 local-mongo
로 사용한다.
$ docker-compose up mongo
$ docker exec -it local-mongo bash
root@f9b5d1203ce4:/# mongosh -u <MONGO_INITDB_ROOT_USERNAME> -p <MONGO_INITDB_ROOT_PASSWORD>
Current Mongosh Log ID: 64338c90c75cf191f8a3d93d
Connecting to: mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.8.0
Using MongoDB: 5.0.15
Using Mongosh: 1.8.0
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.
------
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> config = {
"_id" : "rs0", // docker-compose에 있는 replSet과 동일하게
"members" : [
{
"_id" : 0,
"host" : "local-mongo:27017"
}
]
}
{ _id: 'rs0', members: [ { _id: 0, host: 'local-mongo:27017' } ] }
test> rs.initiate(config)
{ ok: 1 }
rs0 [direct: other] test>
/etc/hosts 설정없이 하려고, 다음과 같이 시도해 보았으나 에러가 발생하였습니다.
test> config = {
... "_id" : "rs0",
... "members" : [
... {
... "_id" : 0,
... "host" : "127.0.0.1:27017"
... },
... {
... "_id" : 1,
... "host" : "local-mongo:27017"
... }
... ]
... }
{
_id: 'rs0',
members: [
{ _id: 0, host: '127.0.0.1:27017' },
{ _id: 1, host: 'local-mongo:27017' }
]
}
test> rs.initiate(config)
MongoServerError: Either all host names in a replica set configuration must be localhost references, or none must be; found 1 out of 2