Dockerfile build remove source code from final image
You can do a multi-stage build and copy the artifacts on a new image from the previous one. Also install any required runtime dependencies (if any).
FROM alpine AS builderRUN apk add --no-cache <build_dependencies>COPY source_code /tmp/source_codeRUN make -C /tmp/source_code && \ mkdir /libraries/ cp /tmp/lib/* /libraries/ rm -rf /tmp/*FROM alpineRUN apk add --no-cache <runtime_dependencies>COPY --from=builder /libraries/ /libraries/
Another way for compacting the resulting image, aside from using a multistage Docker build, is using the --squash
build option. Example image build command line:
docker image build --squash -t your-image .
When deleting files in the Docker image, the files themselves aren't truly gone, but remain in previous Docker filesystem layers, so they still take up space.
Squashing collapses all filesystem layers of your image, so files that are deleted with rm
will be removed from the resulting single layer. This is an effective way for removing the source code from your image and compacting it.
Note that, squashing in an experimental Docker feature, and has to be enabled in Docker configuration.
For more details on docker build --squash
, see: