Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 111 ยท Docker Compose

Compose Commands

A practical tour of the docker compose commands you use every day: up, down, ps, logs, exec, run, build, pull, config, scale, cp and top, with real output.

Once your stack is described in compose.yaml, you rarely touch docker run again. Everything happens through the docker compose command, and a small set of subcommands covers almost every day-to-day job: start things, look at them, read their logs, run something inside them, rebuild, and tear everything down.

This lesson walks through those subcommands with one tiny project, shows what they print, and points out the differences that trip people up (exec versus run, stop versus down, up versus restart). All output below comes from a real Docker 29 with Compose v5. It assumes you know the file format from Services in Compose.

The example project

Two services: an nginx web server and a small worker built from a local Dockerfile that prints a line every two seconds.

YAML
name: tcd-b10-cc
services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:18101:80"
  worker:
    build: ./app
    command: ["sh", "-c", "while true; do echo tick; sleep 2; done"]
DOCKERFILE
FROM alpine:3
RUN echo hi > /hello.txt

Every docker compose command looks for compose.yaml (or compose.yml, docker-compose.yml) in the current directory and then in parent directories. The name: key sets the project name; without it Compose uses the folder name. The project name prefixes every container, network and volume, which is how Compose finds "its" objects again later.

Run docker compose from the folder that holds the file, or point at it with -f path/to/compose.yaml. For another project name use -p name (or the COMPOSE_PROJECT_NAME variable).

Starting: up

docker compose up is the workhorse. It creates the network and volumes if needed, builds images that are missing, creates the containers and starts them, in dependency order.

CONSOLE
$ docker compose up -d
 Network tcd-b10-cc_default Created
 Container tcd-b10-cc-worker-1 Created
 Container tcd-b10-cc-web-1 Created
 Container tcd-b10-cc-worker-1 Started
 Container tcd-b10-cc-web-1 Started

Without -d (detached) Compose stays in the foreground, prints every service's logs with a colored prefix, and stops everything when you press Ctrl+C. That is handy while developing; use -d for anything that should keep running.

The flags you will use most:

Flag What it does
-d Start in the background and return your prompt.
--build Rebuild images before starting, even if an image exists.
--no-build Never build; fail if an image is missing.
--force-recreate Recreate containers even if nothing changed.
--no-deps Start only the named services, not their depends_on chain.
--scale web=3 Run three containers of the service web.
--remove-orphans Remove containers of services that are no longer in the file.
--abort-on-container-exit Stop everything when any container exits (useful for tests).
--wait With -d, wait until services are running (or healthy) before returning.

You can also name services: docker compose up -d web starts web and everything it depends on.

up is idempotent

Run up a second time and Compose compares the file with what is running. Unchanged services are left alone; changed ones are recreated. I edited the worker's command and ran up -d again:

CONSOLE
$ docker compose up -d
 Container tcd-b10-cc-worker-1 Recreate
 Container tcd-b10-cc-worker-1 Recreated
 Container tcd-b10-cc-worker-1 Starting
 Container tcd-b10-cc-worker-1 Started
 Container tcd-b10-cc-web-1 Running

Only worker was replaced; web printed Running and kept going. This is why you can run docker compose up -d after every git pull without thinking about it. Note what "changed" covers: the service configuration, not the contents of a build context. After editing source code, add --build.

Looking: ps, top, ls, port

docker compose ps lists the containers of this project only:

CONSOLE
$ docker compose ps
NAME                  IMAGE               COMMAND                  SERVICE   CREATED         STATUS        PORTS
tcd-b10-cc-web-1      nginx:alpine        "/docker-entrypoint.โ€ฆ"   web       2 seconds ago   Up 1 second   127.0.0.1:18101->80/tcp
tcd-b10-cc-worker-1   tcd-b10-cc-worker   "sh -c 'while true; โ€ฆ"   worker    2 seconds ago   Up 1 second

By default ps hides stopped containers. Add -a to see them, --services to print just service names, --status running to filter, and --format for custom columns:

CONSOLE
$ docker compose ps --format 'table {{.Name}}\t{{.Service}}\t{{.Status}}'
NAME                  SERVICE   STATUS
tcd-b10-cc-web-1      web       Up 21 seconds
tcd-b10-cc-worker-1   worker    Up 21 seconds

docker compose top shows the processes inside every container, with the PIDs as the host sees them. It is the Compose version of docker top:

CONSOLE
$ docker compose top
SERVICE  #   UID    PID    PPID   C   STIME  TTY  TIME      CMD
web      1   root   17122  17100  0   14:53  ?    00:00:00  nginx: master process nginx -g daemon off;
web      1   statd  17180  17122  0   14:53  ?    00:00:00  nginx: worker process
worker   1   root   17067  17043  1   14:53  ?    00:00:00  sh -c while true; do echo tick; sleep 2; done
worker   1   root   17397  17067  0   14:53  ?    00:00:00  sleep 2

(The PIDs, times and the user name of the nginx workers on your machine will differ.) Two more look-up commands:

CONSOLE
$ docker compose port web 80
127.0.0.1:18101

