1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for reply,your answer if really helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.