如何为docker-compose run传递底层命令的命令行参数?
Absolutely, this is totally feasible—you just need to tweak how you pass those arguments through docker-compose! Let me break down why your initial command didn't work and show you the correct ways to make this happen.
Why your original command failed
In your non-Docker workflow, npm run test:watch -- --verbose --match="matching test name" uses the -- to tell npm to pass everything after it directly to your test runner. But when you run docker-compose run test-service-name -- --verbose ..., that -- is interpreted by docker-compose as a separator for its own options, not for the npm command inside the container. The arguments don't end up reaching your test runner like you expect.
Solution 1: Pass the full npm command with arguments (no yml changes)
You can explicitly run the full npm command inside the container, including the -- that npm needs to forward arguments to the test script. Use this command:
docker-compose run test-service-name npm run test:watch -- --verbose --match="matching test name"
This works because you're telling docker-compose to execute the exact npm command you'd run locally, including the argument separator and test runner flags. No changes to your docker-compose.yml are needed here.
Solution 2: Simplify with docker-compose.yml configuration (for repeated use)
If you run this test command often, you can adjust your service definition to make passing arguments easier. Update your docker-compose.yml to set an entrypoint that includes the base npm command and the -- separator:
services: test-service-name: build: . entrypoint: ["npm", "run", "test:watch", "--"]
Now you can run the command with just the test runner arguments, since the entrypoint handles the npm and separator part:
docker-compose run test-service-name --verbose --match="matching test name"
This keeps your run commands clean and avoids repeating the full npm syntax every time.
Important note about existing command definitions
If your docker-compose.yml already has a command set for the test service, keep in mind that docker-compose run will override this command unless you use the entrypoint approach above. That's why Solution 1 explicitly includes the full npm command—so it replaces any pre-defined command in the yml.
内容的提问来源于stack exchange,提问作者Christiaan Maks

