## Intro

Working with Docker Compose can simplify multi-container development and deployment, but it also introduces its own set of recurring failures. Misconfigured YAML, port collisions, missing variables, and broken volume mounts can stop a stack before it starts, and the error messages are not always clear. This guide turns those failure moments into a repeatable troubleshooting workflow.

We will walk through the most common Docker Compose errors, explain why they happen, and show step-by-step fixes using real command examples and configuration snippets. Every fix includes a way to verify the result so you can move forward with confidence. Whether you are debugging a local environment or preparing a production-like test, the same principles apply: observe the current state first, change one thing at a time, and confirm the expected behavior.

The article is written for developers, DevOps consultants, and technical startup teams who use Docker Compose regularly. It focuses on practical diagnosis and recovery rather than broad theory. You will learn how to interpret Compose error messages, inspect services without modifying them, persist data correctly, and design a safe recovery path when something breaks.

## Version and Environment Inventory

Before touching any configuration, confirm what is actually installed and running. Many "Compose" problems are version mismatches or stale containers. Start with read-only commands that show the current state without changing anything.

### Check Docker and Compose Versions

The syntax for the `docker-compose` command changed between the standalone binary and the Compose plugin. If you see an error like `docker-compose: command not found` but `docker compose` works, or vice versa, you are likely dealing with a version or installation mismatch.

Run these commands to see exactly what is available:

```bash
docker --version
# Example output: Docker version 24.0.7, build afdd53b

docker compose version
# Example output (plugin): Docker Compose version v2.23.0

docker-compose --version
# Example output (standalone): docker-compose version 1.29.2, build 5becea4c
```

If the standalone binary is missing but the plugin works, do not install both and risk confusion. Choose one invocation style and update all scripts, Makefiles, and documentation to match. The plugin (`docker compose`) is the current recommended path and receives ongoing updates.

### Inspect the Existing Project State

A failing Compose project often has leftover containers, networks, or volumes from an earlier run. List everything the current Compose file manages:

```bash
docker compose ps -a
# Shows all containers for the project, including stopped ones

# Example output:
# NAME                IMAGE               COMMAND                  SERVICE   STATUS        PORTS
# myapp-web-1         myapp-web:latest    "nginx -g 'daemon of…"   web       Up 2 minutes   0.0.0.0:80->80/tcp
# myapp-db-1          postgres:15         "docker-entrypoint.s…"   db        Exited (1)     
```

Pay attention to the `STATUS` column. An `Exited` status with a non-zero code means the container failed to start or crashed. The logs for that service will usually reveal the cause.

### Read Logs Without Modifying Anything

Use `docker compose logs` to read the most recent output for one or more services. Add `--tail` to limit the number of lines and `--no-color` for cleaner output in scripts:

```bash
docker compose logs --tail 100 web
# Shows the last 100 lines from the web service

docker compose logs -f db
# Follows the db service logs in real time (Ctrl+C to exit)
```

If a container is already running but behaving incorrectly, attach to its shell without rebuilding or restarting it:

```bash
docker compose exec web sh
# Opens a shell inside the web container (use 'bash' if the image has it)
```

Inside the shell, you can test network connectivity, check environment variables, and inspect file paths exactly as the application sees them.

### Inventory Volumes and Bind Mounts

Data loss is a common but serious Compose mistake. Before modifying or removing containers, check where each service writes its persistent data.

```bash
docker volume ls
# Lists all named volumes

docker inspect myapp_db_data
# Replace with your volume name; shows mountpoint and other metadata
```

In the Compose file, named volumes and bind mounts look like this:

```yaml
version: "3.9"
services:
  db:
    image: postgres:15
    volumes:
      - db_data:/var/lib/postgresql/data  # named volume
      - ./backups:/backups                # bind mount

volumes:
  db_data:
```

A named volume like `db_data` is managed by Docker and survives container rebuilds. A bind mount maps a host directory such as `./backups` directly into the container; it is useful for local development, but the path must exist with the right permissions on every machine that runs the Compose file. If a bind mount path is missing, the container may still start, but writes will go to the container's writable layer and disappear on recreation.

### Restart Test for Data Persistence

