ImagePull is the Docker client operation that downloads a container image to the local machine before that image is used to create and run a container. It keeps image retrieval separate from container creation: first make the image available locally, then send configuration to ContainerCreate, and finally call ContainerStart. section 3.2 section 3.4
Using the Docker Go SDK avoids handling raw HTTP methods, status codes, and request serialization directly. A Run method calls ImagePull on its client with a context, an image name, and ImagePullOptions. The operation returns an io.ReadCloser for pull output plus an error, so both the request result and its progress messages are available to the caller. section 3.2 section 3.4
A practical pull step follows a small, explicit sequence:
- Create a context, here with context.Background(), to supply the API-call boundary. section 3.4
- Call ImagePull with the configured image name and pull options. section 3.4
- Check the returned error immediately; log it and return a DockerResult when the pull fails. section 3.4
- Copy the returned reader to standard output so command-line users can see pull activity. section 3.4
- Proceed to ContainerCreate and ContainerStart only after a successful pull. section 3.2 section 3.4
Pulling an image at the start of Run
A Docker task stores a client and configuration. Its Run method obtains a background context, pulls d.Config.Image, returns early on error, and streams the pull response to stdout: ctx := context.Background() reader, err := d.Client.ImagePull( ctx, d.Config.Image, types.ImagePullOptions{}) if err != nil { log.Printf("Error pulling image %s: %v\n", d.Config.Image, err) return DockerResult{Error: err} } io.Copy(os.Stdout, reader) For example, a task configured with the image postgres:13 performs this pull before building its container configuration and starting the resulting container. section 3.4 section 3.4
Listing 3.9 The start of our Run() method
func (d *Docker) Run() DockerResult {
ctx := context.Background()
reader, err := d.Client.ImagePull(
ctx, d.Config.Image, types.ImagePullOptions{})
if err != nil {
log.Printf("Error pulling image %s: %v\n", d.Config.Image, err)
return DockerResult{Error: err}
}
io.Copy(os.Stdout, reader)
}
This minimal Run-method opening makes the call order concrete: establish context, pull the configured image, handle failure, then expose pull output at the command line. section 3.4
ImagePull is one stage in a larger task lifecycle, not a substitute for container creation or execution. After the pull succeeds, configuration can define the image, environment, exposed ports, restart policy, and resource limits; ContainerCreate returns an ID that ContainerStart uses. Later, ContainerLogs can stream output, while ContainerStop and ContainerRemove clean up the running container. section 3.2 section 3.4
