0

I'm using a docker client with golang; in the following script, I'm trying to pass an environmental variable when a container is going to start.

package main

import (
    "context"
    "fmt"
    "os/user"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "github.com/docker/docker/client"
)

func main() {
    dockerClient, _ := client.NewClientWithOpts(client.FromEnv)
    env := []string{}

    for key, value := range map[string]string{"hi": "hoo"} {
        env = append(env, fmt.Sprintf("%s=%s", key, value))
    }

    user, err := user.Current()
    if err != nil {
        fmt.Println(err)
    }

    config := container.Config{
        User:  fmt.Sprintf("%s:%s", user.Uid, user.Gid),
        Image: "675d8442a90f",
        Env:   env,
    }

    response, err := dockerClient.ContainerCreate(context.Background(), &config, nil, nil, nil, "")
    if err != nil {
        fmt.Println(err)
    }

    if err = dockerClient.ContainerStart(context.Background(), response.ID, types.ContainerStartOptions{}); err != nil {
        fmt.Println(err)
    }

}

and my docker file is a simple one which I try to echo the hi env:

# Filename: Dockerfile 
FROM ubuntu:latest
COPY . .
CMD ["echo", "$hi"]

When I built the image and passed the id to the script, it didn't echo the variable. Do you have any idea how I can use the environmental variables in the dockerfile, which are sent to the container by docker golang client?

Maryam
  • 660
  • 6
  • 19
  • Do you need to use the shell form of `CMD`, as in [Use environment variables in CMD](https://stackoverflow.com/questions/23071214/use-environment-variables-in-cmd)? – David Maze Nov 18 '22 at 16:10
  • I was thinking what David Maze said as well. make sure your docker image works as you expect when you invoke at command line with`-e hi=world`, then once you know the docker container acts like you expect, you can see if Go can do the same thing – erik258 Nov 18 '22 at 16:36

0 Answers0