Docker compose allows you to manage multiple containers as a single unit. However, it can be challenging to execute commands only once, especially when dealing with data-dependent processes like setting up databases.
In your compose file, you've created a "mongodata" data volume container to store the MongoDB data. This container is essentially a paused container that simply mounts the assigned volume.
Entrypoint Script for One-Time Initialization:
To prevent the "-setup" command from executing multiple times, you can employ an entrypoint script within the "my_project" container. This script will check if the database has been initialized and perform the setup only if necessary.
Example:
#!/bin/sh # Check if database is initialized if test -f /app/initialized; then # Database already initialized, skip setup echo "Database already initialized" else # Initialize database ./my-project -setup touch /app/initialized fi # Start the application exec /go/bin/my_project
Docker 1.9 and later provide native volume management capabilities, eliminating the need for "data-only" containers. You can simplify your compose file as follows:
services: mongo: image: mongo:latest volumes: - mongodata:/data/db ports: - "28001:27017" command: --smallfiles --rest --auth
In the entrypoint script, it's essential to handle potential delays in database availability. The script should retry connection attempts if the database is not yet accessible.
The above is the detailed content of How to Run a Command Once in Docker Compose for Data-Dependent Processes?. For more information, please follow other related articles on the PHP Chinese website!