I’ve tried following the tutorials out there, but for some reason, because of how my directories are set up, I can’t seem to make a dockerfile to create a docker container for my web app so I can run it on multiple devices using docker.
Here is my project structure:
MyApp
/cmd
/web
- main.go
- middleware.go
- routes.go
/pkg
/somepackage
- somegolangfile.go
/anotherpackageIuse
- somegolangfile.go
/templates
-HTML files
go.mod
go.sum
.gitignore
Dockerfile
Here is the dockerfile I’m using:
FROM golang:latest as build
WORKDIR /build
COPY . .
RUN go build -o app .
FROM alpine:latest as run
WORKDIR /app
COPY --from=build /build/app .
ENTRYPOINT ["/app/app"]
I get the error that there are no go files in /build. This is correct and the error makes sense since the go files are in cmd/web/
However, I can’t seem to fix it. I’ve tried doing:
FROM golang:latest as build
WORKDIR /build
COPY . .
RUN go build cmd/web/ -o app .
FROM alpine:latest as run
WORKDIR /app
COPY --from=build /build/app .
ENTRYPOINT ["/app/app"]
Key difference here is that I’ve swapped out RUN go build -o app .
with RUN go build cmd/web/ -o app .
, and yet I get the error that my sum.go and mod.go are not present in the directory, which is also true
How do I make a docker container for my web app, and have it build in which my go files are in a different directory? Also, when I run my web app normally, I used go run cmd/web/*.go
in which all golang files in the cmd/web directory need to be run at the same time. Therefore, I also need my dockerfile to build and compile all the golang files together
=============================================
2
Answers
There is an extra dot in your build command and wrong arguments order:
Hey @Radin Khosraviani,
copy . .
will only copy the source code. You need to copy theGo module files
as well.Below I have modified your docker file and have added
COPY go.mod .
COPY go.sum .
RUN go mod download