lsimmons
lsimmons

Reputation: 727

Programmatically exec into docker container

I would like to write a program that allows the user to choose a running docker container which they can be given an interactive shell to. The flow of the program I would like to have is roughly the following:

  1. user runs program from bash - ./my_program
  2. user is given an interactive cli they can use to choose which docker container to exec into
  3. when user chooses container, something like docker exec -it <CONTAINER_ID> bash is run from my_program, my_program exits, and the user is transferred into a shell session of the docker container as if they had manually run docker exec -it <CONTAINER_ID> bash

I'm trying this from golang with the following code:

rv, err := exec.Command("docker", "exec", "-it", containerId, "bash").Output()
log.Infof("RV: %v", rv)
if err != nil {
    log.Errorf("Error exec-ing into container: %s", err)
}

and see the following output:

RV: []
Error exec-ing into container: exit status 1

I'm trying with err := exec.Command("docker", "exec", "-it", containerId, "bash").Run() as well and see the same error.

How might I go about creating a program like this or debugging what's currently happening?

Upvotes: 1

Views: 2278

Answers (1)

colm.anseo
colm.anseo

Reputation: 22057

Since you are launching your docker exec in interactive mode (-i) and with a tty (-t) the exec.Command needs to be provided a means for the user to send input/receive output from the tty.

To tie the cmd's stdin/stdout directly to your go process:

cmd := exec.Command("docker", "exec", "-it", containerId, "bash")

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout

err := cmd.Run()
if err != nil {
    panic(err)
}

// reached once user types `exit` from the bash shell
fmt.Println("Docker: bash console ended successfully")

Upvotes: 3

Related Questions