Docker Compose: How to Execute Multiple Commands in a Service

When working with Docker Compose, you might find yourself needing to run multiple commands in a service’s container—like running database migrations, starting a server, or initializing dependencies. However, Docker Compose services accept only one command via the command: or entrypoint: fields.

So how do you run multiple commands effectively?


⚙️ Option 1: Use a Shell to Chain Commands

You can use sh -c (or bash -c) to run multiple commands as a single string:

services:
  web:
    image: node:18
    command: sh -c "npm install && npm run build && npm start"

Here, all three commands will run sequentially, and the container will exit if any command fails.


⚙️ Option 2: Use a Custom Shell Script

For better readability and maintainability, create a shell script inside your image:

# Dockerfile
COPY entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

Then in entrypoint.sh:

#!/bin/sh
npm install
npm run build
npm start

This is especially helpful if your command list grows or requires logic like conditionals.


⚙️ Option 3: Use &&, ;, or ||

You can chain commands using:

  • &&: Run next only if previous succeeds
  • ;: Run next regardless of previous
  • ||: Run next only if previous fails
command: sh -c "echo 'Building...' && npm run build; echo 'Done'"

⚠️ Notes and Tips

  • Make sure to quote the whole command after sh -c.
  • Avoid using command: and entrypoint: together unless intentional.
  • You can override commands via docker-compose.override.yml.

✅ Conclusion

To run multiple commands in Docker Compose:

  • Use sh -c with &&, ;, or ||
  • Or, bundle commands in a shell script

This approach improves flexibility and keeps your service containers clean and efficient.

Sharing Is Caring:

Leave a Comment