Docker "failed to solve: cannot replace to directory with file" in CI
BuildKit will not silently turn a directory into a file. When a COPY or ADD resolves its destination to a path that an earlier layer already created as a directory, the overlay cannot reconcile the type change and the solve fails with cannot replace to directory with a file.
What this error means
A build fails at a COPY/ADD with cannot replace to directory with a file. The named destination exists as a directory from a prior step but the new source is a single file.
ERROR: failed to solve: cannot replace to directory /app/config with fileCommon causes
A trailing-slash mismatch on the destination
Copying a file to /app/config when /app/config/ already exists as a directory tries to overwrite the directory with a file.
An earlier step created the path as a directory
A RUN mkdir /app/config or a previous COPY of a folder claimed the path; a later file copy collides with it.
How to fix it
Copy the file into the directory, not over it
- Give the file an explicit name inside the existing directory.
- Use a trailing slash on the destination so Docker treats it as a directory target.
# wrong - replaces the directory:
# COPY config.yml /app/config
# right - places the file inside it:
COPY config.yml /app/config/config.ymlRemove the conflicting directory first
- If the path should be a file, drop the directory created earlier.
- Then copy the file to the now-free path.
RUN rm -rf /app/config
COPY config.yml /app/configHow to prevent it
- Be explicit about file vs directory destinations in COPY/ADD.
- Use a trailing slash when the target is a directory.
- Avoid creating a path as a directory then overwriting it with a file.