How to specify a directory where a Dockerfile is
2 min readNov 29, 2022
I’ve recently started learning Docker and Go. While coding, I faced a difficult problem and managed to solve it, so I’m going to summarize it.
Directory Structure
>AppName
# blah blah
>docker
>web
>Dockerfile
>docker-compose.yml
>go.mod
# blah blah
docker-compose.yml
version: '3'
services:
web:
build: ./docker/web
tty: true
command: go run .
volumes:
- .:/go/src/projects/AppName
ports:
- "3000:3000"
environment:
MYSQL_HOST: AppName_DB
networks:
- AppName_default
Dockerfile
FROM golang:latest
RUN apt-get update && apt-get install -y vim
RUN apt-get update && apt-get install -y locales \
&& sed -i -e 's/# \(ja_JP.UTF-8\)/\1/' /etc/locale.gen \
&& locale-gen \
&& update-locale LANG=ja_JP.UTF-8
RUN mkdir /AppName
WORKDIR /AppName
ADD . /AppName
RUN go get github.com/go-sql-driver/mysql
Problem
And then, I executed like below.
docker-compose up --build
However, the result was
> [7/7] RUN go get github.com/go-sql-driver/mysql:
#11 0.255 go: go.mod file not found in current directory or any parent directory.
#11 0.255 'go get' is no longer supported outside a module.
#11 0.255 To build and install a command, use 'go install' with a version,
#11 0.255 like 'go install example.com/cmd@latest'
#11 0.255 For more information, see https://golang.org/doc/go-get-install-deprecation
#11 0.255 or run 'go help get' or 'go help install'.
What did I have to do?
Reason
Dockerfile can’t refer to files in its parent directory, which means if the dockerfile is in the root directory, the bug doesn’t happen.
Answer
I had to fix docker-compose.yml.
version: '3'
services:
web:
build:
context: . #here
dockerfile: ./docker/web/Dockerfile #here
tty: true
command: go run .
volumes:
- .:/go/src/projects/AppName
ports:
- "3000:3000"
environment:
MYSQL_HOST: AppName_DB
networks:
- AppName_default
Dockerfile can be recognized as if it existed in the root directory by writing above.