$ docker compose ls
NAME         STATUS      CONFIG FILES
tcd-b10-cc   running(2)  /path/to/compose.yaml

port answers "which host port did Docker give this service?", which matters when you publish a port without choosing the host side. ls lists every Compose project on the machine, which is the quickest way to find a stack you forgot about.

Reading logs: logs

CONSOLE
$ docker compose logs --tail 2 worker
worker-1  | tick
worker-1  | tick

logs merges the output of all services (or the ones you name), each line prefixed with the container name. The useful flags mirror docker logs:

  • -f follows new output (Ctrl+C stops following, not the containers).
  • --tail N limits history to the last N lines per container.
  • -t adds timestamps; --since 10m limits by time.
  • --no-log-prefix removes the worker-1 | prefix, handy for piping.
CONSOLE
$ docker compose logs --no-log-prefix -t --tail 2 worker
2026-10-23T14:54:40.630729086Z tick
2026-10-23T14:54:42.631865334Z tick

Running things inside: exec versus run

These two look alike and do very different things.

exec runs a command inside a container that is already running. Use it to look around, open a shell or run a maintenance command.

CONSOLE
$ docker compose exec worker cat /hello.txt
hi
$ docker compose exec worker sh -c 'exit 3'; echo "exit code: $?"
exit code: 3

The exit code of your command becomes the exit code of docker compose exec, so it works in scripts. A TTY is allocated by default, which breaks piping; pass -T to turn it off:

CONSOLE
$ docker compose exec -T web sh -c 'echo piped; nginx -v'
piped
nginx version: nginx/1.31.8

run starts a brand-new, one-off container from the service definition (same image, same networks, same volumes, same environment) and runs the command you give it instead of the service's command. Use it for migrations, tests, scripts and shells that should not touch the running instance.

CONSOLE
$ docker compose run --rm --no-deps worker sh -c 'echo one-off; exit 2'
 Container tcd-b10-cc-worker-run-ceee6d58f1c3 Creating
 Container tcd-b10-cc-worker-run-ceee6d58f1c3 Created
one-off
$ echo $?
2

Three details matter. First, always add --rm, otherwise every run leaves a stopped container behind. Second, run starts the service's dependencies unless you pass --no-deps. Third, run does not publish the service's ports by default (use --service-ports if you need them), so a one-off shell never clashes with the running container.

exec run
Needs a running container yes no
Creates a container no yes (name ends in -run-<id>)
Replaces command no, adds a process yes
Publishes ports n/a no, unless --service-ports
Typical use inspect, debug, psql, sh migrations, tests, one-off jobs

Building and pulling: build, pull, images

docker compose build builds every service that has a build: section and tags the result as <project>-<service>:

CONSOLE
$ docker compose build
 ...
 Image tcd-b10-cc-worker Built

Add a service name to build one (docker compose build worker), --no-cache to ignore cached layers (see The Build Cache), --pull to refresh base images, and --build-arg KEY=value to set build arguments.

docker compose pull refreshes the images of services that name an image: and skips the ones that are built locally:

CONSOLE
$ docker compose pull
 worker Skipped No image to be pulled
 Image nginx:alpine Pulling
 Image nginx:alpine Pulled

A common deployment sequence is docker compose pull followed by docker compose up -d: the first downloads new tags, the second recreates only the containers whose image changed.

docker compose images shows which image each container uses:

CONSOLE
$ docker compose images
CONTAINER             REPOSITORY          TAG      PLATFORM       IMAGE ID       SIZE
tcd-b10-cc-web-1      nginx               alpine   linux/amd64    a3554c0d0b48   93.6MB
tcd-b10-cc-worker-1   tcd-b10-cc-worker   latest   linux/amd64    8c296a9b427a   12.9MB

(IDs and sizes vary with the image version.)

Checking the file: config

docker compose config loads and merges your files, substitutes variables and prints the final configuration, or fails with an error if the file is invalid. It is the best way to debug interpolation, .env files and multiple -f files.

CONSOLE
$ docker compose config
name: tcd-b10-cc
services:
  web:
    image: nginx:alpine
    networks:
      default: null
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 80
        published: "18101"
        protocol: tcp
  ...

Notice what Compose added: the short port string became a long-form mapping, and the default network was attached. Useful variants:

CONSOLE
$ docker compose config --services
web
worker
$ docker compose config --images
nginx:alpine
tcd-b10-cc-worker
$ docker compose config --quiet; echo "exit code: $?"
exit code: 0

--quiet prints nothing and only sets the exit code, which makes it a perfect first step in a CI pipeline.

Scaling and copying files

--scale changes how many containers a service runs. Compose adds the missing ones and keeps the existing ones:

CONSOLE
$ docker compose up -d --scale worker=3
$ docker compose ps --format 'table {{.Name}}\t{{.Service}}\t{{.Status}}'
NAME                  SERVICE   STATUS
tcd-b10-cc-web-1      web       Up 21 seconds
tcd-b10-cc-worker-1   worker    Up 21 seconds
tcd-b10-cc-worker-2   worker    Up 1 second
tcd-b10-cc-worker-3   worker    Up 2 seconds

