How to debug build failures

If I’m building an image and I have a line of code in the build file that causes the build to fail, how can I interactively run that container to check the file system and etc?

Use the image IDs that docker build spits out with docker run. Notice how I run the ID from the last “good” line here.

$ echo 'from debian
env FOO=BAR
env QUUX=SPAM
run myprog
' | docker build -
Sending build context to Docker daemon 2.048 kB
Step 1 : FROM debian
 ---> 9a02f494bef8
Step 2 : ENV FOO BAR
 ---> Running in 4def0346ae9d
 ---> b6373963d411
Removing intermediate container 4def0346ae9d
Step 3 : ENV QUUX SPAM
 ---> Running in 7cdc5a97b776
 ---> a7c9a0d24fe3
Removing intermediate container 7cdc5a97b776
Step 4 : RUN myprog
 ---> Running in d590aa9618dc
/bin/sh: 1: myprog: not found
The command '/bin/sh -c myprog' returned a non-zero code: 127

$ docker run -ti a7c9a0d24fe3 env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ff5acdf0f353
TERM=xterm
FOO=BAR
QUUX=SPAM
HOME=/root

Sometimes it’s useful to inspect the filesystem of the step that failed, not just the last good step. I’ve written a guide on how to debug docker builds like that. In short, look at the container ID of the failed step, then commit that to a temporary image, then run ‘sh’ (or ‘env’ or whatever) from that temporary image.

docker commit d590aa9618dc mytempimage
docker run -ti --rm mytempimage sh

Sometimes it is also usefull to run your command with set -ex to get more information as you execute your commands and break where it fails (https://www.peterbe.com/plog/set-ex)

RUN set -ex …

T.

you can leverage image cache: start a container from the last successful step and debug you failures.
E.g.:

$ docker build -t temp .
Sending build context to Docker daemon    620kB
Step 1/3 : FROM sonarqube
 ---> a84a2ad61bb7
Step 2/3 : RUN date
 ---> Using cache
 ---> a3acfa4ab179
Step 3/3 : RUN check
 ---> Running in c294d0fc7992
/bin/sh: 1: check: not found

The last successful step is 2. It produced an image a3acfa4ab179. Now you start a container
$ docker run -it a3acfa4ab179 bash
and investigate why check not found.