7

Dockerfile

FROM node:carbon

WORKDIR /usr/src/app

COPY package*.json ./
RUN npm install
RUN npm install gulp -g

COPY . .

run gulp build --build
run npm test

EXPOSE 80
CMD [ "npm", "start" ]

Tests are ran using mocha --recursive

build.sh

docker build -t my-app .
echo $?

How can I detect that one mocha test fails, thus npm test should not be ok, and neither docker build?

I may have missed something in here.

Francois
  • 10,730
  • 7
  • 47
  • 80

3 Answers3

7

RUN in a Dockerfile will fail if the exit code of the command is non-zero. If that happens, docker build will also fail with a non-zero exit code.

Your npm test script needs to return a non-zero exit code when the tests fail.

For reference, you can check the exit code like this:

$ npm test
$ echo $?
mkasberg
  • 16,022
  • 3
  • 42
  • 46
6

You may change line run npm test to run npm test || exit 1

Ran a quick test and confirmed build is failing. Here is a screen shot.

enter image description here

Robert Ranjan
  • 1,538
  • 3
  • 19
  • 17
  • That would work if this was a shell script, but this is a Dockerfile. The build would already be failing if `npm test` was returning a failure code. – mkasberg Dec 24 '17 at 04:32
  • 1
    This worked in a dockerfile for me, to solve the opposite problem of needing docker build to continue regardless of test failures so that we can publish the test results – CurlyPaul Jun 08 '23 at 11:28
-1

I would recommend to follow some docker and node app best practices. You shouldn't build your app inside a container with npm install and run the tests inside. The build and test lifecycles can be run on a CI/CD server (e.g. TravisCI https://travis-ci.org/ or CircleCI https://circleci.com - both are free for public GitHub repositories). During your CI pipeline you can detect a failing built/test and the CI can be configured more easily to not build your image after a failure. Your bundeled app should be copied inside your docker container from an CI server and then you should only start your application inside the container.

rieckpil
  • 10,470
  • 3
  • 32
  • 56
  • 1
    yes, but in my case, node environment is not on the computer, only in the container. – Francois Dec 23 '17 at 09:38
  • With multi-layer docker builds, I think it's best to have the build inside docker for consistency, I realize this is kinda of a new feature, but this option can save you a great deal of problems of build inconsistency – lauksas Nov 12 '20 at 12:44