A scaled service cannot have a fixed container_name, and it cannot publish one fixed host port (three containers cannot all bind port 8080). Scale workers and other internal services; put a proxy in front of anything that needs a public port.

docker compose cp copies files between your machine and a service container, in either direction:

CONSOLE
$ docker compose cp note.txt worker:/tmp/note.txt
 tcd-b10-cc-worker-1 Copying note.txt to tcd-b10-cc-worker-1:/tmp/note.txt
 tcd-b10-cc-worker-1 Copied note.txt to tcd-b10-cc-worker-1:/tmp/note.txt
$ docker compose exec worker cat /tmp/note.txt
from host

Use it for one-off extractions such as a log or a database dump. For regular data exchange use a volume or bind mount (Bind Mounts).

Stopping: stop, down, restart, kill

This group causes the most confusion, so here is the exact difference:

Command Containers Networks Volumes Images
stop stopped, kept kept kept kept
start started again - - -
restart stopped and started kept kept kept
down stopped and removed removed kept kept
down -v removed removed removed kept
down --rmi local removed removed kept locally built images removed

After stop, the containers are still there, and ps -a shows their exit codes:

CONSOLE
$ docker compose stop
$ docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
SERVICE   STATUS
web       Exited (0) 5 seconds ago
worker    Exited (137) 2 seconds ago

Look at that 137. It is 128 + 9, meaning the worker was killed with SIGKILL. Compose sends SIGTERM and waits 10 seconds; the worker's main process is a sh -c loop running as PID 1, which ignores SIGTERM, so Docker gave up and killed it. A well-behaved program exits with 0 within moments. The lesson Signals, PID 1 and --init explains the cause and the fix.

docker compose restart restarts the containers without re-reading the file. If you changed compose.yaml, use up -d instead; restart would happily restart the old configuration.

docker compose kill -s SIGKILL worker sends a signal immediately, with no grace period. docker compose down then cleans up:

CONSOLE
$ docker compose down
 Container tcd-b10-cc-web-1 Removed
 Container tcd-b10-cc-worker-1 Removed
 Network tcd-b10-cc_default Removed

Add --remove-orphans to also delete containers that belong to the project but no longer match any service in the file. That happens when you rename or delete a service:

CONSOLE
$ docker compose -f other.yaml up -d      # a file that only defines "web"
$ docker compose -f compose.yaml down --remove-orphans
 Container tcd-b10-cc-worker-1 Removed
 ...

docker compose down -v deletes the named volumes of the project, and with them your database. Type it deliberately, never from muscle memory.

Global options worth knowing

These go before the subcommand: docker compose -f other.yaml -p demo up -d.

  • -f, --file use this file (repeat it to merge several; see Multiple Files, Profiles and Extends).
  • -p, --project-name override the project name.
  • --profile name enable services that belong to a profile.
  • --env-file path read variables from another file than .env.
  • --progress plain print plain lines instead of the animated display (good for CI logs).

A day with Compose

Putting it together, a typical day looks like this:

CONSOLE
$ docker compose pull            # fetch newer images
$ docker compose up -d --build   # (re)create what changed
$ docker compose ps              # is everything up?
$ docker compose logs -f api     # watch one service
$ docker compose exec db psql -U app   # poke around
$ docker compose run --rm api python manage.py migrate
$ docker compose down            # end of day (volumes stay)

You will see this exact flow in Project: A Full-Stack App with Compose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You changed a port mapping in compose.yaml. Which command applies the change?

    up -d compares the file with the running containers and recreates the ones whose configuration changed. restart and start reuse the old containers, and config only prints the merged file.
  2. 2. What is the main difference between docker compose exec and docker compose run?

    exec adds a process to an already running container. run creates a fresh container from the service definition, which is why you should add --rm to remove it afterwards.
  3. 3. After docker compose down, what is still there?

    down removes containers and networks only. Named volumes and images stay unless you add -v or --rmi.
  4. 4. A container shows Exited (137) after docker compose stop. What does it tell you?

    137 is 128 + 9, the signal number of SIGKILL. Compose waits for the stop timeout and then kills processes that ignore SIGTERM.
  5. 5. Which command checks the final, merged configuration and fails on errors without starting anything?

    docker compose config loads the file(s), substitutes variables and prints the result; --quiet prints nothing and only returns the exit code.

Summary

  • docker compose up -d creates and starts everything; run it again after any change and only the changed services are recreated. Add --build after code changes.
  • ps, top, port, logs and ls answer "what is running, where, and what is it saying?"
  • exec enters a running container; run --rm starts a throwaway container for one-off jobs (it does not publish ports by default).
  • config shows the merged file (use --quiet as a check), build and pull refresh images, cp moves single files, --scale adds containers.
  • stop keeps containers, down removes containers and networks, down -v also deletes named volumes.
  • restart does not re-read the file; up -d does. Exit code 137 after a stop means the process ignored SIGTERM.

Next: Project: A Full-Stack App with Compose