One low-risk way to verify that your volumes are configured correctly is to run a restart test. Do this before any destructive operation:

1. Write a test file inside the container's data directory.
2. Stop and recreate the container.
3. Confirm the file still exists.

Example for a database service:

```bash
# Step 1: create a marker file in the data directory
docker compose exec db touch /var/lib/postgresql/data/_restart_test

# Step 2: stop and recreate the db service only
docker compose up -d --force-recreate db

# Step 3: check the file
docker compose exec db ls /var/lib/postgresql/data/_restart_test
# Expected output: /var/lib/postgresql/data/_restart_test
```

If the file is missing after recreation, the data directory was not mounted to a persistent volume or bind mount. Adjust the Compose file before relying on the service for any real work.

## Safe Configuration Path

Configuration errors are the most frequent source of Compose failures. A small YAML indentation mistake, an undefined variable, or a port that is already in use can prevent the whole stack from starting. This section walks through each common problem and shows how to fix it safely.

### Validate the Compose File Before Applying

Always run `docker compose config` before `up`. This command parses and validates the Compose file, expanding environment variables, and prints the effective configuration that Docker would use. It catches syntax errors and many semantic mistakes before any container is created.

```bash
docker compose config
# If the file is valid, it prints the normalized YAML.
# If there is an error, it shows the file and line number.
```

Example of a common YAML error and its fix. Suppose you have this Compose snippet:

```yaml
services:
  web:
    image: nginx:alpine
     ports:
      - "8080:80"
```

The `ports` key is indented one extra space relative to `image`. Running `docker compose config` returns:

```
yaml: line 4: mapping values are not allowed in this context
```

Fix the indentation so that `ports` aligns with `image`, and re-run `docker compose config` to confirm.

### Environment Variables: Undefined or Misplaced

Compose supports environment variables in two places: the `${VAR}` syntax inside the YAML file, and the `environment` section that passes variables into containers. A common error is referencing a variable that is not set in the shell or in a `.env` file.

Example Compose file:

```yaml
services:
  api:
    image: myapp/api:${API_VERSION}
    ports:
      - "${API_PORT}:8080"
```

If `API_VERSION` or `API_PORT` is not defined, `docker compose config` fails with:

```
WARN[0000] The "API_VERSION" variable is not set. Defaulting to a blank string.
```

Or in newer versions, `docker compose up` may error entirely. To fix this, create a `.env` file in the same directory as `docker-compose.yml`:

```env
API_VERSION=1.4.2
API_PORT=8080
```

Then run `docker compose config` again. The output should now show the substituted values. Never commit secrets like passwords or API keys to a `.env` file that is tracked in version control; use a separate untracked file or a secrets manager for sensitive values.

### Port Already in Use

When a container fails with `port is already allocated`, it means another process on the host (or another container) is already bound to the same port. This often happens when you run multiple Compose projects that both map port 80 or 5432.

Example error during `docker compose up`:

```
Error response from daemon: driver failed programming external connectivity on endpoint myapp_web_1
Bind for 0.0.0.0:80 failed: port is already allocated
```

To see what is using the port on Linux or macOS:

```bash
sudo lsof -i :80
# Example output:
# COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
# docker-pr 1234 root    4u  IPv6  12345      0t0  TCP *:http (LISTEN)
```

On Windows, use `netstat -ano | findstr :80` to get the PID, then check the process in Task Manager.

There are two safe fixes:

1. Change the host port in the Compose file to an unused one, e.g., `"8080:80"`.
2. Stop the other container or process that is using the port, if you have control over it.

Always re-run `docker compose up -d` and then `docker compose ps` to verify the service started and the ports are mapped correctly.

### Volume Permission Denied

Containers often run as a non-root user for security, but the mounted volume directory on the host may be owned by root or by a different UID/GID. The result is a `permission denied` error when the container tries to write to the volume.

Example log line:

```
PermissionError: [Errno 13] Permission denied: '/app/data'
```

To fix this, check the UID and GID of the user inside the container:

```bash
docker compose exec app id
# Example output: uid=1000(appuser) gid=1000(appuser) groups=1000(appuser)
```

