container_create.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/url"
  6. "path"
  7. "github.com/docker/docker/api/types/container"
  8. "github.com/docker/docker/api/types/network"
  9. "github.com/docker/docker/api/types/versions"
  10. specs "github.com/opencontainers/image-spec/specs-go/v1"
  11. )
  12. type configWrapper struct {
  13. *container.Config
  14. HostConfig *container.HostConfig
  15. NetworkingConfig *network.NetworkingConfig
  16. }
  17. // ContainerCreate creates a new container based on the given configuration.
  18. // It can be associated with a name, but it's not mandatory.
  19. func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.ContainerCreateCreatedBody, error) {
  20. var response container.ContainerCreateCreatedBody
  21. if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
  22. return response, err
  23. }
  24. // When using API 1.24 and under, the client is responsible for removing the container
  25. if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") {
  26. hostConfig.AutoRemove = false
  27. }
  28. if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil {
  29. return response, err
  30. }
  31. query := url.Values{}
  32. if p := formatPlatform(platform); p != "" {
  33. query.Set("platform", p)
  34. }
  35. if containerName != "" {
  36. query.Set("name", containerName)
  37. }
  38. body := configWrapper{
  39. Config: config,
  40. HostConfig: hostConfig,
  41. NetworkingConfig: networkingConfig,
  42. }
  43. serverResp, err := cli.post(ctx, "/containers/create", query, body, nil)
  44. defer ensureReaderClosed(serverResp)
  45. if err != nil {
  46. return response, err
  47. }
  48. err = json.NewDecoder(serverResp.body).Decode(&response)
  49. return response, err
  50. }
  51. // formatPlatform returns a formatted string representing platform (e.g. linux/arm/v7).
  52. //
  53. // Similar to containerd's platforms.Format(), but does allow components to be
  54. // omitted (e.g. pass "architecture" only, without "os":
  55. // https://github.com/containerd/containerd/blob/v1.5.2/platforms/platforms.go#L243-L263
  56. func formatPlatform(platform *specs.Platform) string {
  57. if platform == nil {
  58. return ""
  59. }
  60. return path.Join(platform.OS, platform.Architecture, platform.Variant)
  61. }