From d1234e37acf815f212f99bef6f3621e704fd1fee Mon Sep 17 00:00:00 2001 From: berkay Date: Sun, 20 Apr 2025 11:49:44 +0300 Subject: [PATCH] updated with simple init.js --- docker-compose.yml | 6 +++--- init-mongo-simple.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 init-mongo-simple.js diff --git a/docker-compose.yml b/docker-compose.yml index 3cd1391..f1a0165 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,17 +7,17 @@ services: environment: - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USERNAME:-admin} - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD:-password} + - MONGO_INITDB_DATABASE=appdb volumes: - mongodb_data:/data/db - mongodb_config:/data/configdb - - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro - - ./keyfile:/data/keyfile:ro # Add this for replica set auth + - ./init-mongo-simple.js:/docker-entrypoint-initdb.d/init-mongo.js:ro ports: - "27017:27017" # Expose MongoDB port to external machines # Use a simpler configuration without replica set for now command: ["--auth", "--bind_ip_all"] healthcheck: - test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/admin --quiet + test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/admin -u ${MONGO_ROOT_USERNAME:-admin} -p ${MONGO_ROOT_PASSWORD:-password} --quiet interval: 10s timeout: 5s retries: 5 diff --git a/init-mongo-simple.js b/init-mongo-simple.js new file mode 100644 index 0000000..bb62e71 --- /dev/null +++ b/init-mongo-simple.js @@ -0,0 +1,37 @@ +// Simple initialization script that only creates users +print("Starting MongoDB user initialization..."); + +// Wait for MongoDB to be ready +db = db.getSiblingDB('admin'); +print("Connected to admin database"); + +// Create application database and user +db = db.getSiblingDB('appdb'); +print("Switched to appdb database"); + +try { + db.createUser({ + user: 'appuser', + pwd: 'apppassword', + roles: [ + { role: 'readWrite', db: 'appdb' } + ] + }); + print("Successfully created appuser"); +} catch (err) { + print("Error creating appuser: " + err.message); +} + +// Verify user was created +let users = db.getUsers(); +print("Users in appdb: " + JSON.stringify(users)); + +// Also create a test collection and document to verify database is working +try { + db.test.insertOne({ name: "test", created: new Date() }); + print("Successfully inserted test document"); +} catch (err) { + print("Error inserting test document: " + err.message); +} + +print("MongoDB initialization completed!");