skip to Main Content

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


  1. There is an extra dot in your build command and wrong arguments order:

    RUN go build -o app ./cmd/web/...
    
    Login or Signup to reply.
  2. Hey @Radin Khosraviani,

    copy . . will only copy the source code. You need to copy the Go module files as well.

    Below I have modified your docker file and have added COPY go.mod . COPY go.sum . RUN go mod download

    FROM golang:latest as build
    
    WORKDIR /app
    
    # Copy the Go module files
    COPY go.mod .
    COPY go.sum .
    
    # Download the Go module dependencies
    RUN go mod download
    
    COPY . .
    
    RUN go build -o /myapp ./cmd/web
     
    FROM alpine:latest as run
    
    # Copy the application executable from the build image
    COPY --from=build /myapp /myapp
    
    WORKDIR /app
    EXPOSE 8080
    CMD ["/myapp"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search