What is the difference between docker compose up and docker compose run?
up creates and starts all services (or those named) as defined, with ports and dependencies. run starts a one-off container for a single service with a command you give, then exits, and does not publish ports by default.
Explain it simply
up opens the whole restaurant: kitchen, counter, waiters. run calls just one chef for a single task, such as cleaning a tandoor, and then he goes home.
docker compose up -d builds if needed and starts every service, wiring networks, volumes and published ports. docker compose run web python manage.py migrate starts a new temporary container from the web service definition, runs that command instead of the default, and starts the services it depends on. Differences: run does not publish the service's ports unless you add --service-ports, it overrides the command, and it creates a separate container each time, so use --rm to remove it afterwards.
Typical uses of run: database migrations, tests, seeding data, a debugging shell.
Example
docker compose up -d # whole stack
docker compose run --rm web python manage.py migrate
docker compose run --rm web sh # debugging shell
docker compose run --service-ports web # publish ports as wellWhat to say in the interview
"up starts the full stack as defined. run launches a one-off container for one service with a custom command, without publishing ports by default, which I use for migrations, tests and shells with --rm."
Common mistakes
- Forgetting --rm and collecting many stopped one-off containers.