Then compare with the ownership of the host directory (for a bind mount):

```bash
ls -ld ./data
# Example output: drwxr-xr-x 2 root root 4096 Jun 1 10:00 ./data
```

The host directory is owned by root, but the container user is UID 1000. You can fix this in one of three ways:

1. Change the host directory ownership to match the container user:
   ```bash
   sudo chown -R 1000:1000 ./data
   ```
2. Run the container as root temporarily by setting `user: root` in the Compose service (only for debugging, not recommended for production).
3. Use a named volume instead of a bind mount; Docker will initialize the volume with the correct permissions from the image.

After changing ownership, restart the service and test by creating a file:

```bash
docker compose exec app touch /app/data/test.txt
# If no error, permissions are correct
```

### Command or Entrypoint Override Failures

If you override the `command` or `entrypoint` in your Compose file, make sure the new executable exists inside the container image. A typo in the command path leads to an immediate exit with a "not found" error.

Example Compose override:

```yaml
services:
  web:
    image: nginx:alpine
    command: /usr/local/bin/custom-start.sh
```

If `custom-start.sh` is not present in the image, the container exits with:

```
Error: exec: "/usr/local/bin/custom-start.sh": stat /usr/local/bin/custom-start.sh: no such file or directory
```

Verify the file exists inside the image without starting a container:

```bash
docker run --rm nginx:alpine ls -l /usr/local/bin/custom-start.sh
```

If it is missing, either correct the path, add the script via a custom Dockerfile, or use an alternative command that the image supports.

## Verification and Diagnostics

Once you have made a change, do not assume the problem is fixed. Use structured verification commands to confirm the expected state. This section covers the essential diagnostic commands for containers, networks, and service health.

### Container Status and Health

`docker compose ps` gives a quick overview, but for deeper inspection use `docker inspect`. It returns JSON with every detail about a container, including its configuration, state, mounts, and network settings.

```bash
docker compose ps
# Quick status

docker inspect myapp_web_1
# Full JSON output
```

To pull just the fields you need, use `--format`:

```bash
docker inspect --format='{{.State.Status}}' myapp_web_1
# Example output: running

docker inspect --format='{{.State.Health.Status}}' myapp_web_1
# Example output: healthy (if a healthcheck is defined)
```

If a container has a healthcheck in its Dockerfile or Compose file, the health status tells you whether the service is actually ready to accept traffic, not just that the process is running.

### Network Connectivity Between Services

Compose creates a default network for the project. Services can reach each other by service name. If one service cannot connect to another, start by listing the project networks:

```bash
docker network ls
# Example output:
# NETWORK ID     NAME                DRIVER    SCOPE
# abc123def456   myapp_default       bridge    local
```

Inspect the network to see which containers are attached:

```bash
docker network inspect myapp_default
```

Then test DNS resolution from inside one container:

```bash
docker compose exec web nslookup db
# Example output: Address: 172.18.0.3#53, Name: db, Address 1: 172.18.0.2
```

If DNS fails, make sure both services are on the same network and the service names in the Compose file match what the application is trying to reach. Also check for `links` or `depends_on` misconfigurations.

### Environment Variables Inside the Container

To confirm that environment variables are passed correctly, print them inside the running container:

```bash
docker compose exec api env | sort
# Shows all environment variables in the container, sorted

docker compose exec api printenv DATABASE_URL
# Shows the value of a specific variable
```

If a variable is missing or has the wrong value, review the `environment` or `env_file` sections in the Compose file and the `.env` file in the project directory.

### Checking Logs for Errors

Logs are the first place to look for runtime failures. Use `docker compose logs` with service names and time filters:

```bash
docker compose logs --since 10m --timestamps web db
# Shows logs from the last 10 minutes for web and db, with timestamps
```

If the log output is too large, combine `--tail` with `--follow` selectively:

```bash
docker compose logs --tail 200 -f api > api-debug.log 2>&1 &
# Writes the last 200 lines and follows the api service, saving to a file
```

When reading logs, look for repeated error patterns, stack traces, or connection refused messages that point to the root cause.

## Failure Modes and Recovery

