英文:
How to take arguments at run time in docker?
问题
我对Docker非常陌生,不知道如何在运行时接收参数。我的代码如下:
package main
import (
"fmt"
// "flag"
"os"
"net/http"
"io/ioutil"
"reflect"
)
func main() {
var args string
// flag.Parse()
// args := flag.Args()
fmt.Println("输入URL:")
fmt.Scanf("%s", &args)
fmt.Println(args)
if len(args) < 1 {
fmt.Println(reflect.TypeOf(args), "请输入URL")
os.Exit(1)
}
retrieve(args)
}
func retrieve(url string) {
resp, err := http.Get(url)
if err != nil {
fmt.Println("读取错误:", err)
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取错误:", err)
return
} else {
fmt.Println(string(body))
}
}
Dockerfile如下:
FROM golang:1.7-alpine
ADD . /home
WORKDIR /home
CMD ["go","run","fetchSource.go"]
我已经注释了代码中不起作用的部分。我只想在运行时接收参数,所以我取消了那些行的注释。
英文:
I am very new to docker and i don't know how to take arguments at run time.My code looks like this:
package main
import (
"fmt"
//"flag"
"os"
"net/http"
"io/ioutil"
"reflect"
)
func main() {
var args string
// flag.Parse()
// args := flag.Args()
fmt.Println("Enter the URL : ")
fmt.Scanf("%s ",&args)
fmt.Println(args)
if len(args) < 1 {
fmt.Println(reflect.TypeOf(args),"Please Enter the URL")
os.Exit(1)
}
retrieve(args) //call the retrieve function
}
func retrieve(url string){ //gives the source code as
output.
resp, err := http.Get(url)
if err != nil{
fmt.Println("read error is:", err)
return
}
body, err := ioutil.ReadAll(resp.Body);
if err != nil{
fmt.Println("read error is:", err)
return
} else{
fmt.Println(string(body))
}
}
<br>Dockerfile looks like this:
FROM golang:1.7-alpine
ADD . /home
WORKDIR /home
CMD ["go","run","fetchSource.go"]
i have commented the code where it doesn't work.i just want to take arguments at run time so that i uncomment those lines.
答案1
得分: 1
请提供完整的命令和所有参数,例如:
docker run myimage:latest go run fetchSource.go arg1 arg2 arg3
编辑:
当你在docker run命令的末尾指定了某些内容时,你正在覆盖Dockerfile中的"Entrypoint"或"Cmd"部分。你需要指定完整的命令。
英文:
Specify the full command with all args like :
docker run myimage:latest go run fetchSource.go arg1 arg2 arg3
Edit :
When you specify something at the end of you docker run command, you're overwriting the "Entrypoint" or "Cmd" section of you Dockerfile. You have to specify the full command.
答案2
得分: 1
我已经尝试了以下Dockerfile的更改,并且也成功了。
FROM golang:1.7-alpine
ADD . /home
WORKDIR /home
# 这里首先构建了一个可执行文件
RUN ["go", "build"]
# 现在你可以运行可执行文件,并在运行时传递参数。
ENTRYPOINT ["./home"]
英文:
I have tried with the following changes in Dockerfile and it also worked.
FROM golang:1.7-alpine
ADD . /home
WORKDIR /home
# This builds a binary first
RUN ["go", "build"]
# Now you can run the executable and pass arguments at the run time.
ENTRYPOINT ["./home"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论