Docker Compose — logs, exec, attach

2 minute read

These commands help you debug and interact with running containers.

docker compose logs

View container output:

docker compose logs            # All services
docker compose logs api        # Specific service
docker compose logs -f         # Follow (stream) logs
docker compose logs -f api db  # Follow multiple services
docker compose logs --tail 50  # Last 50 lines
docker compose logs --since 1h # Last hour
docker compose logs -t         # Add timestamps

Combining Flags

docker compose logs -f --tail 100 --since 30m api

Shows the last 100 lines from the last 30 minutes, then follows new output.

Example Output

api-1  | Server started on port 3000
api-1  | Connected to database
db-1   | PostgreSQL ready for connections
web-1  | Nginx listening on port 80

docker compose exec

Run a command in a running container:

docker compose exec api sh               # Shell into service
docker compose exec db psql -U postgres   # PostgreSQL CLI
docker compose exec cache redis-cli       # Redis CLI
docker compose exec api env               # View environment
docker compose exec -u root api sh       # Run as root
docker compose exec -w /tmp api ls       # Set working directory

Common Use Cases

Task Command
Interactive shell exec api sh
Database CLI exec db psql -U postgres
View env vars exec api env
Check connectivity exec api ping db
View files exec api ls /app
Run as root exec -u root api sh

docker compose run

Run a one-off command in a new container:

docker compose run --rm api npm test      # Run tests
docker compose run --rm api npm install   # Install packages
docker compose run --rm db psql -h db     # Database command

exec vs run

Feature exec run
Container Existing (running) New (temporary)
Dependencies N/A Starts deps by default
Ports Already mapped Not mapped (use --service-ports)
Cleanup Nothing to clean Use --rm

docker compose attach

Attach to a running container’s process (stdin/stdout/stderr):

docker compose attach api

Press Ctrl+P then Ctrl+Q to detach without stopping.

Note: attach connects to the main process (PID 1). Use exec to start a new process.

Summary

Command Purpose
logs -f Follow output stream
logs --tail N Last N lines
exec svc cmd Run in existing container
run --rm svc cmd Run in new container
attach svc Connect to main process

Quick Reference

Item Detail
logs -f Follow log stream
logs –tail 50 Last 50 lines
exec api sh Shell into running container
run –rm api cmd One-off command in new container
attach Connect to PID 1 process
exec vs run Existing vs new container