How to Execute One-Time Commands in Docker Compose
To set up a Docker environment where a command needs to be executed only once, such as populating a database, a recommended approach is to utilize an entrypoint script.
Entrypoint Script
Create an entrypoint script within your container image, typically named entrypoint.sh. This script will check if the database initialization has been completed, and if not, perform the necessary actions.
Here's an example entrypoint script based on the official WordPress image:
#!/bin/bash set -e # Function to check if database initialization is needed is_init_needed() { # Insert database initialization check logic here return 0 } # Check if initialization is needed if is_init_needed; then # Perform database initialization echo "Initializing database..." /usr/bin/mysql -u "root" -p"$MYSQL_ROOT_PASSWORD" -h "mysql" < /usr/local/init.sql echo "Database initialized successfully." fi # Start the application exec "$@"
Docker Compose Configuration
In your docker-compose.yml file, specify the entrypoint script in the entrypoint key for the service that requires initialization, like this:
services: my_project: build: . entrypoint: ["./entrypoint.sh"] ...
Additional Notes
The above is the detailed content of How to Execute One-Time Commands in Docker Compose with Entrypoint Scripts?. For more information, please follow other related articles on the PHP Chinese website!