Skip to content
Latchkey

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.

docker
ERROR: failed to solve: cannot replace to directory /app/config with file

Common 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

  1. Give the file an explicit name inside the existing directory.
  2. Use a trailing slash on the destination so Docker treats it as a directory target.
Dockerfile
# wrong - replaces the directory:
# COPY config.yml /app/config
# right - places the file inside it:
COPY config.yml /app/config/config.yml

Remove the conflicting directory first

  1. If the path should be a file, drop the directory created earlier.
  2. Then copy the file to the now-free path.
Dockerfile
RUN rm -rf /app/config
COPY config.yml /app/config

How 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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →