golang无限for循环问题与docker run [英] golang Infinite for loop problem with docker run
问题描述
我尝试做简单的无限循环任务.不使用 docker 也能正常工作.但是当我使用 docker 时,它只会无限执行 for 循环的 else 部分.实际上可能是什么问题?docker 是否有无限 for 循环的问题?我的 main.go 文件如下所示.
主包进口 (bufio"fmt"操作系统")功能主要(){fmt.Println(你好,世界!.....")为了 {fmt.Print("->")var i intfmt.Scan(&i)如果我 == 1 {fmt.Println(你好,世界!1")} 否则如果我 == 2 {fmt.Println(你好,世界!2")} 否则如果我 == 3 {fmt.Println(你好,世界!3")} 否则如果我 == 4 {fmt.Println(你好,世界!4")} 否则如果我 == 5 {fmt.Println(你好,世界!5")} 别的 {fmt.Println("Hello, World! else")}}}
我也尝试了这些链接.
在没有 docker 的情况下使用控制台执行 go run main.go
死循环是因为你的 go 程序正在等待输入,而你没有以交互模式启动容器.
要使其工作,您需要使用此命令(注意 -it
选项):
docker 容器运行 --rm --name hello -it hello
I tried to do simple infinite for loop task. It is working fine without using docker. But when i used the docker,it only executes the else part of for loop infinitely. What may be problem actually? Is docker having problem with infinite for loop? My main.go file is shown below.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println("Hello, World!.....")
for {
fmt.Print("-> ")
var i int
fmt.Scan(&i)
if i == 1 {
fmt.Println("Hello, World! 1")
} else if i == 2 {
fmt.Println("Hello, World! 2")
} else if i == 3 {
fmt.Println("Hello, World! 3")
} else if i == 4 {
fmt.Println("Hello, World! 4")
} else if i == 5 {
fmt.Println("Hello, World! 5")
} else {
fmt.Println("Hello, World! else")
}
}
}
I tried these link as well. Read line in golang How do I break out of an infinite loop in Golang But still of no use. I am trying to solve the problem since yesterday.
The docker file is as given below:
FROM golang:1.12.0-alpine3.9
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["go","run","/app/main.go"]
I tried to build the docker using
docker build -t hello .
and run using docker run hello
Running with
docker run hello
Executing with console without docker go run main.go
The infinite loop is because your go program is waiting for an input and you're not launching the container in interactive mode.
To make it work you need to use this command (note the -it
option) :
docker container run --rm --name hello -it hello
这篇关于golang无限for循环问题与docker run的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!