运行在dockerfile中构建main.go

I'm trying to run go build hello.go inside a dockerfile, as

FROM golang

COPY hello.go /go/src/hello.go

RUN cd src/

RUN go build hello.go

RUN ./hello

It all goes well until the go build command, then it the following error message appears:

stat hello.go: no such file or directory
The command '/bin/sh -c go build hello.go' returned a non-zero code: 1

However, if I comment the last two commands on the dockerfile and run the created image, I can run the go build command with no problems.

Why is this happening?

Every RUN command starts a new shell with a clean environment and a new default working directory. In particular, RUN cd ... as an isolated step does nothing.

If you do actually need to change directories in a Dockerfile, either combine the two steps into one or use a WORKDIR directive to make the change more globally.

In the specific case of a Go repository, since there's a standard directory layout that's at least very strongly encouraged, I'd run with it:

FROM golang
WORKDIR /go/src/github.com/me/myprogram
COPY . ./
RUN go install .
CMD ["/go/bin/myprogram"]

(In general Go deals with whole directories or "packages" of related files, and not necessarily individual .go files.)