container_create.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. "github.com/docker/docker/api/types/versions"
  9. "golang.org/x/net/context"
  10. )
  11. type configWrapper struct {
  12. *container.Config
  13. HostConfig *container.HostConfig
  14. NetworkingConfig *network.NetworkingConfig
  15. }
  16. // ContainerCreate creates a new container based in the given configuration.
  17. // It can be associated with a name, but it's not mandatory.
  18. func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) {
  19. var response container.ContainerCreateCreatedBody
  20. if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
  21. return response, err
  22. }
  23. // When using API 1.24 and under, the client is responsible for removing the container
  24. if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") {
  25. hostConfig.AutoRemove = false
  26. }
  27. query := url.Values{}
  28. if containerName != "" {
  29. query.Set("name", containerName)
  30. }
  31. body := configWrapper{
  32. Config: config,
  33. HostConfig: hostConfig,
  34. NetworkingConfig: networkingConfig,
  35. }
  36. serverResp, err := cli.post(ctx, "/containers/create", query, body, nil)
  37. if err != nil {
  38. if serverResp.statusCode == 404 && strings.Contains(err.Error(), "No such image") {
  39. return response, imageNotFoundError{config.Image}
  40. }
  41. return response, err
  42. }
  43. err = json.NewDecoder(serverResp.body).Decode(&response)
  44. ensureReaderClosed(serverResp)
  45. return response, err
  46. }