how to set env after create container before run in go

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

how to set env after create container before run in go

问题

我想在创建Docker容器后,在运行之前将containerID设置为环境变量。
代码如下:
创建容器

ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
    panic(err)
}
resp, err := cli.ContainerCreate(ctx, &container.Config{
    Image: "alpine",
    Cmd:   []string{"echo", "hello world"},
    Tty:   false,
}, nil, nil, nil, "")
if err != nil {
    panic(err)
}

然后

一些代码来将resp.ID设置为环境变量

然后 运行容器

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
    panic(err)
}
英文:

i want to set the containerID as ENV in docker container after create before run.
the code like this:
create container

ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}
resp, err := cli.ContainerCreate(ctx, &container.Config{
		Image: "alpine",
		Cmd:   []string{"echo", "hello world"},
		Tty:   false,
	}, nil, nil, nil, "")
	if err != nil {
		panic(err)
	}

then

some code to set resp.ID as ENV

then run container

	if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
		panic(err)
	}

答案1

得分: 2

你不能这样做。Docker容器包装了一个单独的进程,当你创建容器时,必须提供启动该进程所需的所有设置(即使你实际上并没有立即启动它);这包括完整的环境设置。

在REST API级别上,无论是"启动容器"还是"更新容器"的API,都没有办法更改进程的环境或命令行。

如果你没有另外设置,容器的主机名将是其容器ID,你可以在应用程序中使用它。在Go语言中,os.Hostname()函数返回容器的主机名。如果你需要这个信息来进行日志记录,将日志元数据设置为包含主机名将实际上包含容器ID。

英文:

You can't do that. A Docker container wraps a single process, and when you create the container, you have to provide all of the settings required to start the process (even if you're not actually starting it immediately); that includes the complete environment.

At a REST API level, neither the "start a container" nor the "update a container" APIs have any way to change the process environment or command line.

If you don't otherwise set it, the container's hostname will be its container ID, and you might be able to use that in your application instead. In Go the os.Hostname() call returns that. If you need this for logging purposes, setting the log metadata to include the hostname will in practice include the container ID.

huangapple
  • 本文由 发表于 2022年5月3日 23:09:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/72101536.html
匿名

发表评论

匿名网友

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

确定