how to set env after create container before run in go

Viewed 50

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 Answers

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.

Related