Reputation: 7102
I can build a simple REST API endpoint with gin
+ golang
using this tutorial:
$ go mod init translator/golang # <--- arbitrary name, right ?
go: creating new go.mod: module translator/golang
go: to add module requirements and sums:
go mod tidy # <--- yes boss !
$ go mod tidy
go: finding module for package github.com/gin-gonic/gin
go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.9.1
$ go run .
# ... omitted log messages ...
[GIN-debug] Listening and serving HTTP on localhost:5000
When I send an http GET
request everything goes fine:
# |---------------| this is my route
curl http://localhost:5000/translator/golang
[
{
"id": "1",
"title": "Blue Train", # <--- expected output of the tutorial, good !
"artist": "John Coltrane",
"price": 56.99
},
# ... omitted ...
]
When I try to "dockerize" this process, it doesn't work:
$ cat Dockerfile
FROM golang:1.21.5
COPY main.go main.go
RUN go mod init translator/golang
# RUN go mod tidy uncommenting this gives an error
EXPOSE 5000
CMD ["go", "run"]
go mod tidy
(like I did locally) I get an error$ docker build --tag host --file Dockerfile .
# ... omitted for brevity ...
=> CACHED [2/4] COPY main.go main.go 0.0s
=> CACHED [3/4] RUN go mod init translator/golang 0.0s
=> ERROR [4/4] RUN go mod tidy 0.1s
------
> [4/4] RUN go mod tidy:
0.129 $GOPATH/go.mod exists but should not
# ... omitted for brevity ...
go mod tidy
docker build
$ docker run -p 8000:5000 -d -t --name scfrontgo host
$ curl http://localhost:8000/translator/golang # <--- (from another window)
curl: (7) Failed to connect to localhost port 8000 after 5 ms: Couldn't connect to server
Upvotes: 0
Views: 591
Reputation: 7102
I think my problems originated from trying to run go mod init
inside the docker. When I looked in this docker guide, I saw that the go mod init
should be run on the local machine, then needs to be copied with COPY
. Here is the complete Dockerfile
that worked for me:
FROM golang:1.20.0
WORKDIR /app
COPY main.go ./
COPY go.mod ./
COPY go.sum ./
RUN go mod download
RUN CGO_ENABLED=0 GOOS=linux go build -o /translator
EXPOSE 5000
CMD ["/translator"]
And main.go
is similar to the tutorial except for the route mentioned in the comment by David Maze:
func main() {
router := gin.Default()
router.GET("/translator/golang", getAlbums)
router.Run("0.0.0.0:5000")
}
Upvotes: 0