Merge pull request #926 from thewilloftheshadow/feat/mongo-replica-sets

feat: mongo replica sets
This commit is contained in:
Mauricio Siu
2024-12-25 23:37:29 -06:00
committed by GitHub
6 changed files with 4353 additions and 6 deletions

View File

@@ -28,17 +28,66 @@ export const buildMongo = async (mongo: MongoNested) => {
databasePassword,
command,
mounts,
replicaSets,
} = mongo;
const defaultMongoEnv = `MONGO_INITDB_ROOT_USERNAME=${databaseUser}\nMONGO_INITDB_ROOT_PASSWORD=${databasePassword}${
const startupScript = `
#!/bin/bash
${
replicaSets
? `
mongod --port 27017 --replSet rs0 --bind_ip_all &
MONGOD_PID=$!
# Wait for MongoDB to be ready
while ! mongosh --eval "db.adminCommand('ping')" > /dev/null 2>&1; do
sleep 2
done
# Check if replica set is already initialized
REPLICA_STATUS=$(mongosh --quiet --eval "rs.status().ok || 0")
if [ "$REPLICA_STATUS" != "1" ]; then
echo "Initializing replica set..."
mongosh --eval '
rs.initiate({
_id: "rs0",
members: [{ _id: 0, host: "localhost:27017", priority: 1 }]
});
// Wait for the replica set to initialize
while (!rs.isMaster().ismaster) {
sleep(1000);
}
// Create root user after replica set is initialized and we are primary
db.getSiblingDB("admin").createUser({
user: "${databaseUser}",
pwd: "${databasePassword}",
roles: ["root"]
});
'
else
echo "Replica set already initialized."
fi
`
: ""
}
${command ?? "wait $MONGOD_PID"}`;
const defaultMongoEnv = `MONGO_INITDB_ROOT_USERNAME=${databaseUser}\nMONGO_INITDB_ROOT_PASSWORD=${databasePassword}${replicaSets ? "\nMONGO_INITDB_DATABASE=admin" : ""}${
env ? `\n${env}` : ""
}`;
const resources = calculateResources({
memoryLimit,
memoryReservation,
cpuLimit,
cpuReservation,
});
const envVariables = prepareEnvironmentVariables(
defaultMongoEnv,
mongo.project.env,
@@ -56,12 +105,17 @@ export const buildMongo = async (mongo: MongoNested) => {
Image: dockerImage,
Env: envVariables,
Mounts: [...volumesMount, ...bindsMount, ...filesMount],
...(command
...(replicaSets
? {
Command: ["/bin/sh"],
Args: ["-c", command],
Command: ["/bin/bash"],
Args: ["-c", startupScript],
}
: {}),
: {
...(command && {
Command: ["/bin/bash"],
Args: ["-c", command],
}),
}),
},
Networks: [{ Target: "dokploy-network" }],
Resources: {
@@ -90,6 +144,7 @@ export const buildMongo = async (mongo: MongoNested) => {
: [],
},
};
try {
const service = docker.getService(appName);
const inspect = await service.inspect();