kike
kike

Reputation: 738

Why my Dockerfile is not working with my Golang app?

I am making a web app based in Golang, and I want to reply it in Docker.

My directory is:

-Dockerfile
app/
    -main.go
    /controllers (go code)
    /core (go code)
    /domain (go code)
    /repositories (go code)
media/
    /css
    /html
    /img
    /svg

I am following this tutorial: https://levelup.gitconnected.com/complete-guide-to-create-docker-container-for-your-golang-application-80f3fb59a15e

And I have my Dockerfile as follows:

FROM golang:alpine

# Set necessary environmet variables needed for our image
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# Copy the files into the container (HTML, CSS, images...)
COPY . /media/

# Move to working directory /build
WORKDIR /app

# Copy and download dependency using go mod
COPY app/go.mod .
COPY app/go.sum .
RUN go mod download

# Copy the code into the container
COPY . .

# Build the application
RUN go build -o main .

# Copy binary from build to main folder
RUN cp /build/main .

# Export necessary port
EXPOSE 8040

# Command to run when starting the container
CMD ["/app/main"]

And when I try to build the image, I am having an error saying no Go files in /app, and I don't know why is that happening, I tried different things but I can not get it working.

I also do not understand why on the second COPY I need to put app/go.mod or app/go.sum when WORKDIR is already pointing to /app and in the tutorial it is not used, but here I need it to pass that phase in the building image.

The original project is here: https://github.com/kiketordera/full-project-go

Upvotes: 0

Views: 1322

Answers (1)

kike
kike

Reputation: 738

The root problem was that COPY media . copies the contents of media folder to /. I needed to change COPY media . to COPY media /media/. Here is the full Dockerfile solved:

FROM golang:alpine

# Set necessary environmet variables needed for our image
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# Copy the code into the container
COPY media /media/

# Move to working directory /build
WORKDIR /build

# Copy the code from /app to the build folder into the container
COPY app .

# Configure the build (go.mod and go.sum are already copied with prior step)
RUN go mod download

# Build the application
RUN go build -o main .

WORKDIR /app

# Copy binary from build to main folder
RUN cp /build/main .

# Export necessary port
EXPOSE 8080

# Command to run when starting the container
CMD ["/app/main"]

Upvotes: 1

Related Questions