---
title: "Run the tests inside the container build · Agent Wranglers"
url: https://agentwranglers.se/playbook/engineering/build-test-and-deploy/container-build-gated-by-tests
updated: 2026-10-20
licence: "All rights reserved"
---

# Run the tests inside the container build

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Recommended
- Chapter: [Build, test and deploy](https://agentwranglers.se/playbook/engineering/build-test-and-deploy)
- Rule: Make it impossible to produce a deployable image from untested code.
- How: Use a multi-stage container build, such as a `Dockerfile`. Build and test in one stage, and run the slower tests against that build in another. Container builders such as BuildKit skip any stage the final image does not use. So the final stage copies a marker file from the test stage, and it cannot exist without passing tests. Pin each base image by digest, as the [containers chapter](https://agentwranglers.se/playbook/operations/containers/pinned-base-images) explains.
- Check: Break a test. The image does not build.

Example:

```dockerfile
# Tags keep the example short. Pin each FROM by digest, such as node:24@sha256:<digest>.
FROM node:24 AS build
WORKDIR /app
COPY . .
RUN npm ci && npm test && npm run build

FROM build AS test
RUN npm run test:e2e && touch /tests-passed

FROM build AS runtime-deps
RUN npm ci --omit=dev

FROM node:24-slim
WORKDIR /app
COPY --from=test /tests-passed /tests-passed
COPY --from=runtime-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/server ./server
USER node
CMD ["node", "server/server.js"]
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers engineering playbook: https://agentwranglers.se/playbook/engineering/build-test-and-deploy/container-build-gated-by-tests`.

- Previous: [Unit test the tricky parts](https://agentwranglers.se/playbook/engineering/build-test-and-deploy/unit-tests-for-the-tricky-parts)
- Next: [Stamp every build with its version](https://agentwranglers.se/playbook/engineering/build-test-and-deploy/version-every-release)
- [Build, test and deploy](https://agentwranglers.se/playbook/engineering/build-test-and-deploy)
