Search code examples
dockerdocker-compose

docker-compose build fails with no such file or directory


I have the following docker-compose.yml

version: '3.7'
services:
  auth_api:
    build:
      dockerfile: my-server/dev.Dockerfile
      context: .
    ports:
      - '9000:3000'
    volumes:
      - ./my-server:/app/

And the following my-server/dev.Dockerfile

FROM golang:1.13.3

WORKDIR /app

RUN ls
# Copy go mod and sum files
COPY ./go.mod ./go.sum ./


# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o main .

# Expose port 8080 to the outside world
EXPOSE 3000

# Command to run the executable
CMD ["./main"]

Now, when I run

docker build my-server/ --file=my-server/dev.Dockerfile

The docker container is built successfully.

However, when I run docker-compose build, It fails with the output:

Building auth_api
Step 1/9 : FROM golang:1.13.3
 ---> dc7582e06f8e
Step 2/9 : WORKDIR /app
 ---> Using cache
 ---> c4005150884a
Step 3/9 : RUN ls
 ---> Using cache
 ---> 59051268c382
Step 4/9 : COPY ./go.mod ./go.sum ./
ERROR: Service 'auth_api' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder881802488/go.mod: no such file or directory

Any idea how to fix it?

EDIT

TBH I'm new to setting up docker-compose etc, so not really sure of how the different config options work. If there is any change I could make to my docker-compose.yml which would set the working directory for COPY, that would be best


Solution

  • The context: option in the docker-compose.yml matches the path option to docker build, except that docker build seems to strip off a file prefix if it matches the build context directory. If you're manually running

    docker build my-server/ --file=my-server/dev.Dockerfile
    #               ^^^                          ^^^
    #             context                     dockerfile
    

    then you need to change the docker-compose.yml to match

    build:
      dockerfile: dev.Dockerfile
      context: my-server
    

    All paths in the Dockerfile are relative to the context directory, so given the files you show, this would correspond to a filesystem structure like

    docker-compose.yml
    my-server/
    +-- go.mod
    +-- go.sum
    +-- dev.Dockerfile