MongoDB with Replica Sets enabled: container exits with code 0 and restarts in a loop (generated startup script never waits on mongod)

Abierto Apto para principiantes
#6,051 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@ghazy2001 ya está trabajando en esto.

Desde el 19/11/2026.

  • #6082 de @ghazy2001 — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
68/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
bash, docker, mongodb, typescript
Área
backend, database

Línea de trabajo

Lee packages/server/src/utils/databases/mongo.ts cerca de la línea 84 y sigue cómo la pestaña Advanced guarda un valor Command vacío en apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx. Comprueba cómo gestiona el script de inicio generado para el replica set un Command vacío; el fallo notificado es que termina después de la inicialización en lugar de mantener mongod en ejecución. Se considerará terminado cuando el script mantenga la tarea en ejecución si Command está vacío y la reproducción notificada con MongoDB 8.0 y replica sets deje de entrar en un bucle.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug
To Reproduce
  1. Create a MongoDB database in Dokploy with Replica Sets enabled.
  2. Set the image to mongo:8.0 on the Advanced tab and save. Leave Command and Args empty.
  3. Deploy.
  4. Run docker service ps <appName> --no-trunc on the server.
Current vs. Expected behavior

Expected: one task stays Running, with mongod as a long-lived process.

Actual: the service restarts in a loop about every 13 seconds.

  • docker service ps <appName> --no-trunc shows a new task every ~13 s, each ending Shutdown / Complete. docker ps -a shows Exited (0).
  • mongod logs a healthy startup each time (becomes PRIMARY, "startup complete", no fatal errors). The container log then ends with Replica set already initialized. and the container exits.

docker service inspect shows Command: ["/bin/bash"] with a -c script. Redacted copy of the generated script:

#!/bin/bash

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: "<appName>:27017", priority: 1 }]
	});
	while (!rs.isMaster().ismaster) { sleep(1000); }
	db.getSiblingDB("admin").createUser({
		user: "<REDACTED>",
		pwd: "<REDACTED>",
		roles: ["root"]
	});
	'
else
	echo "Replica set already initialized."
fi

The script ends after the if/else. There is no wait $MONGOD_PID at the end, so bash (PID 1) exits with code 0 and mongod is killed with it.

Likely cause (hypothesis, from reading the source): in packages/server/src/utils/databases/mongo.ts#L84, the last line of the script is:

${command ?? "wait $MONGOD_PID"}

The Advanced tab form (show-custom-command.tsx#L138) saves command: "" when the field is left empty. "" ?? "wait $MONGOD_PID" evaluates to "", so the wait line is dropped. I think this is why it works for some users: the bug only appears once that form has been saved, for example to change the image. A database whose command is still NULL keeps the wait.

Possible fix: use command || "wait $MONGOD_PID", or command?.trim() ? command : "wait $MONGOD_PID". Saving null from the form when Command is empty would also work.

Workaround: set Command on the Advanced tab to:

trap 'kill -TERM $MONGOD_PID' TERM INT; wait $MONGOD_PID; wait $MONGOD_PID

After that, one task stays Running. docker service update --force <appName> gives a clean Shutdown of the old task (not Failed) and a healthy new one.

Setting Command to mongod makes things worse. With replica sets on, Command replaces the final wait line of the script instead of the container command. A second mongod starts and fails with "Address already in use" (exit code 48).

Provide environment information
Operating System:
  OS: Ubuntu 24.04.5 LTS
  Arch: x86_64
Dokploy version: v0.31.4
VPS Provider: Contabo
Docker: 29.9.3
Swarm: active
What applications/services are you trying to deploy?
  MongoDB (mongo:8.0) with Replica Sets enabled
Which area(s) are affected? (Select all that apply)

Databases

Are you deploying the applications where Dokploy is installed or on a remote server?

Same server where Dokploy is installed

Additional context

Related observations. I can file these separately if you prefer:

  1. The Command field means something different with Replica Sets on. It replaces the script's final wait $MONGOD_PID line instead of the container command. Nothing in the UI says so.
  2. Credentials are not enforced in replica-set mode. mongod is started directly with --port 27017 --replSet rs0 --bind_ip_all, with no --auth or --keyFile. The root user is created, but the log says "Access control is not enabled for the database", and unauthenticated mongosh can list databases. Users who enter credentials in the UI will expect them to be enforced.
  3. The root password is embedded in the service spec in plain text (visible via docker service inspect, in the -c script). It is also interpolated inside a single-quoted bash string, so (hypothesis, untested) a password containing ' would break the script.
Will you send a PR to fix it?

Maybe. I may be able to send a one-line fix if I have time, but I'm not sure yet.

Lenguaje dominante
TypeScript
Estrellas
38.8k
Forks
3.2k
Merge medio
1 d 10 h
PR fusionados (30 d)
110

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Dokploy/dokploy

Todos los issues de Dokploy/dokploy

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.