Home > Blockchain >  How to resolve dockerfile, and docker-compose when main go files are in nested directory?
How to resolve dockerfile, and docker-compose when main go files are in nested directory?

Time:09-22

I am very new to Docker so please forgive me, but I have a working dockerfile and docker-compose when the Main.go is at root-level but in this project the app will break if I put main.go at root.

File Structure

queue-backend
- .idea
- cmd
  - appCode
    - handler.go
    - helper.go
    - main.go
    - routes.go
- pkg
  - forms
  - models
    - mongodb
    - models.go
- tmp
.gitignore
docker-compose.yml
Dockerfile
go.mod
README.md
db
extensions

Anyway... my dockerfile looks like this

FROM golang:1.16

WORKDIR /app
COPY go.mod .
COPY go.sum .
RUN go mod download

COPY ../.. .
RUN curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

CMD ["air"]

Docker-compose.yml looks like

version: '3.9'
services:
  backend:
    build: ""
    ports:
      - 8000:8000
    volumes:
      - .:/app
    depends_on:
      - mongodb_container
  mongodb_container:
    image: mongo:latest
    environment:
      MONGO_INITDB_ROOT_USERNAME: queue-delivery
      MONGO_INITDB_ROOT_PASSWORD: password
    ports:
      - 27017:27017
    volumes:
      - mongodb_data_container:/data/db

volumes:
  mongodb_data_container:

I have tried to set WORKDIR to /app/cmd/appCode or /cmd/appCode and matching the same in the docker-compose to .:/app/cmd/appCode and .:/cmd/appCode which none work, it always returns this, or the stated paths above instead of just the '/app' path

backend_1            | no Go files in /app
backend_1            | failed to build, error: exit status 1

At this point, I'm not sure what else to try...

CodePudding user response:

To resolve Dockerfile in docker-compose.yml you need to change the build section as below

version: '3.9'
services:
    backend:
        build:
            context: .
            dockerfile: Dockerfile
        ports:
            - 8000:8000
        volumes:
            - .:/app
        depends_on:
            - mongodb_container

    mongodb_container:
        image: mongo:latest
        environment:
            MONGO_INITDB_ROOT_USERNAME: queue-delivery
            MONGO_INITDB_ROOT_PASSWORD: password
        ports:
            - 27017:27017
        volumes:
            - mongodb_data_container:/data/db

volumes:
    mongodb_data_container:

Your Dockerfile has some issues,

FROM golang:1.16

WORKDIR /app
# File changes must be added at the very end, to avoid the installation of dependencies again and again
RUN curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin
COPY go.mod .
COPY go.sum .  # can not find this file in the directory structure
RUN go mod download

COPY ../.. .  # doesn't make sense, just use COPY . .

CMD ["air"]
  • Related