Execute a command after run
Problem
Hi, It will be very helpful to have something like "onrun" in the YAML to be able to run commands after the run. Similar to https://github.com/docker/docker/issues/8860 [code block] After the mongodb start, It will dump db2dump.domain.lan and restore it. When I will stop and then start the container, onrun part will no be executed to preserve idempotency. EDIT 15 June 2020 5 years later, Compose wan't to "standardize" specifications, please check https://github.com/compose-spec/compose-spec/issues/84
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement Post-Run Command Execution in Docker Compose
Docker Compose does not currently support executing commands after container runs due to the lack of an 'onrun' hook in its YAML specification. This limitation prevents users from automating tasks that need to occur after the container has started, leading to manual intervention and potential inconsistencies.
Awaiting Verification
Be the first to verify this fix
- 1
Create a Wrapper Script
Develop a shell script that will start the MongoDB container and then execute the required commands after the container is up and running.
bash#!/bin/bash # Start the MongoDB container docker-compose up -d mongodb # Wait for MongoDB to be ready sleep 10 # Execute the dump command docker exec mongodb_container_name mongodump --db db2 --out /path/to/dump - 2
Modify Docker Compose File
Ensure that the Docker Compose file is set up correctly to allow for the container to be started in detached mode and to expose necessary ports.
yamlversion: '3' services: mongodb: image: mongo ports: - '27017:27017' volumes: - ./data:/data/db - 3
Schedule the Wrapper Script Execution
Use a cron job or a similar scheduling tool to run the wrapper script at desired intervals or conditions, ensuring that the commands are executed after the MongoDB container starts.
bash0 * * * * /path/to/your/wrapper_script.sh - 4
Test the Implementation
Run the wrapper script manually to ensure that it starts the MongoDB container and executes the dump command without errors. Check the output directory for the dump files.
bash./path/to/your/wrapper_script.sh
Validation
Confirm that the MongoDB container starts successfully and that the dump command is executed by checking the output directory for the presence of the dump files. Additionally, verify that running the script multiple times does not create duplicate dumps, ensuring idempotency.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep