container_create.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package client
  2. import (
  3. "encoding/json"
  4. "net/url"
  5. "strings"
  6. "github.com/docker/docker/api/types/container"
  7. "github.com/docker/docker/api/types/network"
  8. "golang.org/x/net/context"
  9. )
  10. type configWrapper struct {
  11. *container.Config
  12. HostConfig *container.HostConfig
  13. NetworkingConfig *network.NetworkingConfig
  14. }
  15. // ContainerCreate creates a new container based in the given configuration.
  16. // It can be associated with a name, but it's not mandatory.
  17. func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) {
  18. var response container.ContainerCreateCreatedBody
  19. if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
  20. return response, err
  21. }
  22. query := url.Values{}
  23. if containerName != "" {
  24. query.Set("name", containerName)
  25. }
  26. body := configWrapper{
  27. Config: config,
  28. HostConfig: hostConfig,
  29. NetworkingConfig: networkingConfig,
  30. }
  31. serverResp, err := cli.post(ctx, "/containers/create", query, body, nil)
  32. if err != nil {
  33. if serverResp.statusCode == 404 && strings.Contains(err.Error(), "No such image") {
  34. return response, imageNotFoundError{config.Image}
  35. }
  36. return response, err
  37. }
  38. err = json.NewDecoder(serverResp.body).Decode(&response)
  39. ensureReaderClosed(serverResp)
  40. return response, err
  41. }