When I need to run one command with a service’s settings, volumes and environment, I want a throwaway container, not a new service in the compose file.
That is what docker compose run is for. It starts a new container from a service’s configuration, runs the command you give it instead of the configured one, and exits. Add --rm and Docker removes the container when it finishes, even when the service has a restart policy, according to the Docker docs.
docker compose run --rm app ls -la /data
Replace app with the name of a service in your compose file. Without --rm every run leaves a stopped container behind, and they pile up quietly.
Two behaviours. First, run does not publish the service’s ports by default, which avoids a clash with the container that is already running. If you need them, add --service-ports, or map one yourself with -p 8080:80. Second, it starts linked services that are stopped before it runs. Add --no-deps when you only want the one container.
docker compose run --rm --no-deps -e DEBUG=1 app sh
The -e flag sets an environment variable for that one run, so you can try a setting without editing the file. This is a one-off container, so anything it writes outside a mounted volume disappears with it, which is the point and also the caveat. If you want to look inside the container that is already running, that is docker compose exec, a different tool.
Further reading: Docker docs: docker compose run, On this site: docker compose logs –since 10m shows only what just happened, On this site: add –wait to docker compose up and let it tell you when the stack is really ready