`.dockerignore` patterns with a leading slash (e.g. `/foo/a.py`) are not applied, so matching files are still added to the build context · Issue #2700 · docker-java/docker-java · GitHub
FilenameUtils.normalize(pattern) keeps the leading /, and getIgnores adds the pattern unchanged.
Problem
When a .dockerignore entry starts with / (e.g. /foo/a.py), the leading slash is preserved after FilenameUtils.normalize at Dockerfile.java:98 and passed on to GoLangFileMatch.match. The resulting regex is anchored on a literal / at the start, which never matches the relative file paths of the build context. As a result the pattern has no effect and the file remains in filesToAdd, even though the Docker documentation states that /foo/bar and foo/bar should exclude the same file.
[ERROR] com.github.dockerjava.core.dockerfile.DockerfileLeadingSlashIgnoreTest.leadingSlashPatternShouldExcludeFile Time elapsed: 0.003 s <<< FAILURE!
java.lang.AssertionError:
Expected: iterable with items ["Dockerfile", ".dockerignore", "b.py"] in any order
The assertion fails because a.py is not excluded and remains in filesToAdd — the exact symptom described above.
Toolchain: openjdk version "21.0.2" 2024-01-16, Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)
The control run without the test patch exits 0 on the same suite.
Already fixed in docker/docker-py
PR: docker/docker-py#1709 — "Leading slash in .dockerignore should be ignored" (merged 2017-08-15T22:40:17Z, merge commit 92a2e48e174). It strips any leading / from each .dockerignore pattern before the patterns are used for exclusion, so /foo/a.py and foo/a.py behave identically.
How docker-py fixed it:
--- a/docker/utils/build.py+++ b/docker/utils/build.py@@ -26,6 +26,7 @@ def exclude_paths(root, patterns, dockerfile=None):
if dockerfile is None:
dockerfile = 'Dockerfile'
+ patterns = [p.lstrip('/') for p in patterns]
exceptions = [p for p in patterns if p.startswith('!')]
include_patterns = [p[1:] for p in exceptions]
Activity