英文:
How to run golang server in docker
问题
我使用golang设置了一个简单的服务器:
package main
import (
"golang-server/database"
"golang-server/helper"
"log"
"net/http"
)
func main() {
database.Connect()
port := helper.GetPort()
SetupRoutes()
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, router))
}
这是我的文件夹结构:
这是我的Dockerfile:
FROM golang:1.18
WORKDIR $GOPATH/src
COPY .
RUN go mod download
RUN go build -o /golang-server
EXPOSE 8080
CMD ["golang-server"]
我在主目录中运行以下Docker命令:
docker build . -t golang-server
docker run --network=golang-server --name=golang-server golang-server
然而,当我运行时出现以下错误:
docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "golang-server": executable file not found in $PATH: unknown.
我应该如何设置Dockerfile才能成功部署到Docker?
英文:
I setup a simple server with golang:
package main
import (
"golang-server/database"
"golang-server/helper"
"log"
"net/http"
)
func main() {
database.Connect()
port := helper.GetPort()
SetupRoutes()
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, router))
}
Here is what my folder structure look like:
Here is what my dockerfile look like:
FROM golang:1.18
WORKDIR $GOPATH/src
COPY . .
RUN go mod download
RUN go build -o /golang-server
EXPOSE 8080
CMD ["golang-server"]
I am running these docker commands in the main directory:
docker build . -t golang-server
docker run --network=golang-server --name=golang-server golang-server
However I am getting this error when I run:
docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "golang-server": executable file not found in $PATH: unknown.
What should I set the dockerfile so I can successfully deploy to docker?
答案1
得分: 2
问题与您Dockerfile中的最后一行相关,即CMD ["golang-server"]
。当您将其放在那里时,系统(容器内部)会尝试在您的$PATH
变量中查找名为golang-server
的可执行文件。
要解决此问题,您只需将Dockerfile中的最后一行编辑为CMD ["/golang-server"]
,因为您正在/
中构建应用程序(RUN go build -o /golang-server
)。最终的Dockerfile应该如下所示:
FROM golang:1.18
WORKDIR $GOPATH/src
COPY . .
RUN go mod download
RUN go build -o /golang-server
EXPOSE 8080
CMD ["/golang-server"]
英文:
The problem is related with your last line in Dockerfile CMD ["golang-server"]
. When you put it there, the system (inside of the container) are trying to find an executable file inside of your $PATH
variable called golang-server
.
To solve this issue, you can just edit your last line from your Dockerfile to CMD ["/golang-server"]
, once you are building your application in /
(RUN go build -o /golang-server
). The final Dockerfile should be something like:
FROM golang:1.18
WORKDIR $GOPATH/src
COPY . .
RUN go mod download
RUN go build -o /golang-server
EXPOSE 8080
CMD ["/golang-server"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论