Rabindra
Rabindra

Reputation: 25

golang Infinite for loop problem with docker run

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

I tried to run using docker run hello, it only prints else part infinetely

Executing with console without docker go run main.go I tried to run using go run main.go and it works fine

Upvotes: 0

Views: 782

Answers (2)

Marc ABOUCHACRA
Marc ABOUCHACRA

Reputation: 3463

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

Upvotes: 2

xarantolus
xarantolus

Reputation: 2029

Scan returns an error. It is likely that no data is read and i is 0 (as that is the zero value of an int).

Change your code to panic in case of no data:

var i int
_, err := fmt.Scan(&i)
if err != nil {
    panic(err)
}

The Go playground behaves in a similar way.

Upvotes: 0

Related Questions