Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 111 ยท Practice

Common Docker Errors

Port already allocated, name conflicts, exec format error, permission denied, no space left, failed builds and Compose mistakes: real error text, causes and fixes.

Every Docker user meets the same two dozen errors. They look scary because the messages are long and come from several layers at once (the CLI, the daemon, containerd, runc, BuildKit), but each one usually means something simple. This lesson collects the errors you will see most often. Every message below was produced on a real Docker 29 installation by doing the mistake on purpose, so you can match your screen against the text.

The method is always the same. Read the last sentence of the message first, because that is where the real cause usually sits. Then check the exit code of the command (echo $?), because Docker uses a small set of codes with fixed meanings. Finally ask which layer complained: the daemon (Error response from daemon), the runtime (OCI runtime create failed), the builder (failed to solve), or Compose (validating ...).

Container IDs in the messages are shortened or removed for readability. Everything else is printed exactly as Docker printed it. If you use Git Bash on Windows, it rewrites arguments that look like Unix paths (/w becomes C:/Program Files/Git/w). Set MSYS_NO_PATHCONV=1 or double the leading slash (//w) when you pass such paths to Docker.

Exit codes worth memorizing

A container's exit code is the exit code of its main process. Docker adds a few of its own for failures before the process even starts.

Code Meaning
0 The process finished successfully
1-2 The program reported an error (its own choice)
125 The Docker daemon or docker run itself failed (bad flag, name conflict, port in use, image missing)
126 The command was found but cannot be executed (permissions)
127 The command was not found inside the container
137 Killed by SIGKILL (128 + 9): docker kill, a docker stop that timed out, or the out-of-memory killer
139 Segmentation fault (128 + 11)
143 Ended by SIGTERM (128 + 15), the normal result of a graceful docker stop

Anything above 128 means "killed by signal (code minus 128)". More on this in The Container Lifecycle and Signals, PID 1 and --init.

Errors when starting a container

Port is already allocated

You asked for a host port that something else already holds. It can be another container or a program on the host.

CONSOLE
$ docker run -d --name web1 -p 127.0.0.1:18161:80 nginx:alpine
fc68be6e175a
$ docker run -d --name web2 -p 127.0.0.1:18161:80 nginx:alpine
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint web2 (a9f287508...): Bind for 127.0.0.1:18161 failed: port is already allocated

Run 'docker run --help' for more information
$ echo $?
125

Notice that web2 was still created. It sits in the Created state until you remove it. The fix is to pick another host port (-p 127.0.0.1:18162:80), or to stop whatever owns the port. To find out who, run docker ps --filter publish=18161 for containers, and netstat -ano | findstr 18161 (Windows) or ss -ltnp | grep 18161 (Linux) for host programs. You only change the host side of -p host:container; the container side stays what the application listens on. See Port Publishing.

The container name is already in use

Names are unique per daemon, even for stopped containers.

CONSOLE
$ docker run -d --name web1 alpine sleep 5
docker: Error response from daemon: Conflict. The container name "/web1" is already in use by container "fc68be6e175a...". You have to remove (or rename) that container to be able to reuse that name.

Run 'docker run --help' for more information

Either remove the old container (docker rm web1, or docker rm -f web1 if it is running), rename it (docker rename web1 web1-old), or add --rm to scripts so that finished containers delete themselves. In Compose you never hit this, because Compose derives names from the project name.

Image not found

Two different messages cover two different mistakes. A repository that does not exist (or is private) gives:

CONSOLE
$ docker run --rm nosuchimage
Unable to find image 'nosuchimage:latest' locally
docker: Error response from daemon: pull access denied for nosuchimage, repository does not exist or may require 'docker login'

Run 'docker run --help' for more information

A real repository with a tag that does not exist gives a different sentence:

CONSOLE
$ docker run --rm alpine:no-such-tag-xyz
Unable to find image 'alpine:no-such-tag-xyz' locally
docker: Error response from daemon: failed to resolve reference "docker.io/library/alpine:no-such-tag-xyz": docker.io/library/alpine:no-such-tag-xyz: not found

"pull access denied" almost always means a typo in the name, or a private image you have not logged in for. "not found" means the name is right and the tag is wrong. Check spelling, check the tags on the registry page, and remember that for images outside Docker Hub the full name must include the registry host (ghcr.io/owner/app:1.2). See Tags and Registries.

Executable not found, permission denied

When the container's main command cannot be started, the failure comes from runc, the low-level runtime. The message is long, but the end tells you what happened.

CONSOLE
$ docker run --rm alpine nosuchcmd
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "nosuchcmd": executable file not found in $PATH
$ echo $?
127

$ docker run --rm alpine /etc/passwd
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "/etc/passwd": permission denied
$ echo $?
126

executable file not found in $PATH (code 127) means the program does not exist inside the image. Common causes: a typo, a minimal image without that tool (bash is not in Alpine, use sh), or a Dockerfile CMD ["node", "server.js"] on an image that has no Node. permission denied (code 126) means the file exists but is not executable, typically a script copied without its execute bit. Fix it with COPY --chmod=755 script.sh /usr/local/bin/ or a RUN chmod +x. See CMD and ENTRYPOINT.

exec format error

This one has a different wording and no OCI runtime prefix: the file was found and is executable, but the kernel does not know how to run it.

CONSOLE
$ cat run.sh
echo hi
$ docker run --rm -v "$PWD:/w" alpine /w/run.sh
exec /w/run.sh: exec format error

There are two common causes. The first, shown above, is a script without a shebang line. Add #!/bin/sh as the very first line and it works. The second is a CPU architecture mismatch: an arm64 binary or image on an amd64 machine (or the reverse), as with images built on Apple Silicon and run on a typical cloud server. Docker Desktop can emulate other architectures with QEMU, so a foreign image may even run here, slowly, while a Linux server without emulation fails with this exact error. Build for the target with docker buildx build --platform linux/amd64 as shown in Multi-Platform Images.

A related cause on Windows is a script saved with CRLF line endings: the shebang becomes #!/bin/sh\r, and the error mentions a missing interpreter. Configure your editor or .gitattributes to keep *.sh files in LF.

Cannot attach stdin to a TTY

CONSOLE
$ echo | docker run --rm -it alpine sh
cannot attach stdin to a TTY-enabled container because stdin is not a terminal

-t asks for a terminal, but your input is a pipe, a CI job or a script, not a terminal. Drop -t (and usually -i too) in scripts and CI. Use -it only at an interactive prompt. On Windows with Git Bash you may also see "the input device is not a TTY"; run the command with winpty in front, or use PowerShell.

Cannot reach the daemon

CONSOLE
$ docker ps
error during connect: Get "http://127.0.0.1:18199/v1.56/containers/json": dial tcp 127.0.0.1:18199: connectex: No connection could be made because the target machine actively refused it.

The CLI is only a client. This message (here caused by pointing DOCKER_HOST at a port where nothing listens) means that the daemon is not running or the client looks in the wrong place. On Docker Desktop, start the application and wait for the whale icon to settle. On Linux, run sudo systemctl status docker. If echo $DOCKER_HOST prints something you do not remember setting, unset it, and run docker context ls to see which endpoint is active.

On Linux, a different message appears when the daemon is running but your user may not talk to it:

TEXT
permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

This is a read-only example (it needs a Linux host to reproduce). The socket belongs to the docker group. Add yourself with sudo usermod -aG docker $USER, log out and in again, or use rootless mode as described in Installing Docker. Remember that membership in the docker group is effectively root access on that machine; see Daemon Security.

Errors in running containers

The container exits immediately

You run a container with -d, and docker ps shows nothing. Look at docker ps -a:

CONSOLE
$ docker run --name quick -d alpine
829c84096ba1
$ docker ps -a --filter name=quick --format '{{.Names}} {{.Status}}'
quick Exited (0) 1 second ago

A container lives exactly as long as its main process. Alpine's default command is a shell, and a shell with no terminal attached exits at once. Nothing is wrong with Docker. The process must stay in the foreground: run a server in foreground mode (nginx -g "daemon off;", which the official image does for you), not a command that forks into the background and returns. Never "fix" this with tail -f /dev/null unless you really want an idle container.

If the exit code is non-zero, read the logs:

CONSOLE
$ docker run --name boom -d --restart on-failure:3 alpine sh -c 'echo boom; exit 2'
$ docker inspect -f 'restarts={{.RestartCount}} exit={{.State.ExitCode}}' boom
restarts=3 exit=2
$ docker logs boom
boom
boom
boom
boom

The program ran four times (the first start plus three restarts), printed boom each time and gave up. A restart policy without a limit (always, unless-stopped) turns this into an endless crash loop where docker ps shows Restarting (2) .... Always read docker logs first; Debugging Containers covers the deeper tools.

Connection refused to localhost

Inside a container, localhost is the container itself, not your computer and not the container next door.

CONSOLE
$ docker run -d --name web -p 127.0.0.1:18163:80 nginx:alpine
$ docker run --rm alpine wget -qO- -T 3 http://localhost:80
wget: can't connect to remote host: Connection refused

The second container has nothing listening on its own port 80. Put both containers on a user-defined network and use the service or container name:

CONSOLE
$ docker network create appnet
$ docker network connect appnet web
$ docker run --rm --network appnet alpine wget -qO- http://web | head -2
<!DOCTYPE html>
<html>

The reverse problem is a server that binds to 127.0.0.1 inside its container: even with -p it is unreachable from outside, because published ports arrive on the container's network interface, not on its loopback. Make the app listen on 0.0.0.0. See Container Communication and User-Defined Bridges.

Killed with exit code 137

Exit code 137 with no error message in the logs is usually the kernel's out-of-memory killer, or a docker stop that ran out of patience.

CONSOLE
$ docker run --rm --memory 20m alpine sh -c 'a=x; while true; do a=$a$a; done'
$ echo $?
137

To tell the causes apart, run docker inspect -f '{{.State.OOMKilled}}' <name> on a container that is still there (without --rm). true means the memory limit was hit: raise --memory or fix the leak. false with 137 means somebody sent SIGKILL: a program that ignores SIGTERM (a shell script as PID 1, for example) is killed after the stop timeout, 10 seconds by default. See Resource Limits and Signals, PID 1 and --init.

Cannot exec: the container is not running

CONSOLE
$ docker exec web ls
Error response from daemon: container 73c468464e4d... is not running
$ docker logs nothing
Error response from daemon: No such container: nothing

docker exec only works on running containers. If the container exited, look at its logs and exit code instead. If you want a shell in the image anyway, start a new container: docker run --rm -it --entrypoint sh image. "No such container" means a typo or that the container was already removed (--rm, or Compose down). Check docker ps -a.

Removing a running container

CONSOLE
$ docker rm web
Error response from daemon: cannot remove container "web": container is running: stop the container before removing or force remove

Do what it says: docker stop web && docker rm web, or docker rm -f web (which sends SIGKILL, so give databases the chance to stop cleanly first).

Permission and storage errors

Permission denied when writing

Permissions inside a container are real Linux permissions. If the image runs as a non-root user, it can only write where that user has rights.

CONSOLE
$ docker run --rm -u 1000 alpine sh -c 'echo x > /etc/f'
sh: can't create /etc/f: Permission denied

$ docker volume create data
$ docker run --rm -u 1000 -v data:/data alpine sh -c 'echo x > /data/f'
sh: can't create /data/f: Permission denied

A new named volume is owned by root, so a non-root process cannot write into it, unless the image already has that directory with the right owner (Docker copies ownership from the image the first time an empty volume is mounted). The fix is in the Dockerfile: create the directory and chown it to the runtime user before switching with USER. For bind mounts, match the user ID to the host file owner with --user "$(id -u):$(id -g)". See Users and Permissions and Volumes.

Read-only file system

CONSOLE
$ docker run --rm --read-only alpine sh -c 'echo x > /f'
sh: can't create /f: Read-only file system

Somebody asked for it: --read-only (or read_only: true in Compose) is a security hardening option. Give the application the few writable places it needs with --tmpfs /tmp or a volume.

No space left on device

This message appears in two situations, and the fix differs.

The first is a small tmpfs or a full volume. Here a 1 MB in-memory mount is filled:

CONSOLE
$ docker run --rm --tmpfs /small:size=1m alpine sh -c 'dd if=/dev/zero of=/small/f bs=1k count=2000'
dd: error writing '/small/f': No space left on device

The second is the Docker disk itself being full (images, stopped containers, build cache, volumes). Typical sightings are no space left on device during docker pull or docker build. On Linux that is the filesystem under /var/lib/docker; on Docker Desktop it is the virtual disk of the Docker VM. See where the space went with:

Terminal
docker system df

Then remove what you no longer need (docker image prune, docker builder prune, docker container prune), keeping an eye on volumes, which hold data. Cleaning Up shows each command and what it deletes. Never run docker volume prune on a machine whose databases use anonymous or unused-looking volumes unless you have a backup.

Build errors

BuildKit prints a long progress log, but the error is at the bottom, together with the line of the Dockerfile that failed (marked with >>>).

COPY: file not found

CONSOLE
$ docker build -t demo .
...
Dockerfile:2
--------------------
   1 |     FROM alpine
   2 | >>> COPY app.txt /app.txt
   3 |     
--------------------
ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/app.txt": not found

The wording "failed to calculate checksum" confuses beginners, but it just means the source file is missing from the build context. Three reasons cover nearly every case: the path is wrong or relative to the wrong directory (paths are relative to the context, not to the Dockerfile), the file is excluded by .dockerignore, or it lives outside the context folder (you cannot COPY ../file). See Build Context and .dockerignore.

RUN failed

CONSOLE
$ docker build -t demo .
...
#5 [2/2] RUN exit 3
#5 ERROR: process "/bin/sh -c exit 3" did not complete successfully: exit code: 3
...
ERROR: failed to build: failed to solve: process "/bin/sh -c exit 3" did not complete successfully: exit code: 3

Any RUN command that exits non-zero stops the build, and the exit code is the code of your command. Scroll up to the output of that step to find the real cause (a failed apt-get, npm ci or compile error). To investigate, comment out the failing line, build, and open a shell with docker run --rm -it demo sh to try the command by hand.

Unknown instruction and bad base image

CONSOLE
ERROR: failed to build: failed to solve: dockerfile parse error on line 2: unknown instruction: RUNN (did you mean RUN?)

ERROR: failed to build: failed to solve: alpine:no-such-9: failed to resolve source metadata for docker.io/library/alpine:no-such-9: docker.io/library/alpine:no-such-9: not found

The first is a typo, and Docker even suggests the fix. The second is the same "tag not found" problem as with docker run, found at the FROM line. A stage name that does not exist in COPY --from=name gives a similar parse-time error, so check spelling in Multi-Stage Builds.

The build is slow or the cache never hits

This is not an error message, but it is the most common build complaint. If every build reinstalls your dependencies, a COPY . . probably comes before the dependency install, so any source change invalidates it. Copy the dependency manifest first, install, then copy the rest. Details in The Build Cache.

Compose errors

Compose validates the file before touching anything. These messages come from docker compose config, which you can run at any time as a syntax check.

CONSOLE
$ docker compose config
service "web" depends on undefined service "db": invalid compose project

$ docker compose config
validating /project/compose.yaml: services.web additional properties 'prots' not allowed

$ docker compose config
failed to parse /project/compose.yaml: go-yaml load error in scanner at L4.C11: mapping values are not allowed in this context

The first names a service that does not exist (a typo, or you forgot to define the database). The second is a misspelled key; Compose is strict, so prots instead of ports is rejected. The third is YAML itself: line 4 is indented with one space too many, and YAML requires every key at the same level to line up exactly. Use spaces (never tabs) and an editor that shows indentation.

A softer problem is an unset variable, which only produces a warning and a blank value:

CONSOLE
$ docker compose config
time="..." level=warning msg="The \"TCD_TOKEN\" variable is not set. Defaulting to a blank string."
name: demo
services:
  web:
    environment:
      TOKEN: ""

A blank value can silently break a service (an empty password, say), so treat the warning as a bug. Define the variable in a .env file or the shell, or use ${TOKEN:?token is required} to make Compose fail loudly. See Compose Environment and Configuration.

Debugging order of preference: docker compose config (is the file valid and what do variables become?), docker compose ps -a (what state is each container in?), docker compose logs --tail 50 service (why?), then docker compose exec or run for a shell.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. docker run fails with Bind for 127.0.0.1:18161 failed: port is already allocated and exit code 125. What is the right fix?

    The host side of -p host:container is already taken by another container or program. The container side is where the app listens and stays as it is.
  2. 2. A container ran sh -c 'echo hi; exit 2' and docker ps -a shows Exited (2). Which statement is correct?

    A container's exit code is the exit code of its main process. Docker's own failures use codes such as 125, and memory kills show 137.
  3. 3. Running a script copied into an image gives exec format error. Which is a likely cause?

    The kernel found the file but cannot execute it: a missing interpreter line or a binary built for another CPU architecture.
  4. 4. Inside container A, wget http://localhost:80 is meant to reach container B and gets Connection refused. Why?

    Each container has its own loopback interface. Put both on one user-defined network and address the other by name.
  5. 5. What does exit code 137 tell you?

    Codes above 128 mean death by signal: 137 is 128 + 9 (SIGKILL). Check OOMKilled in docker inspect to see whether memory was the reason.

Summary

  • Read the last sentence of an error first, then the exit code, then ask which layer (daemon, runc, BuildKit, Compose) complained.
  • 125 is Docker's own failure, 126 is not executable, 127 is command not found, 137 is SIGKILL (often out of memory), 143 is a graceful SIGTERM.
  • Port and name conflicts are fixed on the host side: another host port, or remove or rename the old container.
  • "pull access denied" means a wrong name or private image; "not found" means a wrong tag.
  • exec format error points to a missing shebang line or a CPU architecture mismatch.
  • A container lives as long as its main process; keep it in the foreground and read docker logs.
  • localhost inside a container is the container; use networks and names, and make servers listen on 0.0.0.0.
  • New named volumes are owned by root; set up ownership in the Dockerfile for non-root users.
  • Build errors show the failing Dockerfile line with >>>; "failed to calculate checksum" means the file is not in the build context.
  • docker compose config finds YAML, key and variable mistakes before anything starts.

Next: Choosing Your Deployment Path