Not every failure is a configuration mistake. Disk exhaustion, crashed containers, and orphaned services can also bring a Compose stack down. This section describes how to recognize these failure modes and recover without losing data or making the problem worse.

### Disk Full: No Space Left on Device

Containers and volumes can fill the host disk, especially if logs are not rotated or if large datasets are written to the container layer. A common symptom is an error like `no space left on device` inside a container.

To check disk usage of Docker resources:

```bash
docker system df
# Example output:
# TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
# Images          12        3         4.2GB     2.1GB (50%)
# Containers      5         2         350MB     120MB (34%)
# Local Volumes   8         5         6.8GB     1.9GB (27%)
# Build Cache     20        0         1.1GB     1.1GB
```

If volumes are the culprit, list them by size:

```bash
docker system df -v | sort -k7 -h
# Sorts by size column
```

To free space safely, remove only unused resources:

```bash
docker system prune -a --volumes
# WARNING: removes all unused containers, networks, images, and volumes.
# Use with caution, and only after verifying what is still needed.
```

Better: clean up specific unused volumes by name after ensuring no container needs them.

### Container Crash Loop: Restarting

When a container shows `Restarting` status and never becomes healthy, it is stuck in a crash loop. The restart policy in the Compose file (`restart: always` or `unless-stopped`) keeps trying to restart the process, but the application exits immediately each time.

To diagnose, look at the last exit code and logs:

```bash
docker compose ps
# Example output:
# NAME                STATUS                          PORTS
# myapp_api_1         Restarting (1) 5 seconds ago

docker inspect --format='{{.State.ExitCode}}' myapp_api_1
# Example output: 1

docker compose logs --tail 20 api
# Shows the error that caused the exit
```

Common causes include missing configuration files, bad environment variables, or a port conflict. Fix the underlying issue, then disable the restart policy temporarily to see the error without repeated restarts:

```yaml
services:
  api:
    restart: "no"
```

After fixing, re-enable the restart policy.

### Orphaned Containers After Project Removal

If you remove the Compose project with `docker compose down`, but some containers remain, they are "orphans". This can happen if you used `docker-compose` (standalone) to create the project and then `docker compose` (plugin) to manage it, or if the project name changed.

To find orphans not managed by the current Compose file, run:

```bash
docker ps -a --filter "label=com.docker.compose.project"
# Lists all containers that belong to some Compose project
```

If you see containers that are not part of the current project, you can remove them individually after confirming they are not needed:

```bash
docker rm -f <container_name_or_id>
```

To prevent orphan warnings, always use the same Compose command variant and the same project name. You can set an explicit project name with `-p` or the `name:` field in newer Compose versions.

### Recovery from Bad Volume Restore

If you restore a volume from a backup but the application fails to start due to permission or format issues, you need to verify the volume contents and permissions from inside a temporary container.

Example: a database volume was restored, but PostgreSQL refuses to start because the data directory is owned by the wrong user.

Launch a temporary container that mounts the volume and lets you inspect it:

```bash
docker run --rm -it -v app_db_data:/data alpine sh
# Inside the container:
ls -la /data
# Check ownership and files
```

If the UID/GID is wrong, you can either chown from the host if the volume is a bind mount, or if it is a named volume, use a temporary container with the correct user to fix ownership:

```bash
docker run --rm -v app_db_data:/data alpine chown -R 70:70 /data
# 70 is the postgres user UID in the official image
```

Then restart the database service and check its logs for successful startup.

## Operations Checklist

A checklist keeps troubleshooting disciplined and prevents hasty changes that make things worse. Here is a production-oriented checklist you can adapt for your team. It includes a named owner for each major item and a suggested review cadence.

