4

How can I achieve the equivalent of

sudo docker run -it --rm --name my-python-container -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:2-slim python test.py

using the Docker API for Golang?

Either https://github.com/fsouza/go-dockerclient or https://github.com/samalba/dockerclient is fine.

1 Answer 1

8

Using github.com/fsouza/go-dockerclient, you have to first create a container, using the CreateContainerOptions to add the same options that you can via the command line.

container, err := client.CreateContainer(createContainerOptions)

Once you have the container, you start it, with any extra options or overrides in the HostConfig

client.StartContainer(container.ID, hostConfig)

To connect to the std io streams of a container, you need to use client.AttachToContainer, and assign the appropriate stream in the AttachToContinerOptions.

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

3 Comments

Thanks! Do you by any chance have a pointer to an example of writing to stdin and capturing stdout from such a container?
@AlexFlint: Added a line about attaching to the running container. You may need to set the Stdin, Stdout, or Stderr bool flags on that call to get it to work, or the Attach* options when you create the container. I don't have a test setup at the moment to confirm what way is best, or if they differ.
The missing piece of the answer here is how to add those bind mounts asked about in the OP (-v "$PWD":/usr/src/myapp) . github.com/fsouza/go-dockerclient/issues/633 gets started on this, but doesn't end up with a satisfying answer.

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.