I need to write a program that accepts and outputs a command line argument. It is necessary to assemble it and run it in a container. Here’s what I have:
main.go:
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 2 {
fmt.Println("arg: ", os.Args[1])
} else {
fmt.Println("no args")
}
}
Dockerfile:
FROM golang:latest
COPY . /tmp
WORKDIR /tmp
RUN go build -o app main.go
CMD [ "./app" ]
build:
sudo docker build -t test .
run:
sudo docker run test arg1
When I start, I get an error:
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "arg1": executable file not found in $PATH: unknown.
ERRO[0002] error waiting for container:
How to fix it?
2
Answers
You can use environment variables to pass the arguments given at container startup to the entrypoint of your software.
Dockerfile:
Commands:
You can also use a combination of ARG and ENV to create a default value that can be edited. Response from Alexander Mills on another thread.
Edit: I didn’t deduct from your question whether this program will be run as part of a larger process, but depending on whether you need to redirect STDOUT of the program called in the container (chain to other programs) use or omit the
-t
flag of thedocker run
command.You have two choices:
You can invoke your container like this:
sudo docker run test ./app arg1 arg2 arg3
change the last line of your Dockerfile to say this:
ENTRYPOINT [ "./app" ]
There are subtle differences between ENTRYPOINT and CMD: https://docs.docker.com/engine/reference/run/#cmd-default-command-or-options