godocker-composedock

I got error when try to run docker-compose up -d


Im just getting started with Golang and am trying to build go gin with docker-compose. Here is my Dockerfile

FROM golang:1.18

WORKDIR /docker-go

# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
# COPY all file go ./

COPY ./app/main.go ./
COPY . /docker-go
# To initialize a project with go module, create go.mod

RUN go mod init shipping-go

# Add missing and/or remove unused modules
RUN go mod tidy

# This will bring all the vendors to your projects /vendor directory so that 
# you don't need to get the modules again if working from another machine on this project.
RUN go mod vendor

RUN go mod download && go mod verify

COPY . .
RUN go build -v -o /docker-go/app .

RUN chmod +x /docker-go
USER root

and my docker-compose

version: "3.7"
services:
  go-web:
    build:     
      context: ./
      dockerfile: Dockerfile
    restart: 'no'
    working_dir: /docker-go
    ports:
      - "8080:8080"
    entrypoint: ["./start.sh"]
    volumes:
      - ./:/docker-go

And i got error when i check logs container with command

docker logs learn-docker-go_go-web_1

/docker-go
go: cannot find main module, but found .git/config in /docker-go
    to create a module there, run:
    go mod init
/docker-go

its seem go can't find module file but i have install in Dockerfile. For Detail i push code in my repository here https://github.com/duyanh1904/learn-docker-go


Solution

  • There are multiple issues with your Dockerfile and docker-compose.yml and I have been unable to replicate the issue you are seeing (but your setup does not work for me either). A few of the problems I see are:

    Here is a working setup to get you going (this is probably not optimal but should provide a starting point that will enable you to experiment further). Note that you need to make the above change in main.go first.

    Dockerfile

    FROM golang:1.18
    
    WORKDIR /docker-go
    
    # Note: A better solution would be to copy an existing go.mod into the image
    RUN go mod init shipping-go
    COPY ./app/main.go ./
    # Determine required modules and download them
    RUN go mod tidy
    RUN go build -v -o /docker-go/app
    RUN chmod +x /docker-go/app
    

    docker-compose.yml

    version: "3.7"
    services:
      go-web:
        build:     
          dockerfile: Dockerfile
        restart: 'no'
        ports:
          - "8080:8080"
        command: ["./app"]