run.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package run
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/spf13/cobra"
  18. "github.com/docker/api/cli/options/run"
  19. "github.com/docker/api/client"
  20. "github.com/docker/api/progress"
  21. )
  22. // Command runs a container
  23. func Command() *cobra.Command {
  24. var opts run.Opts
  25. cmd := &cobra.Command{
  26. Use: "run",
  27. Short: "Run a container",
  28. Args: cobra.ExactArgs(1),
  29. RunE: func(cmd *cobra.Command, args []string) error {
  30. return runRun(cmd.Context(), args[0], opts)
  31. },
  32. }
  33. cmd.Flags().StringArrayVarP(&opts.Publish, "publish", "p", []string{}, "Publish a container's port(s). [HOST_PORT:]CONTAINER_PORT")
  34. cmd.Flags().StringVar(&opts.Name, "name", "", "Assign a name to the container")
  35. cmd.Flags().StringArrayVarP(&opts.Labels, "label", "l", []string{}, "Set meta data on a container")
  36. cmd.Flags().StringArrayVarP(&opts.Volumes, "volume", "v", []string{}, "Volume. Ex: user:key@my_share:/absolute/path/to/target")
  37. return cmd
  38. }
  39. func runRun(ctx context.Context, image string, opts run.Opts) error {
  40. c, err := client.New(ctx)
  41. if err != nil {
  42. return err
  43. }
  44. containerConfig, err := opts.ToContainerConfig(image)
  45. if err != nil {
  46. return err
  47. }
  48. err = progress.Run(ctx, func(ctx context.Context) error {
  49. return c.ContainerService().Run(ctx, containerConfig)
  50. })
  51. if err == nil {
  52. fmt.Println(opts.Name)
  53. }
  54. return err
  55. }