How to Spin up docker container & run some command via golang script?

huangapple go评论89阅读模式
英文:

How to Spin up docker container & run some command via golang script?

问题

我计划自动化创建容器并在其中运行一些命令。但是我遇到了以下错误:

docker run -it alpine sh ls

我得到的错误是:

docker错误:输入设备不是TTY。

所以我去掉了交互部分,运行了以下命令:

docker run -t alpine sh ls

我没有得到shell,但是docker正在运行。

我在golang的os.exec包中运行了上述docker命令。

package main
import (
	"fmt"
	"os"
	"os/exec"
	"sync"
)
func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		cmd := exec.Command("docker", "run","-it","alpine","sh","ls")
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Run()
		// log.Println(cmd.Run())
	}()
	wg.Wait()
}

我的意图是在启动docker后运行多个shell脚本。

如果有任何帮助,将不胜感激。谢谢。

英文:

I am planning to automate spinning up container and run some commands on it.
But I get the below error

docker run -it alpine sh ls

Error I get is

docker error : the input device is not a TTY.

So I removed interactive part and ran

docker run -t alpine sh ls

I don't get the shell but docker is spinning

I run above docker commands in golangs os.exec package.

package main
import (
	"fmt"
	"os"
	"os/exec"
	"sync"
)
func main() {
	var wg sync.WaitGroup
wg.Add(1)
	go func() {
		defer wg.Done()
		cmd := exec.Command("docker", "run","-it","alpine","sh","ls")
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Run()
		// log.Println(cmd.Run())
	}()
}()
	wg.Wait()
}

My intention is to run multiple shell scripts after spinning up the docker.

Any help would be appreciated. Thanks

答案1

得分: 2

一个可以探索的途径是使用官方的包moby/moby integration-climoby/moby integration-cli/cli with cli.go

func Docker(cmd icmd.Cmd, cmdOperators ...CmdOperator) *icmd函数用于运行docker命令,带有参数。

例如,对于docker run命令的示例:

cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "sh", "-c", "sleep 30; echo hi"))
英文:

One avenue to explore is the official packages moby/moby integration-cli and moby/moby integration-cli/cli with cli.go.

The func Docker(cmd icmd.Cmd, cmdOperators ...CmdOperator) *icmd is made to run a docker command, with parameters.

Example, for docker run:

cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "sh", "-c", "sleep 30; echo hi"))

huangapple
  • 本文由 发表于 2022年6月3日 10:44:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/72484202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定