| Item | Action | Verify | Owner | Review Frequency |
|------|--------|--------|-------|------------------|
| 1. Baseline environment | Record Docker and Compose versions, current stack status with `docker compose ps -a`. | Pasted output in incident doc. | Priya Shah, Engineering Lead | Monthly |
| 2. Backup data volumes | Before any major change, snapshot or copy named volumes. | `docker run --rm -v app_db_data:/data alpine tar czf /tmp/backup.tar.gz -C /data .` | Marcus Chen, DevOps Engineer | Weekly for production |
| 3. Validate configuration | Run `docker compose config` after every Compose file edit. | Exit code 0 and expected variables expanded. | Each developer (self-check) | Before every deploy |
| 4. Single change per test | When debugging, modify only one variable or setting at a time. | `docker compose up -d --force-recreate <service>` succeeds and service healthy. | Developer assigned to the bug | Per incident |
| 5. Review port allocations | Check for port conflicts before starting a new project. | `sudo lsof -i :<port>` returns no conflicting process. | Marcus Chen, DevOps Engineer | When adding a service |
| 6. Verify data persistence | Perform restart test on a service with mounted data. | Marker file still exists after `docker compose up -d --force-recreate`. | Priya Shah, Engineering Lead | Quarterly |
| 7. Monitor disk usage | Run `docker system df` and prune unused resources. | Disk usage below 80% on host. | Marcus Chen, DevOps Engineer | Weekly |
| 8. Document recovery steps | Keep a runbook for each common error and its fix. | Runbook accessible and tested during an incident. | Priya Shah, Engineering Lead | After every incident |

This checklist is not a static document. Revisit it after every significant failure or change to the stack. The owners listed are examples; assign real names in your team.

## Common Pitfalls and How to Avoid Them

Even experienced Compose users fall into the same traps. Recognizing them saves hours of debugging.

### Pitfall 1: Using `docker-compose` and `docker compose` Interchangeably

**Why it happens**: Older tutorials and muscle memory mix the standalone binary and the plugin.

**How to avoid**: Pick one command style per team and document it. Add a wrapper script or alias if necessary. Check scripts and CI pipelines for the old syntax.

### Pitfall 2: Hardcoding Credentials in Compose Files

**Why it happens**: Convenience during development.

**How to avoid**: Use environment variables with a `.env` file that is not committed to version control. For production, use Docker secrets or external secret management. Run `docker compose config` to see if any secrets are exposed in plain text.

### Pitfall 3: Ignoring Healthchecks

**Why it happens**: Developers assume a container is ready when the process starts, but the application may need time to initialize.

**How to avoid**: Define a `healthcheck` in the Compose file for critical services, and use `depends_on` with `condition: service_healthy` in newer Compose versions. Example:

```yaml
services:
  db:
    image: postgres:15
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  api:
    image: myapp/api
    depends_on:
      db:
        condition: service_healthy
```

### Pitfall 4: Mounting Volumes with Wrong Ownership

**Why it happens**: The host directory is owned by a different user than the container process.

**How to avoid**: Use named volumes for application data, or set the correct `user:` in the Compose service to match the host directory owner. Test permissions with a simple write command after the container starts.

### Pitfall 5: Not Cleaning Up Networks and Volumes

**Why it happens**: Repeated `docker compose up` and `down` without `-v` leaves unused resources that accumulate.

**How to avoid**: Use `docker compose down -v` when you want to remove associated volumes (careful: this deletes data). Regularly run `docker system prune` to remove unused networks and build cache.

### Pitfall 6: Overriding the Entrypoint Incorrectly

**Why it happens**: You want to run a custom script but mistype the path or forget that the base image uses a specific entrypoint.

**How to avoid**: Always test the command with `docker run` first, and inspect the image's default entrypoint with `docker image inspect`:

```bash
docker image inspect --format='{{.Config.Entrypoint}} {{.Config.Cmd}}' nginx:alpine
# Example output: [/docker-entrypoint.sh] [nginx -g daemon off;]
```

## Conclusion

Docker Compose common errors are seldom mysterious once you know where to look. A disciplined approach will resolve most issues in minutes, not hours:

- Verify the version and environment before changing anything.
- Validate the Compose file and understand the exact error message.
- Check ports, environment variables, and volume permissions in that order.
- Use logs and inspect commands to see the container's perspective.
- Always confirm the fix with a verification command and a restart test.
- Document the recovery steps so the next person does not repeat the struggle.

The key is to make failures visible and changes reversible. Start with one low-risk verification from this guide, record the current state, and compare the result with the expected output. Over time, you will build a mental library of symptoms and fixes that turns Compose troubleshooting from a panic into a routine.