使用Golang Docker API模拟`docker run`命令

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

Emulating `docker run` using the golang docker API

问题

你可以使用Golang的Docker API来实现与以下命令等效的功能:

sudo docker run -it --rm --name my-python-container -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:2-slim python test.py

你可以选择使用以下两个库之一来实现:

英文:

How can I achieve the equivalent of

sudo docker run -it --rm --name my-python-container -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:2-slim python test.py

using the Docker API for Golang?

Either https://github.com/fsouza/go-dockerclient or https://github.com/samalba/dockerclient is fine.

答案1

得分: 8

使用github.com/fsouza/go-dockerclient,你首先需要创建一个容器,使用CreateContainerOptions来添加与命令行相同的选项。

container, err := client.CreateContainer(createContainerOptions)

一旦你有了容器,你可以使用HostConfig中的任何额外选项或覆盖来启动它

client.StartContainer(container.ID, hostConfig)

要连接到容器的标准输入输出流,你需要使用client.AttachToContainer,并在AttachToContinerOptions中分配适当的流。

请注意,以上代码是使用go-dockerclient库的示例代码,你需要根据自己的需求进行适当的修改。

英文:

Using github.com/fsouza/go-dockerclient, you have to first create a container, using the CreateContainerOptions to add the same options that you can via the command line.

container, err := client.CreateContainer(createContainerOptions)

Once you have the container, you start it, with any extra options or overrides in the HostConfig

client.StartContainer(container.ID, hostConfig)

To connect to the std io streams of a container, you need to use client.AttachToContainer, and assign the appropriate stream in the AttachToContinerOptions.

huangapple
  • 本文由 发表于 2015年6月5日 03:59:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/30653033.html
匿名

发表评论

匿名网友

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

确定