How to Use Docker Compose Run: Syntax and Examples
Use
docker compose run [options] SERVICE [COMMAND] [ARGS...] to start a one-time container for a service defined in your docker-compose.yml. This runs the container with the service’s configuration but allows you to override the command or add arguments for quick tasks.Syntax
The basic syntax of docker compose run is:
docker compose run: The command to run a one-off container.[options]: Optional flags to customize the run, like--rmto remove the container after exit.SERVICE: The name of the service from yourdocker-compose.ymlto run.[COMMAND]: Optional command to override the default command of the service.[ARGS...]: Optional arguments passed to the command.
bash
docker compose run [options] SERVICE [COMMAND] [ARGS...]
Example
This example shows how to run a one-time bash shell inside a service named web defined in docker-compose.yml. It overrides the default command and opens an interactive shell.
yaml and bash
version: '3.8' services: web: image: alpine command: echo Hello from web service # Run the command: docker compose run web sh
Output
/ #
Common Pitfalls
Common mistakes when using docker compose run include:
- Expecting
runto start all services; it only starts the specified one-off container. - Not using
--rmto clean up containers, which can clutter your system. - Forgetting that
rundoes not create networks or volumes unless defined in the Compose file.
Example of a wrong and right way:
bash
# Wrong: runs container but leaves it after exit docker compose run web sh # Right: runs container and removes it after exit docker compose run --rm web sh
Quick Reference
Tips for using docker compose run:
- Use
--rmto auto-remove containers after they stop. - Use
-dto run containers in detached mode. - Use
--service-portsto map the service’s ports to the host. - Use
docker compose upto start all services instead of one-off runs.
Key Takeaways
Use
docker compose run SERVICE to start a one-time container for a service.Add
--rm to automatically remove the container after it stops.Override the default command by specifying
COMMAND and ARGS after the service name.Remember
run starts only one container, not the full Compose app.Use
docker compose up to start all services together.