I’m trying to automate the setup of my MongoDB container by running a shell script during the docker-compose up process. However, the script either fails to execute or the MongoDB service isn't ready when the script triggers, leading to "Connection Refused" errors. How do I properly sequence a script to run after the database has initialized, and where is the best place to store these scripts within the Docker filesystem?
3 answers
Make sure your shell script has the correct line endings! If you created the script on Windows, the \r\n characters will cause a "file not found" or "binary file" error inside the Linux-based Docker container.
The most frequent issue is trying to run scripts via CMD in a Dockerfile, which often executes before the MongoDB daemon is actually ready to accept connections. The "official" and most reliable way to handle this is by placing your .sh or .js scripts into the /docker-entrypoint-initdb.d/ directory. When the container starts for the first time, the MongoDB entrypoint script automatically scans this folder and executes files in alphabetical order.
Important Note: These scripts only run if the /data/db directory is empty. If you’ve already started the container once, you must clear your persistent volume for the initialization scripts to trigger again.
If I’m running a separate application container (like a Node.js app) that needs to run a migration script against the MongoDB container, should I use depends_on with a healthcheck?
Absolutely, David. Using depends_on alone only ensures the container starts, not that the database is ready. You should define a healthcheck in your MongoDB service (using mongosh --eval 'db.adminCommand("ping")') and then set your app container to wait for the service_healthy condition. This prevents your app's shell scripts from crashing due to a closed port.