Docker: COPY failed: file not found in build context or excluded by .dockerignore: stat go.mod

1.3k Views Asked by At

What I am trying to do: To build a docker image from inside Go/node routine

My docker file is:

FROM golang:1.18

WORKDIR /usr/src/app

COPY go.mod go.sum ./
RUN go mod download && go mod verify

COPY . .
RUN go build -v -o /usr/local/bin/app ./...

EXPOSE 3333


CMD ["app"]

It is located in the same directory where I am running the build command. docker build . works just fine.

The problem appears when I am trying to build the Dockerfile from inside of a Go module(or a node module) using docker client SDK.

Full error is:

{"stream":"Step 1/11 : FROM golang:1.18"}
{"stream":"\n"}
{"stream":" ---\u003e e3c0472b1b62\n"}
{"stream":"Step 2/11 : WORKDIR /usr/src/app"}
{"stream":"\n"}
{"stream":" ---\u003e Using cache\n"}
{"stream":" ---\u003e 6a67704c8a3f\n"}
{"stream":"Step 3/11 : RUN ls /usr/src/app"}
{"stream":"\n"}
{"stream":" ---\u003e Running in d6104ab4f79c\n"}
{"stream":"Removing intermediate container d6104ab4f79c\n"}
{"stream":" ---\u003e eddfe3069e8e\n"}
{"stream":"Step 4/11 : COPY go.mod go.sum ./"}
{"stream":"\n"}
{"errorDetail":{"message":"COPY failed: file not found in build context or excluded by .dockerignore: stat go.mod: file does not exist"},"error":"COPY failed: file not found in build context or excluded by .dockerignore: stat go.mod: file does not exist"}

Note: I have tried this with both Go-SDK and npm/dockerode module. Same error in both places.

Do I need to make changes to the dockerfile?

Go program that builds this is as follows:

func buildImage() {
    ctx := context.Background()
    dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
    if err != nil {
        panic(err)
    }
    
    tar, err := archive.TarWithOptions("./Dockerfile", &archive.TarOptions{})
    if err != nil {
        panic(err)
    }
    
    opts := types.ImageBuildOptions{
        Dockerfile:  "Dockerfile",
        Tags:        []string{"myproject" + "/fromgo"},
        Remove:      true,
    }
    res, err := dockerClient.ImageBuild(ctx, tar, opts)
    if err != nil {
        panic(err)
    }
    
    type stream struct{
        stream string
    }
    scanner := bufio.NewScanner(res.Body)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

1

There are 1 best solutions below

2
nihal On

Path to the root of the project updated. This solved the problem. Root cause may have been archive.TarWithOptions, not docker-sdk itself.

    tar, err := archive.TarWithOptions("./", &archive.TarOptions{})
    if err != nil {
        panic(err)
    }